Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(connectors): workspace controls, Console page, agent Connections tab and server connector apps page (#899)
Laasya Bangaloreb6f28489f501
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 602043897..480090280 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,6 +45,33 @@ version of their own to them without also giving them a release of their own.### [Unreleased]#### Added+- **The server's operator sets up connector apps from the dashboard.** A+ Connectors page, beside Users and for the operator alone, sets up the+ GitHub App and Google Workspace's OAuth client (and any static client the+ catalog adds) with no restart. Each save is checked with the vendor first,+ and stored, encrypted, only if the vendor accepts it; GitHub's App name is+ read from GitHub. A secret or private key can be rotated without+ disconnecting anyone; switching to a different app says first how many+ people in how many workspaces must reconnect. The variables that set them+ today (`GITHUB_APP_CONFIG_PATH` and `GITHUB_APP_PRIVATE_KEY_PATH`,+ `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`) keep working and win over a saved+ app, and **Copy into Switch** moves one into the dashboard with nothing+ retyped. Changes are recorded in a new server-wide audit log+ (`server_audit_events`). Members of a server without an app are told to ask+ whoever runs it to add it under Connectors; `GET /service-connections`+ gains `server_setup_needed`. The page and its routes are there only with+ the `service_connections` flag on, like the rest of service connections;+ without it the page says what to turn on. A connection made under an app since removed+ can still be disconnected; the disconnect then says Switch could not revoke+ the sign-in and where to revoke it. A change reaches every switch-core+ replica within seconds, and one that missed it within half a minute. See+ `docs/old/github-app-setup.md` and `docs/old/google-workspace-setup.md`.+- **A connection knows the app it signed in through.** A connection made+ through an app the operator has since replaced shows as needing+ reconnection, and an agent asking for its token is told to reconnect+ rather than handed the vendor's refusal. A sign-in that started before the+ app was replaced is asked to start again. Connections made before this+ release are unaffected.- **Confluence through the Atlassian connection.** Connecting Atlassian nowalso asks for Confluence's read, search and (for writing) write scopes, so agranted agent reaches Confluence pages beside Jira issues. People who@@ -91,6 +118,22 @@ version of their own to them without also giving them a release of their own.and the dev environment's, follow it. A controllerrun as a service installs a release beside the one it runs and keeps the onebefore. Roll back by pointing the values at the previous release.+- **Workspace admins can switch each service off for their workspace.** With+ the `service_connections` flag on, `GET /gateway/workspace/services` lists+ every connectable service with whether the workspace has it on, who last+ changed it and when, and how many members are connected and agents granted;+ `PUT /gateway/workspace/services/{service}` with `{"enabled": false}` switches+ it off (workspace admins and owners, audited). Off, nobody in the workspace+ can start a sign-in, paste a key, connect, grant or be issued a token for it,+ and the refusal says who can turn it back on and where. A running session+ loses the service within half a minute: its grants list leaves it out, and+ its host restarts it without the service. A token already handed out may be+ used until then, except GitHub's, which is revoked before the switch+ answers. Grants are kept, so switching it on again needs no re-grant. A+ service with no setting is on, so an upgraded server behaves as before. The+ service list now says `workspace_enabled` for each service, and+ `GET /gateway/service-connections/{service}/agents` lists the caller's own+ agents with whether each holds a grant and whether others can address it.#### Changed- **Usage telemetry goes to `telemetry.switchagents.ai` by default.** The@@ -102,7 +145,24 @@ version of their own to them without also giving them a release of their own.- **Documentation links point at `docs.switchagents.ai`.** Links in the docsand the synced `docs/official` pages used `docs.flintai.dev`, the older namefor the same site. Old links still redirect.-+- **A sign-in that returns through the server goes straight back to Switch+ Console.** Google Workspace and GitHub send the browser back to the server+ rather than to the computer it left from. The server used to stop there on+ a page naming the Switch account and asking the person to continue; it now+ sends the browser on to Switch Console at once. The page remains only when+ the return cannot be verified or the consent was cancelled. What ties a+ sign-in to the browser and the Console that started it is unchanged.++- **Signing in to a service connects it without a confirm step.** Once the+ browser returns, the server exchanges the code, reads the account and keeps+ the connection in one step, and Switch Console shows the result. It used to+ hold the sign-in until the person confirmed the account in Console. The+ account is chosen at the vendor, and Disconnect undoes a wrong one. The+ flow's `complete` route now answers with the account and any warning, its+ status reads `connected` or `failed` with the reason, and the `confirm`+ route is gone, for GitHub's flow as well; a Switch Console from before this+ release cannot finish a sign-in against this server, so update both+ together. Migration `bf016e18bc16`, expand-only.#### Security- **An agent icon URL must spell its host plainly.** A link with a backslash,or a host with percent-encoding or non-ASCII characters, is refused: browsers@@ -1707,6 +1767,18 @@ version of their own to them without also giving them a release of their own.### [Unreleased]#### Added+- **The server's operator sets up connector apps in Console.** For the+ operator, the Admin page has a Connector apps section under Server, below+ the workspace's switches: the GitHub App and Google Workspace's OAuth+ client as tiles, the+ ones needing attention first, each with its state and the one thing to do+ next. A tile opens the app's page, with its client, its secret's last four+ characters or its key's fingerprint, who uses it and a check with the+ vendor; updating a secret, switching to a different app and removing it are+ in its menu. Setting one up walks through creating it at the vendor, with+ the values to paste and copy buttons, then checks and saves it in one step,+ marking the value the vendor refused. It is the dashboard's Connectors page,+ which stays for now. Needs a server from this release.- **Console follows a server that keeps names away from avatar services.** On aserver with `THIRD_PARTY_AVATARS_ENABLED=false`, Console no longer loadsDiceBear or ui-avatars.com images for that server's agents and shows their@@ -1724,6 +1796,82 @@ version of their own to them without also giving them a release of their own.- **Usage data goes to `telemetry.switchagents.ai`.** Console reported to`telemetry.flintai.dev`, an older name for the same relay that is beingretired. Only where it is sent changes; what is sent, and the opt-out, do not.+- **A sign-in comes back to Console on its own.** When the browser returns+ from a service's sign-in, Console comes to the front with the next step+ showing, and the browser's page says the sign-in is done and the tab can be+ closed. It used to stay behind the browser, with a page telling the person+ to return to it and confirm. Services whose sign-in returns through the+ server (Google Workspace, GitHub) also no longer stop on the server's+ "Continue in Switch Console" page, with a server from the same release.+- **A sign-in connects without a confirm step.** Once the browser returns,+ the server keeps the connection and Console shows the result: a service+ whose agents are added from its page opens that page with the search ready,+ and any other shows "connected" in the dialog. Console no longer asks to+ confirm the account first; the account is chosen at the vendor, and+ Disconnect undoes a wrong one. A sign-in the server refuses, such as an+ account already linked to someone else in the workspace, shows the reason in+ the dialog, and the browser's page says to look there. GitHub's sign-in+ works the same way. Needs a server from this release.+- **A connector's agents are managed on its page, the way a room's+ participants are.** The connector's page lists the agents using it as+ cards, with each agent's avatar and what runs it, under an "Agents" heading+ with the count. "Add agent" opens a search of your other agents under the+ cards, and choosing one turns the service on for it at once. Connecting a+ service now lands on its page with that search open, instead of a checklist+ in the connect dialog. An agent others can address is offered with a note+ that it would act as you. A cross on a card, shown on hover, turns the+ service off for that agent again, so one agent's access can be taken away+ without disconnecting from every agent.+- **GitHub is connected, and handed to agents, from its page like any other+ connector.** Its page has a Repositories section: one card per account the+ App is installed on, with its count, opening to a directory of names in+ columns that is searched rather than scrolled once it is long, re-read as+ the window regains focus. The section's "Choose repositories", "Change+ repositories" once there are some, goes straight to GitHub. The connect+ dialog ends with Done once GitHub is connected, the page behind already+ current; it no longer offers Back or Disconnect, which the page has. "Add+ agent" is offered for GitHub too: what every added agent gets is chosen+ above the search, and the page says so while nothing is chosen, since no+ agent can be added until something is. "Choose repositories" opens the+ choice in place: the account where there are several, the repositories as+ chips, added one by one from a search or all at once and removed with a+ cross, and whether the agent may push. An agent's own choice is changed on+ its Connections tab, whose form is the same choice in place of the account+ dropdown and checkbox list.+- **A workspace's service switches are on an Admin page.** They were a+ "Workspace" tab on the Connectors page, beside Yours and Discover. An Admin+ entry in the sidebar, shown to the workspace's admins and the server's+ operator where service connections are on, opens a page laid out like+ Settings: its sections down the side, grouped under what they reach+ ("Workspace" and the workspace's name). Its Connectors section shows the+ switches as tiles like Discover's: each service with its category, how many+ members have connected it and agents use it, and who last changed it, with+ its switch. A tile keeps its place when it flips, and switching one off+ still asks first when anyone uses it. The Connectors page has Yours and+ Discover again, with "Manage in Admin" in its header for an admin, and its+ search now fills the row.+- **Connector tools ask in approval-required and auto-accept-edits mode.**+ Calls to a granted service's tools (Jira and Confluence through Atlassian,+ Datadog, Google Workspace) used to run without asking in every mode. They now+ follow the agent's mode, as its other tools do: an approval card asks first,+ and declining tells the agent the call was refused. Full access still allows+ them, and Switch's own room tools never ask. The first such card in a session+ comes with a notice saying why. Claude Code, Codex and OpenCode cards name the+ server and tool and show what the call will send, so the text of a comment+ can be read before it is posted; a long input is cut and the card says how+ much is not shown. Codex cards can be approved for the rest of the session. A+ session started before the update keeps allowing them until it restarts.+- **A Console session in "approval required" no longer inherits your own+ Claude Code default mode.** Console now starts a Claude Code session in that+ mode with Claude Code's `default` permission mode. It used to leave the mode+ unset, so a `defaultMode` such as `auto` in your own Claude Code settings+ applied, and tools, connector tools among them, could run without the+ approval card the mode promises.+- **A session says which services it lost or gained.** When a running session+ restarts because its agent's services changed, it shows a notice naming+ them, for example "Datadog was removed from this agent's tools: it was+ switched off for the workspace, or its grant was removed." The agent is told+ the same as it resumes, so it does not look for tools it no longer has.#### Fixed- **Signing in to a service through Core works on a server whose gateway anddiff --git a/CLAUDE.md b/CLAUDE.mdindex d27f3526f..658462614 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -202,8 +202,12 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pyt- `docs/old/GATEWAY_OIDC_SETUP.md` — configuring the gateway's bring-your-ownOIDC browser sign-in (variables, redirect URI, WorkOS Connect setup)- `docs/old/google-workspace-setup.md` — offering Google Workspace on a- self-hosted server: registering the internal Google app, its redirect URI,+ self-hosted server: registering the Google app (Internal or External), its+ redirect URI, saving it under Connectors or in`GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`, and switching it off+- `docs/old/github-app-setup.md` — offering GitHub on a self-hosted server:+ creating the GitHub App, saving it under Connectors or in configuration,+ which wins, rotating its secret or key, and replacing it- `docs/old/LOCAL_DEVELOPMENT.md` — running Switch locally for development:`just` recipes, which port serves what, connecting Switch Console to alocal serverdiff --git a/console/apps/switch-console-desktop/src/main/app/deeplinks.ts b/console/apps/switch-console-desktop/src/main/app/deeplinks.tsindex 76888c31b..b9bedc9eb 100644--- a/console/apps/switch-console-desktop/src/main/app/deeplinks.ts+++ b/console/apps/switch-console-desktop/src/main/app/deeplinks.ts@@ -3,7 +3,7 @@ import { app } from 'electron';import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';import { events } from '../lib/events';import { log } from '../lib/logger';-import { getMainWindow } from './window';+import { focusMainWindow, getMainWindow } from './window';/*** Custom URL scheme Switch Console registers with the OS. Matches the scheme the@@ -61,20 +61,12 @@ function parseSessionDeeplink(rawUrl: string): ParsedDeeplink | null {return { server, agentId, roomId, sessionId };}-function focusWindow(): void {- const win = getMainWindow();- if (!win) return;- if (win.isMinimized()) win.restore();- win.show();- win.focus();-}-/** Parse, focus the app, and hand the deeplink to the renderer (or buffer it* when the renderer isn't up yet). */export function handleDeeplinkUrl(rawUrl: string): void {const parsed = parseSessionDeeplink(rawUrl);if (!parsed) return;- focusWindow();+ focusMainWindow();const win = getMainWindow();if (win && !win.webContents.isLoading()) {events.emit(sessionDeeplinkChannel, { ...parsed, coldStart: false });diff --git a/console/apps/switch-console-desktop/src/main/app/window.ts b/console/apps/switch-console-desktop/src/main/app/window.tsindex d186cc583..dd1d023ab 100644--- a/console/apps/switch-console-desktop/src/main/app/window.ts+++ b/console/apps/switch-console-desktop/src/main/app/window.ts@@ -1,5 +1,5 @@import { join } from 'node:path';-import { BrowserWindow } from 'electron';+import { app, BrowserWindow } from 'electron';import appIcon from '@/assets/images/switch-console/icon-dock.png?asset';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';@@ -133,3 +133,22 @@ function constrainEmbeddedWebviews(window: BrowserWindow): void {export function getMainWindow(): BrowserWindow | null {return mainWindow;}++/**+ * Brings Console to the front, over whatever app is there (a browser that+ * just finished a sign-in, say), and returns the window it showed, or null+ * before the window exists.+ */+export function focusMainWindow(): BrowserWindow | null {+ const win = mainWindow;+ if (!win || win.isDestroyed()) return null;+ if (win.isMinimized()) win.restore();+ win.show();+ if (process.platform === 'darwin') {+ app.focus({ steal: true });+ } else {+ app.focus();+ }+ win.focus();+ return win;+}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/notification.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/notification.tsindex d19424e1d..dc0cc6203 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/notification.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/notification.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm';-import { app, BrowserWindow, Notification } from 'electron';-import { getMainWindow } from '@main/app/window';+import { BrowserWindow, Notification } from 'electron';+import { focusMainWindow } from '@main/app/window';import { loadSessionWithAgent } from '@main/core/sessions/session-join';import { appSettingsService } from '@main/core/settings/settings-service';import { db } from '@main/db/client';@@ -13,23 +13,6 @@ import { notificationFocusSessionChannel } from '@shared/events/appEvents';const activeNotifications = new Set<Notification>();-function focusAppFromNotification(): BrowserWindow | null {- const win = getMainWindow();- if (!win || win.isDestroyed()) return null;-- if (win.isMinimized()) win.restore();- win.show();-- if (process.platform === 'darwin') {- app.focus({ steal: true });- } else {- app.focus();- }-- win.focus();- return win;-}-function getNotificationBody(event: AgentEvent): string | null {if (event.type === 'stop') return 'Your agent has finished working';if (event.type === 'notification') {@@ -71,7 +54,7 @@ export async function maybeShowNotification(event: AgentEvent, appFocused: boolenotification.on('close', releaseNotification);notification.on('failed', releaseNotification);notification.on('click', () => {- const win = focusAppFromNotification();+ const win = focusMainWindow();if (!win) return;releaseNotification();diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-skill-check.smoke.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-skill-check.smoke.test.tsindex b888bf2de..f23d84d7b 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-skill-check.smoke.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-skill-check.smoke.test.ts@@ -51,6 +51,7 @@ describe.skipIf(!RUN)('the Switch skill in an isolated OpenCode session', () =>...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),},mcpServers: {},+ connectorMcpServers: [],model: { id: MODEL },});await adapter.sendTurn({diff --git a/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.tsindex cb4e3eff2..a8bcec154 100644--- a/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/feature-flags/feature-flags-service.ts@@ -1,5 +1,6 @@import {allFeatureFlagsOff,+ FLAGS_NOT_READ_YET,type FeatureFlagKey,resolveFeatureFlags,sameFeatureFlags,@@ -54,7 +55,7 @@ export class FeatureFlagsService {serverId,flags: allFeatureFlagsOff(),fetchedAt: null,- error: 'Not read yet',+ error: FLAGS_NOT_READ_YET,});}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.tsindex 2e07896a8..520b7a4af 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -15,6 +15,10 @@ import {} from '@main/core/workspaces/workspace-session';import { listWorkspacesForServer } from '@main/core/workspaces/workspaces-store';import { log } from '@main/lib/logger';+import type {+ SaveConnectorAppInput,+ SaveConnectorAppResult,+} from '@shared/core/switch-servers/connector-apps';import {type InviteServer,SWITCH_CLOUD_NAME,@@ -64,12 +68,17 @@ import {fetchPendingInvitations,GatewayError,type RemoteTenant,+ checkConnectorApp,+ fetchConnectorAppImpact,+ fetchConnectorApps,+ importConnectorApp,+ removeConnectorApp,+ saveConnectorApp,} from './gateway-client';import { openAuthenticatedGatewayPage } from './gateway-web';import {startGitHubBrowserFlow,getGitHubBrowserFlow,- confirmGitHubBrowserFlow,cancelGitHubBrowserFlow,} from './github-browser-flow';import { deleteManagedClaudeCredential } from './managed-claude-credential';@@ -88,7 +97,6 @@ import {} from './servers-store';import {cancelServiceBrowserFlow,- confirmServiceBrowserFlow,getServiceBrowserFlow,startServiceBrowserFlow,} from './service-browser-flow';@@ -319,8 +327,6 @@ export const switchServersController = createRPCController({),getGitHubFlow: (serverId: string, id: string) =>withReachableServerWorkspaceSession(serverId, (server) => getGitHubBrowserFlow(server, id)),- confirmGitHubConnection: (serverId: string, id: string) =>- withReachableServerWorkspaceSession(serverId, (server) => confirmGitHubBrowserFlow(server, id)),cancelGitHubConnection: (serverId: string, id: string) =>withReachableServerWorkspaceSession(serverId, (server) => cancelGitHubBrowserFlow(server, id)),disconnectGitHub: (serverId: string) =>@@ -333,10 +339,6 @@ export const switchServersController = createRPCController({withReachableServerWorkspaceSession(serverId, (server) =>getServiceBrowserFlow(server, service, id)),- confirmServiceConnection: (serverId: string, service: string, id: string) =>- withReachableServerWorkspaceSession(serverId, (server) =>- confirmServiceBrowserFlow(server, service, id)- ),cancelServiceConnection: (serverId: string, service: string, id: string) =>withReachableServerWorkspaceSession(serverId, (server) =>cancelServiceBrowserFlow(server, service, id)@@ -482,6 +484,42 @@ export const switchServersController = createRPCController({clearTrustSettings: async (serverId: string): Promise<ClearTrustSettingsResult> =>clearTrustSettingsOnServer(await requireReachableServer(serverId)),+ /**+ * The apps connectors sign in through, for the server's operator: not+ * scoped to a workspace, since one app serves them all. Null when the+ * server has none to set up.+ */+ getConnectorApps: async (serverId: string) =>+ fetchConnectorApps(await requireReachableServer(serverId)),++ /** Check a connector's app with its vendor, and save it if the vendor accepts it. */+ saveConnectorApp: async (params: {+ serverId: string;+ service: string;+ input: SaveConnectorAppInput;+ }): Promise<SaveConnectorAppResult> =>+ saveConnectorApp(await requireReachableServer(params.serverId), params.service, params.input),++ /** Copy a connector's app from the server's configuration into Switch. */+ importConnectorApp: async (params: { serverId: string; service: string }) =>+ importConnectorApp(await requireReachableServer(params.serverId), params.service),++ /** Ask the vendor about the connector's app in use; nothing is stored. */+ checkConnectorApp: async (params: { serverId: string; service: string }) =>+ checkConnectorApp(await requireReachableServer(params.serverId), params.service),++ /** Who would have to reconnect if the app `clientId` names replaced the one in use. */+ getConnectorAppImpact: async (params: { serverId: string; service: string; clientId: string }) =>+ fetchConnectorAppImpact(+ await requireReachableServer(params.serverId),+ params.service,+ params.clientId+ ),++ /** Remove a connector's saved app; the connections made through it are kept. */+ removeConnectorApp: async (params: { serverId: string; service: string }) =>+ removeConnectorApp(await requireReachableServer(params.serverId), params.service),+// Reported here rather than in `auth.ts`: the same functions are used to// re-authenticate a managed server on its own and to log in while starting a// stack, and neither of those is a person signing in.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex b02e8fe1e..1f98f309e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -50,16 +50,21 @@ const {cloudMachineLifecycle,listCloudMachines,getConnectionCatalog,+ fetchConnectionAgents,fetchServiceGrants,+ fetchWorkspaceServices,+ setWorkspaceService,+ fetchConnectorApps,+ saveConnectorApp,+ fetchConnectorAppImpact,+ removeConnectorApp,removeServiceGrant,setServiceGrant,getGitHubConnection,startGitHubConnection,completeGitHubConnection,- confirmGitHubConnection,startServiceConnection,completeServiceConnection,- confirmServiceConnection,connectServiceWithKey,disconnectService,acceptInvitation,@@ -173,6 +178,33 @@ function cookieHeaderOf(call: unknown[]): string {const fetchMock = vi.fn(async () => okMeResponse());+const CONNECTOR_APP = {+ slug: 'github',+ name: 'GitHub',+ kind: 'github_app',+ source: 'saved',+ configuration_variables: ['GITHUB_CONNECTIONS_CONFIG_PATH'],+ deprecated: false,+ client_id: 'Iv1',+ saved_client_id: 'Iv1',+ fields: { slug: 'switch-example' },+ secrets: {+ client_secret: { set: true, last4: 'ab12' },+ private_key: { set: true, fingerprint: 'SHA256:abc' },+ },+ saved_ignored: false,+ unreadable: false,+ load_error: null,+ redirect_uri: 'https://switch.example.com/gateway/provider-connections/github/callback',+ setup_blocked: null,+ install_url: 'https://github.com/apps/switch-example/installations/new',+ updated_by_name: 'Ada',+ updated_at: '2026-10-16T09:00:00+00:00',+ connected_members: 3,+ workspaces: 1,+ stale_connections: 0,+};+describe('gatewayFetch proactive session renewal', () => {beforeEach(() => {vi.clearAllMocks();@@ -1052,7 +1084,7 @@ describe('GitHub connection transport', () => {getSessionCookie.mockResolvedValue(makeJwt(7200));});afterEach(() => vi.unstubAllGlobals());- it('sends objects, encoded once, for start, complete and confirm', async () => {+ it('sends objects, encoded once, for start and complete, and reads the account back', async () => {const state = 'a'.repeat(43);const input = { port: 12345, state, completion_secret: 'b'.repeat(43) };fetchMock.mockResolvedValueOnce(@@ -1064,17 +1096,18 @@ describe('GitHub connection transport', () => {));await startGitHubConnection(SERVER, input);- fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));- await completeGitHubConnection(SERVER, state, 'SYNTHETIC-CODE', input.completion_secret);- fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));- await confirmGitHubConnection(SERVER, state, input.completion_secret);+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ warning: null, login: 'example-user' }))+ );+ expect(+ await completeGitHubConnection(SERVER, state, 'SYNTHETIC-CODE', input.completion_secret)+ ).toEqual({ warning: null, login: 'example-user' });const bodies = (fetchMock.mock.calls as unknown[][]).map((call) =>JSON.parse((call[1] as RequestInit).body as string));expect(bodies).toEqual([input,{ code: 'SYNTHETIC-CODE', completion_secret: input.completion_secret },- { completion_secret: input.completion_secret },]);});it('only accepts authorization URLs on the authenticated server', async () => {@@ -1177,6 +1210,9 @@ describe('GitHub connection transport', () => {loopback_ports: null,key: null,external_identity: 'ada-gh',+ consent: 'write',+ // A server without the workspace switch: no workspace layer.+ workspace_enabled: null,},expect.objectContaining({ slug: 'jira', status: 'coming_soon', unavailable_reason: null }),expect.objectContaining({@@ -1212,6 +1248,8 @@ describe('GitHub connection transport', () => {loopback_ports: null,key: null,external_identity: null,+ consent: null,+ workspace_enabled: null,},]);const [url] = fetchMock.mock.calls.at(-1) as unknown as [string];@@ -1223,6 +1261,212 @@ describe('GitHub connection transport', () => {);await expect(getConnectionCatalog(SERVER)).rejects.toThrow();});+ it('reads whether the workspace has each service switched on', async () => {+ const entry = {+ slug: 'example',+ name: 'Example',+ category: 'Observability',+ description: 'Metrics.',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ configured: true,+ unavailable_reason: null,+ status: 'not_connected',+ consent: null,+ };+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ connections: [+ { ...entry, workspace_enabled: false },+ { ...entry, slug: 'other', workspace_enabled: true, status: 'active', consent: 'read' },+ ],+ })+ )+ );+ expect(+ (await getConnectionCatalog(SERVER)).map(({ slug, workspace_enabled, consent }) => ({+ slug,+ workspace_enabled,+ consent,+ }))+ ).toEqual([+ { slug: 'example', workspace_enabled: false, consent: null },+ { slug: 'other', workspace_enabled: true, consent: 'read' },+ ]);+ });+ it("reads the person's own agents for a service", async () => {+ const agents = [+ { agent_id: 'a1', name: 'Helper', granted: true, addressing_open: false },+ { agent_id: 'a2', name: 'Open one', granted: false, addressing_open: true },+ ];+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(agents)));+ expect(await fetchConnectionAgents(SERVER, 'google workspace')).toEqual(agents);+ expect((fetchMock.mock.calls.at(-1) as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/service-connections/google%20workspace/agents'+ );++ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify([{ agent_id: 'a1', name: 'Helper', granted: 'yes' }]))+ );+ await expect(fetchConnectionAgents(SERVER, 'example')).rejects.toThrow();++ // A server from before the list: the page says it cannot list them.+ fetchMock.mockResolvedValueOnce(new Response('{"detail":"Not Found"}', { status: 404 }));+ expect(await fetchConnectionAgents(SERVER, 'example')).toBeNull();+ fetchMock.mockResolvedValueOnce(new Response('{"detail":"boom"}', { status: 500 }));+ await expect(fetchConnectionAgents(SERVER, 'example')).rejects.toMatchObject({ status: 500 });+ });+ it("reads the workspace's switches, and none from a server without them", async () => {+ const services = [+ {+ slug: 'example',+ name: 'Example',+ enabled: false,+ updated_by_name: 'Ada',+ updated_at: '2026-01-02T03:04:05+00:00',+ connected_members: 3,+ granted_agents: 5,+ },+ {+ slug: 'other',+ name: 'Other',+ enabled: true,+ updated_by_name: null,+ updated_at: null,+ connected_members: 0,+ granted_agents: 0,+ },+ ];+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ services })));+ expect(await fetchWorkspaceServices(SERVER)).toEqual(services);+ expect((fetchMock.mock.calls.at(-1) as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/workspace/services'+ );++ // No workspace switch on this server: the page shows no workspace layer.+ fetchMock.mockResolvedValueOnce(new Response('{"detail":"Not Found"}', { status: 404 }));+ expect(await fetchWorkspaceServices(SERVER)).toBeNull();+ });+ it('raises a refusal or a failure of the switches, never an empty list', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({ detail: 'Workspace admins only.', code: 'forbidden', retryable: false }),+ { status: 403 }+ )+ );+ await expect(fetchWorkspaceServices(SERVER)).rejects.toMatchObject({+ status: 403,+ detail: 'Workspace admins only.',+ });++ fetchMock.mockResolvedValueOnce(new Response('{"detail":"boom"}', { status: 500 }));+ await expect(fetchWorkspaceServices(SERVER)).rejects.toMatchObject({ status: 500 });+ });+ it('switches a service for the workspace and keeps the warning', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({ slug: 'github', enabled: false, warning: 'Access stays a while.' })+ )+ );+ expect(await setWorkspaceService(SERVER, 'github', false)).toEqual({+ slug: 'github',+ enabled: false,+ warning: 'Access stays a while.',+ });+ const [url, init] = fetchMock.mock.calls.at(-1) as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/workspace/services/github');+ expect(init.method).toBe('PUT');+ expect(JSON.parse(String(init.body))).toEqual({ enabled: false });+ });+ it("reads the server's connector apps, and none from a server without them", async () => {+ const apps = { public_url: 'https://switch.example.com', apps: [CONNECTOR_APP] };+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ ...apps, registered: [{ slug: 'linear' }] }))+ );+ expect(await fetchConnectorApps(SERVER)).toEqual(apps);+ expect((fetchMock.mock.calls.at(-1) as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/connector-apps'+ );++ fetchMock.mockResolvedValueOnce(new Response('{"detail":"Not Found"}', { status: 404 }));+ expect(await fetchConnectorApps(SERVER)).toBeNull();++ fetchMock.mockResolvedValueOnce(new Response('{"detail":"Admins only."}', { status: 403 }));+ await expect(fetchConnectorApps(SERVER)).rejects.toMatchObject({ status: 403 });+ });+ it("answers a vendor's refusal of a save with the value to look at, and throws the rest", async () => {+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(CONNECTOR_APP)));+ expect(await saveConnectorApp(SERVER, 'github', { client_id: 'Iv1', replace: false })).toEqual({+ kind: 'saved',+ app: CONNECTOR_APP,+ });+ const [url, init] = fetchMock.mock.calls.at(-1) as unknown as [string, RequestInit];+ expect(url).toBe('https://switch.example.com/gateway/connector-apps/github');+ expect(init.method).toBe('PUT');+ expect(JSON.parse(String(init.body))).toEqual({ client_id: 'Iv1', replace: false });++ const check = {+ name: 'secret',+ ok: false,+ message: 'GitHub refused the secret.',+ field: 'client_secret',+ };+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ detail: 'GitHub refused the secret.',+ field: 'client_secret',+ checks: [check],+ }),+ { status: 422 }+ )+ );+ expect(+ await saveConnectorApp(SERVER, 'github', {+ client_id: 'Iv1',+ client_secret: 'x',+ replace: false,+ })+ ).toEqual({+ kind: 'refused',+ message: 'GitHub refused the secret.',+ field: 'client_secret',+ checks: [check],+ });++ // A 422 that is not the vendor's (a missing secret) is a failure like any other.+ fetchMock.mockResolvedValueOnce(+ new Response('{"detail":"Enter the client secret."}', { status: 422 })+ );+ await expect(+ saveConnectorApp(SERVER, 'github', { client_id: 'Iv1', replace: false })+ ).rejects.toMatchObject({ status: 422, detail: 'Enter the client secret.' });+ });+ it('asks who would reconnect, and who was connected through a removed app', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ connected_members: 4, workspaces: 2 }))+ );+ expect(await fetchConnectorAppImpact(SERVER, 'google-workspace', 'a b')).toEqual({+ connected_members: 4,+ workspaces: 2,+ });+ expect((fetchMock.mock.calls.at(-1) as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/connector-apps/google-workspace/impact?client_id=a+b'+ );++ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ connected_members: 0, workspaces: 0 }))+ );+ expect(await removeConnectorApp(SERVER, 'github')).toEqual({+ connected_members: 0,+ workspaces: 0,+ });+ expect((fetchMock.mock.calls.at(-1) as unknown as [string, RequestInit])[1].method).toBe(+ 'DELETE'+ );+ });it("reads someone else's agent's grants as none, and any other failure as one", async () => {fetchMock.mockResolvedValueOnce(new Response('{"detail":"Agent not found."}', { status: 404 }));expect(await fetchServiceGrants(SERVER, 'theirs')).toBeNull();@@ -1314,29 +1558,22 @@ describe('a service sign-in', () => {});afterEach(() => vi.unstubAllGlobals());- it('starts, completes and confirms on the service’s own routes', async () => {+ it('starts and completes on the service’s own routes, and reads the account back', async () => {answer({id: state,mode: 'loopback',url: vendor({ state, redirect_uri: 'http://127.0.0.1:12345/switch-services/callback' }),});expect((await startServiceConnection(SERVER, 'example', input)).mode).toBe('loopback');- fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));- await completeServiceConnection(SERVER, 'example', state, 'SYNTHETIC-CODE', 'b'.repeat(43));- answer({ warning: null, consent: 'write' });- expect(await confirmServiceConnection(SERVER, 'example', state, 'b'.repeat(43))).toEqual({- warning: null,- });+ answer({ warning: null, consent: 'write', account: '[email protected]' });+ expect(+ await completeServiceConnection(SERVER, 'example', state, 'SYNTHETIC-CODE', 'b'.repeat(43))+ ).toEqual({ warning: null, consent: 'write', account: '[email protected]' });const calls = fetchMock.mock.calls as unknown as [string, RequestInit][];- expect(calls.map(([url]) => url)).toEqual([- flows,- `${flows}/${state}/complete`,- `${flows}/${state}/confirm`,- ]);+ expect(calls.map(([url]) => url)).toEqual([flows, `${flows}/${state}/complete`]);expect(calls.map(([, init]) => JSON.parse(init.body as string))).toEqual([input,{ code: 'SYNTHETIC-CODE', completion_secret: 'b'.repeat(43) },- { completion_secret: 'b'.repeat(43) },]);});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex b02ccda8b..20971208d 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -18,10 +18,29 @@ import type {import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import {+ type ConnectionAgent,type ConnectionCatalogEntry,+ type WorkspaceService,+ type WorkspaceServiceChange,+ connectionAgentsSchema,connectionCatalogSchema,serviceConnectionsSchema,+ workspaceServiceChangeSchema,+ workspaceServicesSchema,} from '@shared/core/switch-servers/connection-catalog';+import {+ type ConnectorApp,+ type ConnectorAppCheckResult,+ type ConnectorAppImpact,+ type ConnectorApps,+ type SaveConnectorAppInput,+ type SaveConnectorAppResult,+ connectorAppCheckResultSchema,+ connectorAppImpactSchema,+ connectorAppRefusalSchema,+ connectorAppSchema,+ connectorAppsSchema,+} from '@shared/core/switch-servers/connector-apps';import {gitHubConnectionSchema,gitHubFlowSchema,@@ -3031,6 +3050,8 @@ export async function getConnectionCatalog(loopback_ports: entry.loopback_ports,key: entry.key,external_identity: entry.external_identity,+ consent: entry.consent,+ workspace_enabled: entry.workspace_enabled,}));}@@ -3051,10 +3072,178 @@ async function getOlderCatalog(server: SwitchServer): Promise<ConnectionCatalogEloopback_ports: null,key: null,external_identity: null,+ consent: null,+ workspace_enabled: null,})));}+/**+ * The signed-in person's own agents in the workspace, and whether each is+ * granted `service`; null when the server has no such list (a 404: it+ * predates it). Any other failure is thrown for the caller to show.+ */+export async function fetchConnectionAgents(+ server: SwitchServer,+ service: string+): Promise<ConnectionAgent[] | null> {+ let response: Response;+ try {+ response = await gatewayFetch(+ server,+ `/service-connections/${encodeURIComponent(service)}/agents`,+ { authenticated: true }+ );+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return null;+ throw cause;+ }+ return connectionAgentsSchema.parse(await response.json());+}++/**+ * Every service the workspace can switch on or off, for a workspace admin; null+ * when the server has no workspace switch (a 404: it predates it, or its+ * `service_connections` flag is off). Any other failure, a refusal included,+ * is thrown for the caller to show.+ */+export async function fetchWorkspaceServices(+ server: SwitchServer+): Promise<WorkspaceService[] | null> {+ let response: Response;+ try {+ response = await gatewayFetch(server, '/workspace/services', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return null;+ throw cause;+ }+ return workspaceServicesSchema.parse(await response.json()).services;+}++/** Switch `service` on or off for the whole workspace; workspace admins only. */+export async function setWorkspaceService(+ server: SwitchServer,+ service: string,+ enabled: boolean+): Promise<WorkspaceServiceChange> {+ const response = await gatewayFetch(+ server,+ `/workspace/services/${encodeURIComponent(service)}`,+ { authenticated: true, method: 'PUT', body: { enabled } }+ );+ return workspaceServiceChangeSchema.parse(await response.json());+}++const connectorAppPath = (service: string, rest = '') =>+ `/connector-apps/${encodeURIComponent(service)}${rest}`;++/**+ * The server's connector apps, for its operator; null when the server has+ * none to set up (a 404: it predates them, or its `service_connections` flag+ * is off). Any other failure, a refusal included, is thrown for the caller+ * to show.+ */+export async function fetchConnectorApps(server: SwitchServer): Promise<ConnectorApps | null> {+ let response: Response;+ try {+ response = await gatewayFetch(server, '/connector-apps', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return null;+ throw cause;+ }+ return connectorAppsSchema.parse(await response.json());+}++/**+ * Save a connector's app once its vendor accepts it; it takes effect at once.+ * A refusal from the vendor's check is answered, with the value to look at+ * again; any other failure is thrown.+ */+export async function saveConnectorApp(+ server: SwitchServer,+ service: string,+ input: SaveConnectorAppInput+): Promise<SaveConnectorAppResult> {+ let response: Response;+ try {+ response = await gatewayFetch(server, connectorAppPath(service), {+ authenticated: true,+ method: 'PUT',+ body: input,+ });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 422 && cause.body) {+ const refusal = connectorAppRefusalSchema.safeParse(safeJson(cause.body));+ if (refusal.success)+ return {+ kind: 'refused',+ message: refusal.data.detail,+ field: refusal.data.field,+ checks: refusal.data.checks,+ };+ }+ throw cause;+ }+ return { kind: 'saved', app: connectorAppSchema.parse(await response.json()) };+}++function safeJson(body: string): unknown {+ try {+ return JSON.parse(body);+ } catch {+ return null;+ }+}++/** Copy the app configuration sets into a saved one, so the configuration can be removed. */+export async function importConnectorApp(+ server: SwitchServer,+ service: string+): Promise<ConnectorApp> {+ const response = await gatewayFetch(server, connectorAppPath(service, '/import'), {+ authenticated: true,+ method: 'POST',+ });+ return connectorAppSchema.parse(await response.json());+}++/** Ask the vendor about the app in use; nothing is stored. */+export async function checkConnectorApp(+ server: SwitchServer,+ service: string+): Promise<ConnectorAppCheckResult> {+ const response = await gatewayFetch(server, connectorAppPath(service, '/check'), {+ authenticated: true,+ method: 'POST',+ });+ return connectorAppCheckResultSchema.parse(await response.json());+}++/** Who would have to reconnect if the app `clientId` names replaced the one in use. */+export async function fetchConnectorAppImpact(+ server: SwitchServer,+ service: string,+ clientId: string+): Promise<ConnectorAppImpact> {+ const query = new URLSearchParams({ client_id: clientId });+ const response = await gatewayFetch(server, connectorAppPath(service, `/impact?${query}`), {+ authenticated: true,+ });+ return connectorAppImpactSchema.parse(await response.json());+}++/** Remove the saved app; answers who was connected through it, and keeps their connections. */+export async function removeConnectorApp(+ server: SwitchServer,+ service: string+): Promise<ConnectorAppImpact> {+ const response = await gatewayFetch(server, connectorAppPath(service), {+ authenticated: true,+ method: 'DELETE',+ });+ return connectorAppImpactSchema.parse(await response.json());+}+/*** An agent's service grants, or null when the gateway answers that it is not* the signed-in person's agent (a 404): only its owner sees them. Any other@@ -3147,30 +3336,14 @@ export async function getGitHubFlow(server: SwitchServer, id: string) {).json());}-export async function confirmGitHubConnection(- server: SwitchServer,- id: string,- completionSecret: string-) {- const response = await gatewayFetch(- server,- `/provider-connections/github/flows/${encodeURIComponent(id)}/confirm`,- {- authenticated: true,- method: 'POST',- body: { completion_secret: completionSecret },- }- );- if (response.status === 204) return { warning: null };- return z.object({ warning: z.string().nullable() }).parse(await response.json());-}+/** Hand the code back: the server exchanges it and keeps the connection. */export async function completeGitHubConnection(server: SwitchServer,id: string,code: string,completionSecret: string) {- await gatewayFetch(+ const response = await gatewayFetch(server,`/provider-connections/github/flows/${encodeURIComponent(id)}/complete`,{@@ -3179,6 +3352,9 @@ export async function completeGitHubConnection(body: { code, completion_secret: completionSecret },});+ return z+ .object({ warning: z.string().nullable(), login: z.string() })+ .parse(await response.json());}export async function cancelGitHubConnection(server: SwitchServer, id: string) {await gatewayFetch(server, `/provider-connections/github/flows/${encodeURIComponent(id)}`, {@@ -3250,31 +3426,30 @@ export async function getServiceFlow(server: SwitchServer, service: string, id:).json());}+/** Hand the code back: the server exchanges it and keeps the connection. */export async function completeServiceConnection(server: SwitchServer,service: string,id: string,code: string,completionSecret: string-) {- await gatewayFetch(server, `${serviceFlows(service)}/${encodeURIComponent(id)}/complete`, {- authenticated: true,- method: 'POST',- body: { code, completion_secret: completionSecret },- });-}-export async function confirmServiceConnection(- server: SwitchServer,- service: string,- id: string,- completionSecret: string) {const response = await gatewayFetch(server,- `${serviceFlows(service)}/${encodeURIComponent(id)}/confirm`,- { authenticated: true, method: 'POST', body: { completion_secret: completionSecret } }+ `${serviceFlows(service)}/${encodeURIComponent(id)}/complete`,+ {+ authenticated: true,+ method: 'POST',+ body: { code, completion_secret: completionSecret },+ });- return z.object({ warning: z.string().nullable() }).parse(await response.json());+ return z+ .object({+ warning: z.string().nullable(),+ consent: z.enum(['read', 'write']),+ account: z.string(),+ })+ .parse(await response.json());}export async function cancelServiceConnection(server: SwitchServer, service: string, id: string) {await gatewayFetch(server, `${serviceFlows(service)}/${encodeURIComponent(id)}`, {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.tsindex e20187d57..9117d29e8 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.test.ts@@ -1,23 +1,23 @@import { afterEach, expect, it, vi } from 'vitest';+import { focusMainWindow } from '@main/app/window';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import {cancelGitHubConnection,completeGitHubConnection,- confirmGitHubConnection,+ getGitHubFlow,startGitHubConnection,} from './gateway-client';import {startGitHubBrowserFlow,cancelGitHubBrowserFlow,- confirmGitHubBrowserFlow,getGitHubBrowserFlow,} from './github-browser-flow';vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn() } }));+vi.mock('@main/app/window', () => ({ focusMainWindow: vi.fn() }));vi.mock('./gateway-client', () => ({cancelGitHubConnection: vi.fn(),completeGitHubConnection: vi.fn(),- confirmGitHubConnection: vi.fn(),getGitHubFlow: vi.fn(),startGitHubConnection: vi.fn(),}));@@ -29,7 +29,8 @@ afterEach(async () => {vi.resetAllMocks();});async function start() {- vi.mocked(completeGitHubConnection).mockResolvedValue(undefined);+ vi.mocked(cancelGitHubConnection).mockResolvedValue(undefined);+ vi.mocked(completeGitHubConnection).mockResolvedValue({ warning: null, login: 'example-user' });vi.mocked(startGitHubConnection).mockImplementation(async (_server, input) => ({id: input.state,url: 'https://switch.example.test/authorize',@@ -46,26 +47,35 @@ it('accepts only this Console state and keeps its secret out of the browser URL'expect(open.mock.calls[0]![0]).not.toContain(input.completion_secret);expect((await fetch(url + '?state=unknown&code=SYNTHETIC')).status).toBe(400);expect(completeGitHubConnection).not.toHaveBeenCalled();+ expect(focusMainWindow).not.toHaveBeenCalled();const response = await fetch(url + `?state=${id}&code=SYNTHETIC`);expect(response.status).toBe(200);expect(response.headers.get('referrer-policy')).toBe('no-referrer');- expect(await response.text()).toContain('Return to Switch Console');+ expect(await response.text()).toContain('Signed in to GitHub, and connected to Switch.');+ expect(focusMainWindow).toHaveBeenCalledOnce();expect(completeGitHubConnection).toHaveBeenCalledExactlyOnceWith(server,id,'SYNTHETIC',input.completion_secret);- await confirmGitHubBrowserFlow(server, id);- expect(confirmGitHubConnection).toHaveBeenCalledExactlyOnceWith(- server,- id,- input.completion_secret- );+});++it('ends the flow once it reads connected, and tells the server to drop it', async () => {+ const { id } = await start();+ vi.mocked(getGitHubFlow).mockResolvedValue({+ status: 'connected',+ login: 'example-user',+ error: null,+ warning: null,+ });+ expect((await getGitHubBrowserFlow(server, id)).login).toBe('example-user');+ expect(cancelGitHubConnection).toHaveBeenCalledWith(server, id);+ await expect(getGitHubBrowserFlow(server, id)).rejects.toThrow('Sign-in was interrupted');});it('refuses unknown local flows and displays a failed completion', async () => {- await expect(confirmGitHubBrowserFlow(server, 'unknown')).rejects.toThrow(+ await expect(getGitHubBrowserFlow(server, 'unknown')).rejects.toThrow('Sign-in was interrupted. Start it again from Switch Console.');const { id, url } = await start();@@ -104,14 +114,6 @@ it('expires the local secret even after the callback was received', async () =>const { id, url } = await start();expect((await fetch(url + `?state=${id}&code=SYNTHETIC`)).status).toBe(200);await vi.advanceTimersByTimeAsync(600_000);- await expect(confirmGitHubBrowserFlow(server, id)).rejects.toThrow('Sign-in was interrupted');- expect(confirmGitHubConnection).not.toHaveBeenCalled();-});--it('keeps a failed confirmation available for retry until its deadline', async () => {- const { id } = await start();- vi.mocked(confirmGitHubConnection).mockRejectedValueOnce(new Error('Temporary failure'));- await expect(confirmGitHubBrowserFlow(server, id)).rejects.toThrow('Temporary failure');- await confirmGitHubBrowserFlow(server, id);- expect(confirmGitHubConnection).toHaveBeenCalledTimes(2);+ await expect(getGitHubBrowserFlow(server, id)).rejects.toThrow('Sign-in was interrupted');+ expect(getGitHubFlow).not.toHaveBeenCalled();});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.tsindex 534568b55..e8be6ea3e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/github-browser-flow.ts@@ -1,14 +1,13 @@import { randomBytes } from 'node:crypto';-import { createServer } from 'node:http';import { log } from '@main/lib/logger';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import {cancelGitHubConnection,completeGitHubConnection,- confirmGitHubConnection,getGitHubFlow,startGitHubConnection,} from './gateway-client';+import { listenForSignIn } from './sign-in-listener';const active = new Map<string, { secret: string; close: () => void }>();const key = (server: SwitchServer, id: string) => JSON.stringify([server.id, id]);@@ -19,60 +18,21 @@ export async function startGitHubBrowserFlow(): Promise<string> {const state = randomBytes(32).toString('base64url');const secret = randomBytes(32).toString('base64url');- let received = false;- let port = 0;- const listener = createServer((request, response) => {- response.setHeader('Cache-Control', 'no-store');- response.setHeader('Referrer-Policy', 'no-referrer');- response.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");- response.setHeader('Content-Type', 'text/html; charset=utf-8');- let url: URL;- try {- url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);- } catch {- response.writeHead(400);- response.end('Invalid authorization response.');- return;- }- const code = url.searchParams.get('code');- if (- received ||- request.method !== 'GET' ||- url.origin !== `http://127.0.0.1:${port}` ||- request.headers.host !== `127.0.0.1:${port}` ||- url.pathname !== '/switch-github/callback' ||- url.searchParams.get('state') !== state ||- !code ||- code.length > 512- ) {- response.writeHead(400);- response.end(- 'This connection was not started by this Switch Console. Return to the computer where you started it.'- );- return;- }- received = true;- listener.close();- void completeGitHubConnection(server, state, code, secret)- .then(() => {- response.end('GitHub authorized. Return to Switch Console to confirm the account.');- })- .catch(() => {+ const listener = await listenForSignIn({+ name: 'GitHub',+ path: '/switch-github/callback',+ state,+ maxCodeLength: 512,+ ports: null,+ complete: async (code) => {+ try {+ await completeGitHubConnection(server, state, code, secret);+ } catch (error) {active.delete(key(server, state));- response.writeHead(400);- response.end('Sign-in was interrupted. Start it again from Switch Console.');- });- });- await new Promise<void>((resolve, reject) => {- listener.once('error', reject);- listener.listen(0, '127.0.0.1', resolve);+ throw error;+ }+ },});- const address = listener.address();- if (!address || typeof address === 'string') {- listener.close();- throw new Error('Could not open the local GitHub callback.');- }- port = address.port;const timeout = setTimeout(() => {active.delete(key(server, state));listener.close();@@ -88,7 +48,11 @@ export async function startGitHubBrowserFlow(active.set(key(server, state), entry);let started = false;try {- const flow = await startGitHubConnection(server, { port, state, completion_secret: secret });+ const flow = await startGitHubConnection(server, {+ port: listener.port,+ state,+ completion_secret: secret,+ });started = true;if (flow.id !== state) throw new Error('The GitHub authorization does not match this Console.');try {@@ -111,19 +75,23 @@ export async function startGitHubBrowserFlow(}}+/**+ * Where the sign-in stands. Once it reads connected the flow is over: the+ * listener and secret go, and the server is told it can drop the flow. A+ * failed flow stays until the person cancels it, so the reason stays readable.+ */export async function getGitHubBrowserFlow(server: SwitchServer, id: string) {const entry = active.get(key(server, id));if (!entry) throw new Error('Sign-in was interrupted. Start it again from Switch Console.');- return getGitHubFlow(server, id);-}--export async function confirmGitHubBrowserFlow(server: SwitchServer, id: string) {- const entry = active.get(key(server, id));- if (!entry) throw new Error('Sign-in was interrupted. Start it again from Switch Console.');- const result = await confirmGitHubConnection(server, id, entry.secret);- entry.close();- active.delete(key(server, id));- return result;+ const flow = await getGitHubFlow(server, id);+ if (flow.status === 'connected') {+ entry.close();+ active.delete(key(server, id));+ cancelGitHubConnection(server, id).catch((cause: unknown) =>+ log.warn('Could not drop a finished GitHub sign-in', cause)+ );+ }+ return flow;}export async function cancelGitHubBrowserFlow(server: SwitchServer, id: string) {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.tsindex 0dadaffc2..e334fc31e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.test.ts@@ -1,26 +1,26 @@import { createServer, type Server } from 'node:http';import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { focusMainWindow } from '@main/app/window';import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import {cancelServiceConnection,completeServiceConnection,- confirmServiceConnection,getConnectionCatalog,+ getServiceFlow,startServiceConnection,} from './gateway-client';import {cancelServiceBrowserFlow,- confirmServiceBrowserFlow,getServiceBrowserFlow,startServiceBrowserFlow,} from './service-browser-flow';vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn() } }));+vi.mock('@main/app/window', () => ({ focusMainWindow: vi.fn() }));vi.mock('./gateway-client', () => ({cancelServiceConnection: vi.fn(),completeServiceConnection: vi.fn(),- confirmServiceConnection: vi.fn(),getConnectionCatalog: vi.fn(),getServiceFlow: vi.fn(),startServiceConnection: vi.fn(),@@ -45,6 +45,8 @@ function listed(ports: number[] | null): ConnectionCatalogEntry[] {loopback_ports: ports,key: null,external_identity: null,+ consent: null,+ workspace_enabled: null,},];}@@ -57,7 +59,12 @@ afterEach(async () => {vi.resetAllMocks();});async function start(service = 'example') {- vi.mocked(completeServiceConnection).mockResolvedValue(undefined);+ vi.mocked(cancelServiceConnection).mockResolvedValue(undefined);+ vi.mocked(completeServiceConnection).mockResolvedValue({+ warning: null,+ consent: 'write',+ account: '[email protected]',+ });vi.mocked(startServiceConnection).mockImplementation(async (_server, _service, input) => ({id: input.state,url: 'https://auth.example.test/authorize',@@ -80,10 +87,12 @@ it('takes back only this Console’s state, and hands the code to Core with its.status).toBe(400);expect(completeServiceConnection).not.toHaveBeenCalled();+ expect(focusMainWindow).not.toHaveBeenCalled();const response = await fetch(url + `?state=${id}&code=SYNTHETIC`);expect(response.status).toBe(200);expect(response.headers.get('referrer-policy')).toBe('no-referrer');- expect(await response.text()).toContain('Return to Switch Console');+ expect(await response.text()).toContain('Signed in to Example, and connected to Switch.');+ expect(focusMainWindow).toHaveBeenCalledOnce();expect(completeServiceConnection).toHaveBeenCalledExactlyOnceWith(server,'example',@@ -91,15 +100,46 @@ it('takes back only this Console’s state, and hands the code to Core with its'SYNTHETIC',input.completion_secret);- await confirmServiceBrowserFlow(server, 'example', id);- expect(confirmServiceConnection).toHaveBeenCalledExactlyOnceWith(- server,- 'example',- id,- input.completion_secret+});++it('ends the flow once it reads connected, and tells the server to drop it', async () => {+ const { id } = await start();+ vi.mocked(getServiceFlow).mockResolvedValue({+ status: 'pending',+ account: null,+ error: null,+ warning: null,+ });+ expect((await getServiceBrowserFlow(server, 'example', id)).status).toBe('pending');+ expect(cancelServiceConnection).not.toHaveBeenCalled();+ vi.mocked(getServiceFlow).mockResolvedValue({+ status: 'connected',+ account: '[email protected]',+ error: null,+ warning: 'Access stays a while.',+ });+ expect((await getServiceBrowserFlow(server, 'example', id)).warning).toBe(+ 'Access stays a while.'+ );+ expect(cancelServiceConnection).toHaveBeenCalledWith(server, 'example', id);+ await expect(getServiceBrowserFlow(server, 'example', id)).rejects.toThrow(+ 'Sign-in was interrupted');});+it('keeps a failed flow readable until the person cancels it', async () => {+ const { id } = await start();+ vi.mocked(getServiceFlow).mockResolvedValue({+ status: 'failed',+ account: null,+ error: 'This Example account is already linked to another Switch user in this workspace.',+ warning: null,+ });+ expect((await getServiceBrowserFlow(server, 'example', id)).status).toBe('failed');+ expect((await getServiceBrowserFlow(server, 'example', id)).status).toBe('failed');+ expect(cancelServiceConnection).not.toHaveBeenCalled();+});+it('takes back a code as long as a vendor issues, and nothing absurdly long', async () => {// Atlassian's codes are signed tokens: 2,177 characters in a live sign-in.const { id, input, url } = await start();@@ -117,18 +157,20 @@ it('takes back a code as long as a vendor issues, and nothing absurdly long', asit('keys each flow by its service', async () => {const { id } = await start('example');- await expect(confirmServiceBrowserFlow(server, 'other', id)).rejects.toThrow(+ await expect(getServiceBrowserFlow(server, 'other', id)).rejects.toThrow('Sign-in was interrupted');- expect(confirmServiceConnection).not.toHaveBeenCalled();+ expect(getServiceFlow).not.toHaveBeenCalled();});-it('does not show Core’s failure in the browser, and ends the flow', async () => {+it('does not show Core’s refusal in the browser, and sends the person to Console', async () => {const { id, url } = await start();vi.mocked(completeServiceConnection).mockRejectedValue(new Error('Private server detail'));const response = await fetch(url + `?state=${id}&code=SYNTHETIC`);expect(response.status).toBe(400);- expect(await response.text()).not.toContain('Private server detail');+ const text = await response.text();+ expect(text).not.toContain('Private server detail');+ expect(text).toContain('Switch Console says what happened');});it('closes the listener when the person cancels', async () => {@@ -161,10 +203,10 @@ it('expires the local secret after ten minutes', async () => {const { id, url } = await start();expect((await fetch(url + `?state=${id}&code=SYNTHETIC`)).status).toBe(200);await vi.advanceTimersByTimeAsync(600_000);- await expect(confirmServiceBrowserFlow(server, 'example', id)).rejects.toThrow(+ await expect(getServiceBrowserFlow(server, 'example', id)).rejects.toThrow('Sign-in was interrupted');- expect(confirmServiceConnection).not.toHaveBeenCalled();+ expect(getServiceFlow).not.toHaveBeenCalled();});/** Something else holding `port` on loopback, as another app might. */diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.tsindex 3a86579fe..56dfa1d6f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/service-browser-flow.ts@@ -1,26 +1,22 @@import { randomBytes } from 'node:crypto';-import { createServer, type Server } from 'node:http';import { log } from '@main/lib/logger';import { SERVICE_CALLBACK_PATH } from '@shared/core/switch-servers/service-connection';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import {cancelServiceConnection,completeServiceConnection,- confirmServiceConnection,getConnectionCatalog,getServiceFlow,startServiceConnection,} from './gateway-client';+import { listenForSignIn } from './sign-in-listener';/*** Signing in to a service through Switch's generic OAuth flow, from this* Console: GitHub's browser flow (`github-browser-flow.ts`) for any service,- * keyed by its slug.- *- * A listener on 127.0.0.1 takes the code back, whether the vendor redirects- * to it directly or Core relays it after its own callback, and hands it to- * Core with the completion secret only this Console holds. Neither the- * listener nor the browser ever sees a token: Core exchanges the code.+ * keyed by its slug. The listener takes the code back and hands it to Core+ * with the completion secret only this Console holds; Core connects the+ * service in that step, and the renderer reads the outcome from the flow.*//** Some vendors issue codes as signed tokens: Atlassian's run past 2,000 characters. */const MAX_CODE_LENGTH = 8192;@@ -35,59 +31,19 @@ export async function startServiceBrowserFlow(): Promise<string> {const state = randomBytes(32).toString('base64url');const secret = randomBytes(32).toString('base64url');- let received = false;- let port = 0;- const listener = createServer((request, response) => {- response.setHeader('Cache-Control', 'no-store');- response.setHeader('Referrer-Policy', 'no-referrer');- response.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");- response.setHeader('Content-Type', 'text/html; charset=utf-8');- let url: URL;- try {- url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);- } catch {- response.writeHead(400);- response.end('Invalid sign-in response.');- return;- }- const code = url.searchParams.get('code');- if (- received ||- request.method !== 'GET' ||- url.origin !== `http://127.0.0.1:${port}` ||- request.headers.host !== `127.0.0.1:${port}` ||- url.pathname !== SERVICE_CALLBACK_PATH ||- url.searchParams.get('state') !== state ||- !code ||- code.length > MAX_CODE_LENGTH- ) {- response.writeHead(400);- response.end(- 'This connection was not started by this Switch Console. Return to the computer where you started it.'- );- return;- }- received = true;- listener.close();- void completeServiceConnection(server, service, state, code, secret)- .then(() => {- response.end('Signed in. Return to Switch Console to confirm the account.');- })- .catch(() => {- response.writeHead(400);- response.end('Sign-in was interrupted. Start it again from Switch Console.');- });- });const catalogEntry = (await getConnectionCatalog(server)).find((candidate) => candidate.slug === service);- await listenOn(listener, catalogEntry?.name ?? service, catalogEntry?.loopback_ports ?? null);- const address = listener.address();- if (!address || typeof address === 'string') {- listener.close();- throw new Error('Could not open the local sign-in callback.');- }- port = address.port;+ const listener = await listenForSignIn({+ name: catalogEntry?.name ?? service,+ path: SERVICE_CALLBACK_PATH,+ state,+ maxCodeLength: MAX_CODE_LENGTH,+ ports: catalogEntry?.loopback_ports ?? null,+ complete: async (code) => {+ await completeServiceConnection(server, service, state, code, secret);+ },+ });const timeout = setTimeout(() => {active.delete(key(server, service, state));listener.close();@@ -104,7 +60,7 @@ export async function startServiceBrowserFlow(let started = false;try {const flow = await startServiceConnection(server, service, {- port,+ port: listener.port,state,completion_secret: secret,});@@ -129,47 +85,28 @@ export async function startServiceBrowserFlow(}}-/**- * Listen on loopback: on any port, or on the first free one of `ports`, for a- * vendor that takes a sign-in back only on the ports Switch registered.- */-async function listenOn(listener: Server, name: string, ports: number[] | null) {- for (const port of ports ?? [0]) {- try {- await new Promise<void>((resolve, reject) => {- listener.once('error', reject);- listener.listen(port, '127.0.0.1', () => {- listener.off('error', reject);- resolve();- });- });- return;- } catch (error) {- if (ports === null || (error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;- }- }- throw new Error(- `${name} takes a sign-in back only on port ${(ports ?? []).join(', ')} of this computer, and all are in use. Close whatever is using them, and connect again.`- );-}-function activeFlow(server: SwitchServer, service: string, id: string) {const entry = active.get(key(server, service, id));if (!entry) throw new Error('Sign-in was interrupted. Start it again from Switch Console.');return entry;}+/**+ * Where the sign-in stands. Once it reads connected the flow is over: the+ * listener and secret go, and the server is told it can drop the flow. A+ * failed flow stays until the person cancels it, so the reason stays readable.+ */export async function getServiceBrowserFlow(server: SwitchServer, service: string, id: string) {- activeFlow(server, service, id);- return getServiceFlow(server, service, id);-}--export async function confirmServiceBrowserFlow(server: SwitchServer, service: string, id: string) {const entry = activeFlow(server, service, id);- const result = await confirmServiceConnection(server, service, id, entry.secret);- entry.close();- active.delete(key(server, service, id));- return result;+ const flow = await getServiceFlow(server, service, id);+ if (flow.status === 'connected') {+ entry.close();+ active.delete(key(server, service, id));+ cancelServiceConnection(server, service, id).catch((cause: unknown) =>+ log.warn('Could not drop a finished service sign-in', cause)+ );+ }+ return flow;}export async function cancelServiceBrowserFlow(server: SwitchServer, service: string, id: string) {diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/sign-in-listener.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/sign-in-listener.tsnew file mode 100644index 000000000..db321be6c--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/sign-in-listener.ts@@ -0,0 +1,133 @@+import { createServer, type Server } from 'node:http';+import { focusMainWindow } from '@main/app/window';++/**+ * The listener on 127.0.0.1 that takes a sign-in's code back to this Console,+ * for every service's browser flow. The vendor sends the browser to it+ * directly, or Core does from its own callback. It takes one code, for the+ * state it was opened with, brings Console to the front so the next step is+ * in view, and hands the code to Core through `complete`. Neither it nor the+ * browser ever sees a token: Core exchanges the code.+ */+export type SignInListener = {+ port: number;+ close: () => void;+};++export async function listenForSignIn({+ name,+ path,+ state,+ maxCodeLength,+ ports,+ complete,+}: {+ /** The service, as the browser's page names it. */+ name: string;+ path: string;+ state: string;+ maxCodeLength: number;+ /** The ports the vendor takes a sign-in back on, or null for any. */+ ports: number[] | null;+ /** Hands the code to Core; what the browser is shown follows its outcome. */+ complete: (code: string) => Promise<void>;+}): Promise<SignInListener> {+ let received = false;+ let port = 0;+ const listener = createServer((request, response) => {+ const reply = (status: number, message: string) => {+ response.writeHead(status, {+ 'Cache-Control': 'no-store',+ 'Referrer-Policy': 'no-referrer',+ 'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'",+ 'Content-Type': 'text/html; charset=utf-8',+ });+ response.end(page(name, message));+ };+ let url: URL;+ try {+ url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);+ } catch {+ reply(400, 'Invalid sign-in response.');+ return;+ }+ const code = url.searchParams.get('code');+ if (+ received ||+ request.method !== 'GET' ||+ url.origin !== `http://127.0.0.1:${port}` ||+ request.headers.host !== `127.0.0.1:${port}` ||+ url.pathname !== path ||+ url.searchParams.get('state') !== state ||+ !code ||+ code.length > maxCodeLength+ ) {+ reply(+ 400,+ 'This connection was not started by this Switch Console. Return to the computer where you started it.'+ );+ return;+ }+ received = true;+ listener.close();+ focusMainWindow();+ void complete(code).then(+ () => reply(200, `Signed in to ${name}, and connected to Switch. This tab can be closed.`),+ () =>+ reply(+ 400,+ `Switch could not finish signing in to ${name}. Switch Console says what happened.`+ )+ );+ });+ await listenOn(listener, name, ports);+ const address = listener.address();+ if (!address || typeof address === 'string') {+ listener.close();+ throw new Error('Could not open the local sign-in callback.');+ }+ port = address.port;+ return { port, close: () => listener.close() };+}++/**+ * Listen on loopback: on any port, or on the first free one of `ports`, for a+ * vendor that takes a sign-in back only on the ports Switch registered.+ */+async function listenOn(listener: Server, name: string, ports: number[] | null): Promise<void> {+ for (const port of ports ?? [0]) {+ try {+ await new Promise<void>((resolve, reject) => {+ listener.once('error', reject);+ listener.listen(port, '127.0.0.1', () => {+ listener.off('error', reject);+ resolve();+ });+ });+ return;+ } catch (error) {+ if (ports === null || (error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;+ }+ }+ throw new Error(+ `${name} takes a sign-in back only on port ${(ports ?? []).join(', ')} of this computer, and all are in use. Close whatever is using them, and connect again.`+ );+}++function page(name: string, message: string): string {+ const title = escapeHtml(`Switch · ${name}`);+ return (+ '<!doctype html><html lang=en><meta charset=utf-8>' ++ "<meta name=viewport content='width=device-width'>" ++ `<title>${title}</title><body><main><h1>${title}</h1><p>${escapeHtml(message)}</p></main></body></html>`+ );+}++function escapeHtml(text: string): string {+ return text+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''');+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.tsindex b5e39443e..6c3bc67e9 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts@@ -18,6 +18,18 @@ const getSessionCookie = vi.hoisted(() => vi.fn());const requireWorkspace = vi.hoisted(() => vi.fn());const listWorkspacesForServer = vi.hoisted(() => vi.fn(async () => [{ id: 'ws' }]));const switchTenant = vi.hoisted(() => vi.fn());+const fetchConnectionAgents = vi.hoisted(() => vi.fn());+const fetchWorkspaceServices = vi.hoisted(() => vi.fn());+const setWorkspaceService = vi.hoisted(() => vi.fn());+const connectServiceWithKey = vi.hoisted(() => vi.fn());+const disconnectService = vi.hoisted(() => vi.fn());+const disconnectGitHub = vi.hoisted(() => vi.fn());+const serviceBrowserFlow = vi.hoisted(() => ({+ startServiceBrowserFlow: vi.fn(),+ getServiceBrowserFlow: vi.fn(),+ cancelServiceBrowserFlow: vi.fn(),+}));+const openExternal = vi.hoisted(() => vi.fn());// Stubbed rather than reimplemented: what the tests below assert is that the// kind reaches the event, not how a row is read as one.const serverKindOf = vi.hoisted(() => vi.fn(() => 'remote_managed'));@@ -48,6 +60,8 @@ vi.mock('@main/lib/logger', () => ({log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },}));// Reads this install's own agent rows, and through them the database client.+vi.mock('@main/core/app/service', () => ({ appService: { openExternal } }));+vi.mock('@main/core/switch-servers/service-browser-flow', () => serviceBrowserFlow);vi.mock('@main/core/switch-servers/backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));vi.mock('@main/core/switch-servers/bridge-home-url', () => ({ withResolvedHomeUrls: vi.fn() }));vi.mock('@main/core/switch-servers/create-bridge', () => ({ createBridgeOnServer: vi.fn() }));@@ -66,6 +80,9 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({addBridgeTeam,addRoomAgents: vi.fn(),agentExistsOnServer: vi.fn(),+ connectServiceWithKey,+ disconnectGitHub,+ disconnectService,createRoomFromTemplate: vi.fn(),decodeJwtTenantId: vi.fn(() => null),deleteRoom,@@ -77,6 +94,8 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({fetchBridges,fetchBridgeTeams,fetchBridgeTypes: vi.fn(),+ fetchConnectionAgents,+ fetchWorkspaceServices,fetchMyIdentities: vi.fn(),fetchRoomAgentIds: vi.fn(),fetchRoomDetail: vi.fn(),@@ -89,6 +108,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({releaseBridgeIdentity: vi.fn(),removeBridgeTeam,removeRoomAgent: vi.fn(),+ setWorkspaceService,switchTenant,updateAddressingPolicy: vi.fn(),updateAgentIcon: vi.fn(),@@ -369,6 +389,86 @@ describe('selecting the workspace’s tenant before the call', () => {expect(getSessionCookie).not.toHaveBeenCalled();});+ it('reads and switches the services of the workspace named, not the active one', async () => {+ const { decodeJwtTenantId } = await import('@main/core/switch-servers/gateway-client');+ vi.mocked(decodeJwtTenantId).mockReturnValue('tenant-a');+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));+ getSessionCookie.mockResolvedValue('cookie-for-tenant-a');+ // Each call is only answered once the session selects the named workspace.+ const selected = () => {+ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tenant-b');+ return Promise.resolve(null);+ };+ fetchConnectionAgents.mockImplementation(selected);+ fetchWorkspaceServices.mockImplementation(selected);+ setWorkspaceService.mockImplementation(selected);++ await workspacesController.getConnectionAgents({ workspaceId: 'ws', service: 'example' });+ await workspacesController.getWorkspaceServices('ws');+ await workspacesController.setWorkspaceService({+ workspaceId: 'ws',+ service: 'example',+ enabled: false,+ });++ expect(fetchConnectionAgents).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srv' }),+ 'example'+ );+ expect(fetchWorkspaceServices).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }));+ expect(setWorkspaceService).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srv' }),+ 'example',+ false+ );+ });++ it('connects, signs in and disconnects in the workspace named, not the active one', async () => {+ const { decodeJwtTenantId } = await import('@main/core/switch-servers/gateway-client');+ vi.mocked(decodeJwtTenantId).mockReturnValue('tenant-a');+ requireWorkspace.mockResolvedValue(workspace('tenant-b'));+ getSessionCookie.mockResolvedValue('cookie-for-tenant-a');+ const selected = () => {+ expect(switchTenant).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'tenant-b');+ return Promise.resolve(null);+ };+ for (const call of [+ connectServiceWithKey,+ disconnectService,+ disconnectGitHub,+ ...Object.values(serviceBrowserFlow),+ ])+ call.mockImplementation(selected);+ const srv = expect.objectContaining({ id: 'srv' });+ const flow = { workspaceId: 'ws', service: 'example', flowId: 'flow-1' };++ await workspacesController.startServiceConnection({ workspaceId: 'ws', service: 'example' });+ await workspacesController.getServiceFlow(flow);+ await workspacesController.cancelServiceConnection(flow);+ await workspacesController.connectServiceWithKey({+ workspaceId: 'ws',+ service: 'example',+ fields: { api_key: 'synthetic' },+ });+ await workspacesController.disconnectService({ workspaceId: 'ws', service: 'example' });+ await workspacesController.disconnectGitHub('ws');++ expect(serviceBrowserFlow.startServiceBrowserFlow).toHaveBeenCalledWith(+ srv,+ 'example',+ expect.any(Function)+ );+ expect(serviceBrowserFlow.getServiceBrowserFlow).toHaveBeenCalledWith(srv, 'example', 'flow-1');+ expect(serviceBrowserFlow.cancelServiceBrowserFlow).toHaveBeenCalledWith(+ srv,+ 'example',+ 'flow-1'+ );+ expect(connectServiceWithKey).toHaveBeenCalledWith(srv, 'example', { api_key: 'synthetic' });+ expect(disconnectService).toHaveBeenCalledWith(srv, 'example');+ expect(disconnectGitHub).toHaveBeenCalledWith(srv);+ });+it('refuses a workspace with no tenant where its server has several', async () => {requireWorkspace.mockResolvedValue(workspace(null));listWorkspacesForServer.mockResolvedValueOnce([{ id: 'ws' }, { id: 'ws-2' }]);diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex 4fb1bee55..9ba52bcb5 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -1,3 +1,4 @@+import { appService } from '@main/core/app/service';import { backfillAgentIcons } from '@main/core/switch-servers/backfill-agent-icons';import { withResolvedHomeUrls } from '@main/core/switch-servers/bridge-home-url';import { createBridgeOnServer } from '@main/core/switch-servers/create-bridge';@@ -54,10 +55,16 @@ import {type TemplateRun,type TemplateVisibility,updateAddressingPolicy,+ fetchConnectionAgents,fetchServiceGrants,+ fetchWorkspaceServices,getConnectionCatalog,getGitHubConnection,+ connectServiceWithKey,+ disconnectGitHub,+ disconnectService,setServiceGrant,+ setWorkspaceService,removeServiceGrant,updateCanManageAgents,updateAgentDescription,@@ -72,6 +79,11 @@ import {} from '@main/core/switch-servers/identities';import { hostUnreachable } from '@main/core/switch-servers/require-server';import { serverKindOf } from '@main/core/switch-servers/servers-store';+import {+ cancelServiceBrowserFlow,+ getServiceBrowserFlow,+ startServiceBrowserFlow,+} from '@main/core/switch-servers/service-browser-flow';import { saveTeamsPackage } from '@main/core/switch-servers/teams-package';import { updateBridgeOnServer } from '@main/core/switch-servers/update-bridge';import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';@@ -806,6 +818,62 @@ export const workspacesController = createRPCController({getServiceConnections: (workspaceId: string) =>withWorkspaceSession(workspaceId, getConnectionCatalog),+ /**+ * Start signing in to `service` for this workspace: the browser opens at the+ * vendor, and this Console's listener takes the result back. Resolves to the+ * flow's id.+ */+ startServiceConnection: (params: { workspaceId: string; service: string }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ startServiceBrowserFlow(server, params.service, (url) => appService.openExternal(url))+ ),++ getServiceFlow: (params: { workspaceId: string; service: string; flowId: string }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ getServiceBrowserFlow(server, params.service, params.flowId)+ ),++ cancelServiceConnection: (params: { workspaceId: string; service: string; flowId: string }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ cancelServiceBrowserFlow(server, params.service, params.flowId)+ ),++ /** Connect `service` with a key, or replace the key it has; Switch checks it with the vendor. */+ connectServiceWithKey: (params: {+ workspaceId: string;+ service: string;+ fields: Record<string, string>;+ }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ connectServiceWithKey(server, params.service, params.fields)+ ),++ /** Disconnect `service` in this workspace: its grants go with it. */+ disconnectService: (params: { workspaceId: string; service: string }) =>+ withWorkspaceSession(params.workspaceId, (server) => disconnectService(server, params.service)),++ disconnectGitHub: (workspaceId: string) =>+ withWorkspaceSession(workspaceId, (server) => disconnectGitHub(server)),++ /** The signed-in person's own agents in this workspace, and which are granted `service`. */+ getConnectionAgents: (params: { workspaceId: string; service: string }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchConnectionAgents(server, params.service)+ ),++ /**+ * The workspace's switch for each service, for a workspace admin; null when+ * its server has no workspace switch.+ */+ getWorkspaceServices: (workspaceId: string) =>+ withWorkspaceSession(workspaceId, fetchWorkspaceServices),++ /** Switch a service on or off for everyone in this workspace; workspace admins only. */+ setWorkspaceService: (params: { workspaceId: string; service: string; enabled: boolean }) =>+ withWorkspaceSession(params.workspaceId, (server) =>+ setWorkspaceService(server, params.service, params.enabled)+ ),+/*** Create or replace the agent's grant on a service; owner only. Resolves to* a warning or null. `access` is left out of an on/off grant (a servicediff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex 517922e46..0668132ff 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -1,5 +1,13 @@+import {+ ConnectorAppMoveDialog,+ ConnectorAppRemoveDialog,+ ConnectorAppSecretDialog,+ ConnectorAppSetupDialog,+} from '@renderer/features/admin/connector-app-dialogs';import { RenameChatModal } from '@renderer/features/chats/components/chat-modals';import { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';+import { ConnectServiceModal } from '@renderer/features/connectors/connect-service-modal';+import { DisconnectServiceDialog } from '@renderer/features/connectors/disconnect-dialog';import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';import { ResetAgentModal } from '@renderer/features/locations/components/reset-agent-modal';@@ -16,7 +24,6 @@ import { AssignServerModal } from '@renderer/features/switch-servers/assign-servimport { BundledChatSignInModal } from '@renderer/features/switch-servers/BundledChatSignIn';import { ClaimIdentityModal } from '@renderer/features/switch-servers/ClaimIdentityModal';import { ConnectChatModal } from '@renderer/features/switch-servers/ConnectChatModal';-import { ConnectionsModal } from '@renderer/features/switch-servers/ConnectionsModal';import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';@@ -92,7 +99,18 @@ export const modalRegistry = {dismissOnOutsideClick: false,}),connectChatModal: createModal(ConnectChatModal, { size: 'md' }),- connectionsModal: createModal(ConnectionsModal, { size: 'md' }),+ connectServiceModal: createModal(ConnectServiceModal, { size: 'md' }),+ disconnectServiceModal: createModal(DisconnectServiceDialog, { size: 'sm' }),+ connectorAppSetupModal: createModal(ConnectorAppSetupDialog, {+ size: 'md',+ dismissOnOutsideClick: false,+ }),+ connectorAppSecretModal: createModal(ConnectorAppSecretDialog, {+ size: 'sm',+ dismissOnOutsideClick: false,+ }),+ connectorAppRemoveModal: createModal(ConnectorAppRemoveDialog, { size: 'sm' }),+ connectorAppMoveModal: createModal(ConnectorAppMoveDialog, { size: 'sm' }),claimIdentityModal: createModal(ClaimIdentityModal, {size: 'md',dismissOnOutsideClick: false,diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.tsindex 4f7b397ef..187b88118 100644--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts@@ -1,6 +1,8 @@import type { ComponentType, ReactNode } from 'react';import { homeView } from '@renderer/app/home-view';+import { adminView } from '@renderer/features/admin/admin-view';import { chatView } from '@renderer/features/chats/chat-view';+import { connectorsView } from '@renderer/features/connectors/connectors-view';import { locationView } from '@renderer/features/locations/view';import { managedAgentView } from '@renderer/features/managed-agents/managed-agent-view';import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';@@ -35,6 +37,7 @@ export const views = {server: serverView,managedServer: managedServerView,serverAgents: serverAgentsView,+ connectors: connectorsView,serverRooms: serverRoomsView,remoteHosts: remoteHostsView,remoteHost: remoteHostView,@@ -43,6 +46,7 @@ export const views = {templateDetail: templateDetailView,templateUse: templateUseView,templateCapture: templateCaptureView,+ admin: adminView,// oxlint-disable-next-line typescript/no-explicit-any} satisfies Record<string, ViewDefinition<any>>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.tsnew file mode 100644index 000000000..54b941e96--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts@@ -0,0 +1,39 @@+export type AdminSection = 'connectors' | 'apps';++export type AdminScope = 'workspace' | 'server';++export const ADMIN_SECTION_LABELS = {+ connectors: 'Connectors',+ apps: 'Connector apps',+} as const satisfies Record<AdminSection, string>;++export type AdminGroup = { scope: AdminScope; sections: AdminSection[] };++/**+ * The Admin page's sections the signed-in account may use, grouped by what+ * they reach. Each is there only for the role that may use it, so nobody is+ * shown a control the server would refuse: the workspace's connector+ * switches are its admins' (the server's operator administers every+ * workspace), and the apps connectors sign in through are the operator's+ * alone. A group with nothing in it is left out.+ */+export function adminGroups(person: { administers: boolean; operator: boolean }): AdminGroup[] {+ const groups: AdminGroup[] = [+ { scope: 'workspace', sections: person.administers ? ['connectors'] : [] },+ { scope: 'server', sections: person.operator ? ['apps'] : [] },+ ];+ return groups.filter((group) => group.sections.length > 0);+}++/**+ * The section to show: the one asked for when the person may use it,+ * otherwise the first they may. Null when they may use none.+ */+export function shownAdminSection(+ groups: AdminGroup[],+ asked: AdminSection | undefined+): AdminSection | null {+ const sections = groups.flatMap((group) => group.sections);+ if (asked !== undefined && sections.includes(asked)) return asked;+ return sections[0] ?? null;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsxnew file mode 100644index 000000000..5b5216813--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx@@ -0,0 +1,239 @@+import { ShieldCheck } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { connectorsPageAccess } from '@renderer/features/connectors/connectors-catalog';+import {+ useConnectorCatalog,+ useServerFeatureFlags,+} from '@renderer/features/connectors/connectors-queries';+import { ServerPage } from '@renderer/features/switch-servers/server-page';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import {+ administersWorkspaceInScope,+ operatesServer,+} from '@renderer/features/switch-servers/workspace-admin';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { PageHeader } from '@renderer/lib/components/page-header';+import {+ PageContent,+ PageLayout,+ type PageSidebarGroup,+ PageSidebarGroups,+} from '@renderer/lib/components/page-layout';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { SearchInput } from '@renderer/lib/ui/search-input';+import { Spinner } from '@renderer/lib/ui/spinner';+import {+ ADMIN_SECTION_LABELS,+ type AdminGroup,+ type AdminSection,+ adminGroups,+ shownAdminSection,+} from './admin-sections';+import { ConnectorAppProfile } from './connector-app-profile';+import { useConnectorApps } from './connector-apps-queries';+import { ConnectorAppsTab } from './connector-apps-tab';+import { WorkspaceSwitchesTab } from './workspace-switches-tab';++type AdminParams = {+ serverId: string;+ /** The section asked for; the first the person may use when absent or not theirs. */+ section?: AdminSection;+ /** The connector app whose profile is open in the Connector apps section. */+ app?: string;+};++/** Wider than a list page, so the tiles keep two columns beside the side menu. */+const WIDTH = 1120;++const AdminTitlebar = observer(function AdminTitlebar() {+ const { serverId } = useParams('admin').params;+ return <ServerSectionTitlebar serverId={serverId} icon={ShieldCheck} label="Admin" />;+});++/**+ * What the workspace's admins, and the server's operator, manage for other+ * people. Laid out like Settings: its sections down the side, grouped by+ * what they reach, each shown only to the role that may use it. Like the+ * Connectors page it is behind the server's `service_connections` flag,+ * since everything on it is about connectors: with it off there is no page,+ * and reaching it anyway goes to Your Agents.+ */+const AdminPanel = observer(function AdminPanel() {+ const { params } = useParams('admin');+ const { serverId } = params;+ const { navigate } = useNavigate();+ const access = connectorsPageAccess(useServerFeatureFlags(serverId));+ const workspace = workspacesStore.onServerInScope(serverId);+ useEffect(() => {+ if (access === 'absent') navigate('serverAgents', { serverId });+ }, [access, navigate, serverId]);++ if (access !== 'shown' || workspace === null)+ return (+ <ServerPage width={880} title="Admin" description="">+ <Spinner />+ </ServerPage>+ );+ const operator = operatesServer(serverId);+ const groups = adminGroups({ administers: administersWorkspaceInScope(serverId), operator });+ const section = shownAdminSection(groups, params.section);+ if (section === null)+ return (+ <ServerPage width={880} title="Admin" description="Ask a workspace admin to change these.">+ {null}+ </ServerPage>+ );+ // Keyed so a workspace switch starts the search afresh.+ return (+ <Admin+ key={workspace.id}+ serverId={serverId}+ operator={operator}+ groups={groups}+ section={section}+ openApp={params.app ?? null}+ workspace={workspace}+ serverName={switchServersStore.servers.find((s) => s.id === serverId)?.name ?? 'This server'}+ />+ );+});++/**+ * The side menu and one section beside it, or a connector app's profile in+ * that column. Which is open is a view param, so the history arrows move+ * between them as they do on the Connectors page.+ */+function Admin({+ serverId,+ operator,+ groups,+ section,+ openApp,+ workspace,+ serverName,+}: {+ serverId: string;+ operator: boolean;+ groups: AdminGroup[];+ section: AdminSection;+ openApp: string | null;+ workspace: { id: string; name: string };+ serverName: string;+}) {+ const { navigate } = useNavigate();+ const [query, setQuery] = useState('');+ const apps = useConnectorApps(serverId, operator);+ const catalog = useConnectorCatalog(workspace.id);+ // A failed check is remembered for the visit, so the tile says so after+ // the profile is left; a later check that passes clears it.+ const [checkFailures, setCheckFailures] = useState<Record<string, string>>({});++ const detail = { workspace: workspace.name, server: serverName };+ const menu: PageSidebarGroup<AdminSection>[] = groups.map((group) => ({+ label: group.scope === 'workspace' ? 'Workspace' : 'Server',+ detail: detail[group.scope],+ items: group.sections.map((id) => ({ id, label: ADMIN_SECTION_LABELS[id] })),+ }));+ const opened =+ section === 'apps' && openApp !== null+ ? apps.data?.apps.find((app) => app.slug === openApp)+ : undefined;++ return (+ <div className="relative z-10 flex min-h-0 flex-1 overflow-hidden bg-background">+ <PageLayout+ width={WIDTH}+ sidebar={+ <PageSidebarGroups+ groups={menu}+ activeId={section}+ onSelect={(item) => {+ setQuery('');+ navigate('admin', { serverId, section: item.id });+ }}+ />+ }+ >+ <PageContent className="px-0">+ {opened ? (+ <div className="pt-10 pb-10">+ <ConnectorAppProfile+ key={opened.slug}+ serverId={serverId}+ app={opened}+ publicUrl={apps.data?.public_url ?? null}+ checkFailure={checkFailures[opened.slug] ?? null}+ onCheckFailure={(message) =>+ setCheckFailures((current) => {+ const next = { ...current };+ if (message === null) delete next[opened.slug];+ else next[opened.slug] = message;+ return next;+ })+ }+ onBack={() => navigate('admin', { serverId, section: 'apps' })}+ />+ </div>+ ) : (+ <div className="space-y-6 pb-10">+ <PageHeader+ sticky+ title={ADMIN_SECTION_LABELS[section]}+ description={+ section === 'apps'+ ? `Some connectors sign people in through an app you register with the vendor. Set each up once, and every workspace on ${serverName} uses it.`+ : `Choose which services people in ${workspace.name} can connect and give to their agents.`+ }+ >+ <div className="space-y-2">+ <SearchInput+ containerClassName="w-full"+ aria-label={section === 'apps' ? 'Search apps' : 'Search services'}+ placeholder="Search by name or category"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ {section === 'connectors' && (+ <p className="text-xs text-foreground-muted">+ Turning a service off takes it from every agent within a minute. Turning it+ back on restores their access.+ </p>+ )}+ </div>+ </PageHeader>+ {section === 'apps' ? (+ <ConnectorAppsTab+ serverId={serverId}+ apps={apps}+ catalog={catalog.data}+ query={query}+ checkFailures={checkFailures}+ onOpen={(slug) => navigate('admin', { serverId, section: 'apps', app: slug })}+ />+ ) : (+ <WorkspaceSwitchesTab workspaceId={workspace.id} query={query} />+ )}+ </div>+ )}+ </PageContent>+ </PageLayout>+ </div>+ );+}++export const adminView = {+ WrapView: ({ children }: { children: React.ReactNode } & AdminParams) => <>{children}</>,+ TitlebarSlot: AdminTitlebar,+ MainPanel: AdminPanel,+ canActivate: (params: unknown): GuardResult => {+ const serverId =+ typeof params === 'object' && params !== null+ ? (params as { serverId?: unknown }).serverId+ : undefined;+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };+ return { ok: true };+ },+} satisfies ViewDefinition<AdminParams>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-dialogs.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-dialogs.tsxnew file mode 100644index 000000000..1f1993825--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-dialogs.tsx@@ -0,0 +1,602 @@+import { CircleCheck, Circle, ExternalLink, FileKey } from 'lucide-react';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { useCloseGuard } from '@renderer/lib/modal/use-close-guard';+import { openExternalUrl } from '@renderer/lib/open-external';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Input } from '@renderer/lib/ui/input';+import { RadioGroup, RadioGroupItem } from '@renderer/lib/ui/radio-group';+import { Spinner } from '@renderer/lib/ui/spinner';+import { cn } from '@renderer/utils/utils';+import type {+ ConnectorApp,+ ConnectorAppField,+ ConnectorAppImpact,+ SaveConnectorAppInput,+} from '@shared/core/switch-servers/connector-apps';+import {+ type Audience,+ type SecretField,+ UPDATE_SECRET_NOTE,+ asksWhoConnects,+ menuLabel,+ moveChecklist,+ peopleIn,+ removeWarning,+ secretFields,+ setupInstructions,+ switchWarning,+ vendorName,+} from './connector-apps';+import { useReloadConnectorApps } from './connector-apps-queries';+import { CopyButton } from './copy-button';++export type SetupMode = 'set_up' | 'switch' | 'enter_again';++type AppDialogProps = { serverId: string; app: ConnectorApp } & BaseModalProps<string>;++/** A save's refusal as the form shows it: the vendor's words, and the value to look at again. */+type Refusal = { message: string; field: ConnectorAppField | null };++/**+ * Save through the server, which checks with the vendor first. Resolves to+ * the refusal to show, or null once saved and the page re-read; a failure+ * that is not the vendor's is shown the same way, with no field marked.+ */+function useSave(serverId: string, service: string, failure: string) {+ const reload = useReloadConnectorApps(serverId);+ return async (input: SaveConnectorAppInput): Promise<Refusal | null> => {+ try {+ const result = await rpc.switchServers.saveConnectorApp({ serverId, service, input });+ if (result.kind === 'refused') return { message: result.message, field: result.field };+ await reload();+ return null;+ } catch (cause) {+ return { message: failureText(cause, failure), field: null };+ }+ };+}++/** A value to paste at the vendor, with a button that copies it. */+function Copyable({ value }: { value: string }) {+ return (+ <span className="mt-1.5 flex items-center gap-1 rounded-md border border-border bg-background-1 py-1 pr-1 pl-2">+ <code className="min-w-0 flex-1 font-mono text-xs break-all">{value}</code>+ <CopyButton value={value} />+ </span>+ );+}++function FieldLabel({ htmlFor, children }: { htmlFor: string; children: React.ReactNode }) {+ return (+ <label htmlFor={htmlFor} className="block text-sm font-medium">+ {children}+ </label>+ );+}++/**+ * The secret inputs, labelled as the vendor labels them: empty and masked,+ * and a private key read from its file here and never shown.+ */+function SecretInputs({+ fields,+ values,+ onChange,+ marked,+ disabled,+ optional,+}: {+ fields: SecretField[];+ values: Record<string, string>;+ onChange: (name: string, value: string) => void;+ marked: ConnectorAppField | null;+ disabled: boolean;+ /** Left empty, the saved one is kept. */+ optional: boolean;+}) {+ const [fileNames, setFileNames] = useState<Record<string, string>>({});+ return (+ <>+ {fields.map((field) => {+ const id = `connector-app-${field.name}`;+ return (+ <div key={field.name} className="space-y-1">+ <FieldLabel htmlFor={id}>+ {field.label}+ {optional && <span className="font-normal text-foreground-muted"> (optional)</span>}+ </FieldLabel>+ {field.file ? (+ <>+ <label+ className={cn(+ 'flex w-fit cursor-pointer items-center gap-2 rounded-md border px-3 py-1.5 text-sm hover:bg-background-1',+ marked === field.name ? 'border-destructive' : 'border-border',+ disabled && 'pointer-events-none opacity-50'+ )}+ >+ <FileKey className="size-4 text-foreground-muted" />+ {fileNames[field.name] ?? 'Choose the .pem file'}+ <input+ id={id}+ type="file"+ accept=".pem"+ className="sr-only"+ aria-invalid={marked === field.name || undefined}+ disabled={disabled}+ onChange={(event) => {+ const file = event.target.files?.[0];+ if (!file) return;+ void file.text().then((text) => {+ setFileNames((names) => ({ ...names, [field.name]: file.name }));+ onChange(field.name, text);+ });+ }}+ />+ </label>+ <p className="text-xs text-foreground-muted">+ Read on this computer and sent only to Switch; never shown.+ </p>+ </>+ ) : (+ <Input+ id={id}+ type="password"+ autoComplete="off"+ spellCheck={false}+ disabled={disabled}+ aria-invalid={marked === field.name || undefined}+ value={values[field.name] ?? ''}+ onChange={(event) => onChange(field.name, event.target.value)}+ />+ )}+ </div>+ );+ })}+ </>+ );+}++function RefusalText({ refusal }: { refusal: Refusal | null }) {+ if (!refusal) return null;+ return (+ <p role="alert" className="text-sm text-destructive">+ {refusal.message}+ </p>+ );+}++type Step = 'warning' | 'create' | 'values';++const STEPS: Record<SetupMode, Step[]> = {+ set_up: ['create', 'values'],+ enter_again: ['create', 'values'],+ switch: ['warning', 'create', 'values'],+};++/**+ * Setting up an app, entering it again, or switching to a different one:+ * create it at the vendor following the steps, paste its values, and check+ * and save in one click. Switching starts with what it does to the people+ * connected, and asks the server who would reconnect before it saves.+ */+export function ConnectorAppSetupDialog({+ serverId,+ app,+ publicUrl,+ mode,+ onSuccess,+ onClose,+}: AppDialogProps & { publicUrl: string | null; mode: SetupMode }) {+ const steps = STEPS[mode];+ const [step, setStep] = useState<Step>(steps[0]);+ const [audience, setAudience] = useState<Audience>('internal');+ const [clientId, setClientId] = useState(+ mode === 'enter_again' ? (app.saved_client_id ?? '') : ''+ );+ const [secrets, setSecrets] = useState<Record<string, string>>({});+ const [refusal, setRefusal] = useState<Refusal | null>(null);+ const [busy, setBusy] = useState(false);+ const [impact, setImpact] = useState<ConnectorAppImpact | null>(null);+ useCloseGuard(busy);+ const save = useSave(serverId, app.slug, `Could not save ${app.name}'s app.`);++ const vendor = vendorName(app);+ const fields = secretFields(app);+ const id = clientId.trim();+ const complete = id !== '' && fields.every((field) => (secrets[field.name] ?? '') !== '');+ const replacing = app.saved_client_id !== null && id !== app.saved_client_id;+ const index = steps.indexOf(step);+ const stepName = {+ warning: 'Before you switch',+ create: `Create the app at ${vendor}`,+ values: 'Paste its values',+ }[step];++ const submit = async () => {+ setBusy(true);+ setRefusal(null);+ try {+ if (mode === 'switch' && impact === null) {+ setImpact(+ await rpc.switchServers.getConnectorAppImpact({+ serverId,+ service: app.slug,+ clientId: id,+ })+ );+ return;+ }+ const refused = await save({ client_id: id, ...secrets, replace: mode === 'switch' });+ if (refused) setRefusal(refused);+ else onSuccess(`${app.name} is ready.`);+ } catch (cause) {+ setRefusal({+ message: failureText(cause, 'Could not ask who would reconnect.'),+ field: null,+ });+ } finally {+ setBusy(false);+ }+ };++ const title =+ mode === 'switch'+ ? `Use a different ${vendor} app`+ : mode === 'enter_again'+ ? `Enter ${app.name}'s app again`+ : `Set up ${app.kind === 'github_app' ? 'GitHub' : app.name}`;++ return (+ <>+ <DialogHeader showCloseButton={!busy}>+ <DialogTitle>{title}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-4 pt-0">+ {steps.length > 1 && (+ <p className="text-xs font-medium tracking-wide text-foreground-muted uppercase">+ Step {index + 1} of {steps.length} · {stepName}+ </p>+ )}++ {step === 'warning' && (+ <div className="space-y-2 rounded-md border border-border-warning bg-background-warning p-3">+ {switchWarning(app, app).map((line) => (+ <p key={line} className="text-sm">+ {line}+ </p>+ ))}+ </div>+ )}++ {step === 'create' && (+ <>+ {asksWhoConnects(app) && (+ <fieldset className="space-y-2">+ <legend className="mb-2 text-sm font-medium">Who will connect?</legend>+ <RadioGroup+ value={audience}+ onValueChange={(value) => setAudience(value as Audience)}+ className="gap-2"+ >+ <label className="flex items-center gap-2 text-sm">+ <RadioGroupItem value="internal" />+ Only people in your Google organization (recommended)+ </label>+ <label className="flex items-center gap-2 text-sm">+ <RadioGroupItem value="external" />+ Anyone with a Google account+ </label>+ </RadioGroup>+ </fieldset>+ )}+ <ol className="list-decimal space-y-3 pl-5 text-sm">+ {setupInstructions(app, audience, publicUrl).map((instruction) => (+ <li key={instruction.text}>+ {instruction.text}+ {instruction.link && (+ <button+ type="button"+ className="ml-1 inline-flex items-center gap-1 text-foreground underline underline-offset-2"+ onClick={() =>+ void openExternalUrl(+ instruction.link!.href,+ `Could not open ${instruction.link!.label}`+ )+ }+ >+ {instruction.link.label}+ <ExternalLink className="size-3" />+ </button>+ )}+ {instruction.copy && <Copyable value={instruction.copy} />}+ </li>+ ))}+ </ol>+ </>+ )}++ {step === 'values' && (+ <div className="space-y-3">+ <div className="space-y-1">+ <FieldLabel htmlFor="connector-app-client_id">Client ID</FieldLabel>+ <Input+ id="connector-app-client_id"+ autoComplete="off"+ spellCheck={false}+ disabled={busy}+ aria-invalid={refusal?.field === 'client_id' || undefined}+ value={clientId}+ onChange={(event) => {+ setClientId(event.target.value);+ setImpact(null);+ }}+ />+ </div>+ <SecretInputs+ fields={fields}+ values={secrets}+ marked={refusal?.field ?? null}+ disabled={busy}+ optional={false}+ onChange={(name, value) => {+ setSecrets((current) => ({ ...current, [name]: value }));+ setRefusal(null);+ }}+ />+ {app.kind === 'github_app' && (+ <p className="text-xs text-foreground-muted">+ The App's name is read from GitHub when Switch checks it.+ </p>+ )}+ {mode === 'enter_again' && replacing && (+ <p role="status" className="text-sm text-foreground-warning">+ This is a different client ID from the one saved. Use a different app to switch on+ purpose.+ </p>+ )}+ {impact && (+ <p role="status" className="text-sm text-foreground-warning">+ {impact.connected_members === 0+ ? 'Nobody is connected through the current app.'+ : `${peopleIn(impact)} will need to reconnect.`}+ </p>+ )}+ <RefusalText refusal={refusal} />+ </div>+ )}+ </DialogContentArea>+ <DialogFooter>+ {index > 0 ? (+ <Button variant="outline" disabled={busy} onClick={() => setStep(steps[index - 1])}>+ Back+ </Button>+ ) : (+ <Button variant="outline" disabled={busy} onClick={onClose}>+ Cancel+ </Button>+ )}+ {step !== 'values' ? (+ <Button onClick={() => setStep(steps[index + 1])}>+ {step === 'warning' ? 'Continue' : 'Next'}+ </Button>+ ) : (+ <Button+ variant={mode === 'switch' && impact ? 'destructive' : 'default'}+ disabled={!complete || busy || (mode === 'enter_again' && replacing)}+ onClick={() => void submit()}+ >+ {busy && <Spinner />}+ {busy+ ? 'Checking…'+ : mode === 'switch'+ ? impact+ ? 'Switch app'+ : 'Check who reconnects'+ : 'Check and save'}+ </Button>+ )}+ </DialogFooter>+ </>+ );+}++/**+ * A new secret (or, for GitHub, a new private key) for the same app: nobody+ * is disconnected. What is left empty keeps what is saved.+ */+export function ConnectorAppSecretDialog({ serverId, app, onSuccess, onClose }: AppDialogProps) {+ const [secrets, setSecrets] = useState<Record<string, string>>({});+ const [refusal, setRefusal] = useState<Refusal | null>(null);+ const [busy, setBusy] = useState(false);+ useCloseGuard(busy);+ const save = useSave(serverId, app.slug, `Could not update ${app.name}'s secret.`);+ const given = Object.fromEntries(Object.entries(secrets).filter(([, value]) => value !== ''));+ const fields = secretFields(app);++ const submit = async () => {+ if (app.client_id === null) return;+ setBusy(true);+ setRefusal(null);+ const refused = await save({ client_id: app.client_id, ...given, replace: false });+ setBusy(false);+ if (refused) setRefusal(refused);+ else onSuccess(`${app.name}'s secret is updated. Nobody was disconnected.`);+ };++ return (+ <>+ <DialogHeader showCloseButton={!busy}>+ <DialogTitle>{menuLabel(app, 'update_secret')}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ <p className="text-sm text-foreground-muted">+ For the app with client ID <code className="font-mono text-xs">{app.client_id}</code>.{' '}+ {UPDATE_SECRET_NOTE}+ </p>+ <SecretInputs+ fields={fields}+ values={secrets}+ marked={refusal?.field ?? null}+ disabled={busy}+ optional={fields.length > 1}+ onChange={(name, value) => {+ setSecrets((current) => ({ ...current, [name]: value }));+ setRefusal(null);+ }}+ />+ <RefusalText refusal={refusal} />+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" disabled={busy} onClick={onClose}>+ Cancel+ </Button>+ <Button disabled={busy || Object.keys(given).length === 0} onClick={() => void submit()}>+ {busy && <Spinner />}+ {busy ? 'Checking…' : 'Check and save'}+ </Button>+ </DialogFooter>+ </>+ );+}++/** Removing the saved app: nobody can connect it after, and who was connected loses it. */+export function ConnectorAppRemoveDialog({ serverId, app, onSuccess, onClose }: AppDialogProps) {+ const reload = useReloadConnectorApps(serverId);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ useCloseGuard(busy);++ const remove = async () => {+ setBusy(true);+ setError(null);+ try {+ await rpc.switchServers.removeConnectorApp({ serverId, service: app.slug });+ await reload();+ onSuccess(`${app.name}'s app is removed.`);+ } catch (cause) {+ setError(failureText(cause, `Could not remove ${app.name}'s app.`));+ } finally {+ setBusy(false);+ }+ };++ return (+ <>+ <DialogHeader showCloseButton={!busy}>+ <DialogTitle>Remove {app.name}'s app?</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ <p className="text-sm">{removeWarning(app)}</p>+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" disabled={busy} onClick={onClose}>+ Cancel+ </Button>+ <Button variant="destructive" disabled={busy} onClick={() => void remove()}>+ {busy && <Spinner />}+ Remove+ </Button>+ </DialogFooter>+ </>+ );+}++/**+ * Moving an app off the server's configuration: copy it into Switch, remove+ * the configuration, restart. Only the first is done here; the dialog stays+ * open on the checklist so the other two are in front of the operator.+ */+export function ConnectorAppMoveDialog({+ serverId,+ app: initial,+ onSuccess,+ onClose,+}: AppDialogProps) {+ const reload = useReloadConnectorApps(serverId);+ const [app, setApp] = useState(initial);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ useCloseGuard(busy);+ const items = moveChecklist(app);+ const copied = items[0]?.done ?? false;++ const copy = async () => {+ setBusy(true);+ setError(null);+ try {+ setApp(await rpc.switchServers.importConnectorApp({ serverId, service: app.slug }));+ await reload();+ } catch (cause) {+ setError(failureText(cause, `Could not copy ${app.name}'s app into Switch.`));+ } finally {+ setBusy(false);+ }+ };++ return (+ <>+ <DialogHeader showCloseButton={!busy}>+ <DialogTitle>Manage {app.name} here instead</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ <ol className="space-y-3">+ {items.map((item, index) => (+ <li key={item.text} className="flex items-start gap-2 text-sm">+ {item.done ? (+ <CircleCheck+ aria-label="Done"+ className="mt-0.5 size-4 shrink-0 text-foreground-success"+ />+ ) : (+ <Circle+ aria-label="To do"+ className="mt-0.5 size-4 shrink-0 text-foreground-muted"+ />+ )}+ <div className="space-y-1.5">+ <p>{item.text}</p>+ {index === 0 && !item.done && (+ <Button size="sm" variant="outline" disabled={busy} onClick={() => void copy()}>+ {busy && <Spinner />}+ Copy into Switch+ </Button>+ )}+ </div>+ </li>+ ))}+ </ol>+ <p className="text-sm text-foreground-muted">+ Nobody needs to reconnect: Switch keeps using the same app.+ </p>+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </DialogContentArea>+ <DialogFooter>+ <Button+ variant={copied ? 'default' : 'outline'}+ disabled={busy}+ onClick={() => (copied ? onSuccess(`${app.name} is copied into Switch.`) : onClose())}+ >+ {copied ? 'Done' : 'Close'}+ </Button>+ </DialogFooter>+ </>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-profile.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-profile.tsxnew file mode 100644index 000000000..4bfea256a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-app-profile.tsx@@ -0,0 +1,233 @@+import { format } from 'date-fns';+import { ArrowLeft, CircleCheck, CircleX, ExternalLink, MoreHorizontal } from 'lucide-react';+import { Fragment, useState } from 'react';+import { ConnectionIcon } from '@renderer/features/switch-servers/connection-icon';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { openExternalUrl } from '@renderer/lib/open-external';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@renderer/lib/ui/dropdown-menu';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectorApp, ConnectorAppCheck } from '@shared/core/switch-servers/connector-apps';+import {+ type DetailRow,+ STATE_BADGE,+ actionLabel,+ appDetails,+ attention,+ cardState,+ configuredSentence,+ menuActions,+ menuLabel,+ notSetUpSentence,+ primaryAction,+ stateLabel,+ usedBy,+} from './connector-apps';+import { changeBlocked, useConnectorAppDialogs } from './connector-apps-tab';+import { CopyButton } from './copy-button';++/**+ * One connector app on its own page, in front of the tiles: whether it is+ * working, what to do next with one obvious button, and the changes that+ * disconnect people kept apart in the ⋯ menu. Checking it asks the vendor+ * and stores nothing; a failed check is the page's to remember, so its tile+ * shows it too.+ */+export function ConnectorAppProfile({+ serverId,+ app,+ publicUrl,+ checkFailure,+ onCheckFailure,+ onBack,+}: {+ serverId: string;+ app: ConnectorApp;+ publicUrl: string | null;+ checkFailure: string | null;+ onCheckFailure: (message: string | null) => void;+ onBack: () => void;+}) {+ const open = useConnectorAppDialogs(serverId, publicUrl);+ const [checks, setChecks] = useState<ConnectorAppCheck[] | null>(null);+ const [checking, setChecking] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const state = cardState(app, checkFailure);+ const needs = attention(app, checkFailure);+ const primary = primaryAction(app, checkFailure);+ const menu = menuActions(app);+ const blocked = changeBlocked(app, publicUrl);++ const check = async () => {+ setChecking(true);+ setError(null);+ try {+ const result = await rpc.switchServers.checkConnectorApp({ serverId, service: app.slug });+ setChecks(result.checks);+ onCheckFailure(result.ok ? null : (result.checks.find((c) => !c.ok)?.message ?? null));+ } catch (cause) {+ setError(failureText(cause, `Could not check ${app.name}'s app.`));+ } finally {+ setChecking(false);+ }+ };++ return (+ <div className="flex flex-col gap-8">+ <div className="flex flex-col gap-4">+ <Button variant="ghost" size="sm" className="-ml-2 w-fit" onClick={onBack}>+ <ArrowLeft className="size-4" />+ Connector apps+ </Button>+ <header className="flex items-start gap-4">+ <ConnectionIcon slug={app.slug} name={app.name} size="xl" />+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex items-center gap-2">+ <h1 className="truncate text-3xl font-semibold tracking-tight text-foreground">+ {app.name}+ </h1>+ <Badge variant={STATE_BADGE[state]}>{stateLabel(state)}</Badge>+ </div>+ <p className="text-sm text-foreground-muted">+ {state === 'not_set_up'+ ? notSetUpSentence(app)+ : app.source === 'configuration'+ ? configuredSentence(app)+ : usedBy(app)}+ </p>+ </div>+ <div className="flex shrink-0 gap-2">+ {primary && (+ <Button+ variant={primary === 'check' || primary === 'manage_here' ? 'outline' : 'default'}+ disabled={checking || (blocked && primary !== 'check')}+ onClick={() => (primary === 'check' ? void check() : open(app, primary))}+ >+ {checking && <Spinner />}+ {actionLabel(app, primary)}+ </Button>+ )}+ {menu.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="outline" size="icon" aria-label={`More for ${app.name}`}>+ <MoreHorizontal className="size-4" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {menu.map((action) =>+ action === 'remove' ? (+ <Fragment key={action}>+ {menu.length > 1 && <DropdownMenuSeparator />}+ <DropdownMenuItem variant="destructive" onClick={() => open(app, action)}>+ {menuLabel(app, action)}…+ </DropdownMenuItem>+ </Fragment>+ ) : (+ <DropdownMenuItem+ key={action}+ disabled={blocked}+ onClick={() => open(app, action)}+ >+ {menuLabel(app, action)}…+ </DropdownMenuItem>+ )+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ </header>+ </div>++ {needs && (+ <p+ role="status"+ className="rounded-lg border border-border-warning bg-background-warning p-3 text-sm"+ >+ {needs.sentence}+ </p>+ )}+ {checks && (+ <ul aria-label="What the vendor said" className="space-y-1.5">+ {checks.map((c) => (+ <li key={c.name} className="flex items-start gap-2 text-sm">+ {c.ok ? (+ <CircleCheck+ aria-label="Passed"+ className="mt-0.5 size-4 shrink-0 text-foreground-success"+ />+ ) : (+ <CircleX aria-label="Failed" className="mt-0.5 size-4 shrink-0 text-destructive" />+ )}+ {c.message}+ </li>+ ))}+ </ul>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}++ {appDetails(app, publicUrl, (iso) => format(new Date(iso), 'MMM d, yyyy')).map((section) => (+ <section key={section.title} className="flex flex-col gap-3">+ <h2 className="text-sm font-semibold text-foreground">{section.title}</h2>+ <dl className="divide-y divide-border rounded-lg border border-border">+ {section.rows.map((detail) => (+ <DetailItem key={detail.label} detail={detail} />+ ))}+ </dl>+ </section>+ ))}+ </div>+ );+}++/**+ * One label and its value, the labels in one column so values line up. An+ * identifier is set in a fixed-width face with a copy button; a link opens+ * in the browser.+ */+function DetailItem({ detail }: { detail: DetailRow }) {+ return (+ <div className="grid grid-cols-[10rem_minmax(0,1fr)] items-center gap-4 px-4 py-2.5">+ <dt className="text-sm text-foreground-muted">{detail.label}</dt>+ <dd className="flex min-w-0 items-center gap-1">+ {detail.href ? (+ <button+ type="button"+ className="flex min-w-0 items-center gap-1 text-left text-sm text-foreground underline underline-offset-2"+ onClick={() =>+ void openExternalUrl(detail.href!, `Could not open ${detail.label.toLowerCase()}`)+ }+ >+ <span className="truncate">{detail.value}</span>+ <ExternalLink className="size-3.5 shrink-0" />+ </button>+ ) : detail.code ? (+ <>+ <code className="min-w-0 truncate font-mono text-xs" title={detail.value}>+ {detail.value}+ </code>+ <CopyButton value={detail.value} />+ </>+ ) : (+ <span className="min-w-0 text-sm text-foreground">{detail.value}</span>+ )}+ </dd>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-queries.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-queries.tsnew file mode 100644index 000000000..48faa8ac2--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-queries.ts@@ -0,0 +1,27 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback } from 'react';+import { rpc } from '@renderer/lib/ipc';++const connectorAppsKey = (serverId: string) => ['connector-apps', serverId];++/**+ * The server's connector apps, asked for only by its operator; null data+ * means the server has none to set up.+ */+export function useConnectorApps(serverId: string, operator: boolean) {+ return useQuery({+ queryKey: connectorAppsKey(serverId),+ queryFn: () => rpc.switchServers.getConnectorApps(serverId),+ enabled: operator,+ retry: false,+ });+}++/** Re-read the apps after a change, so what a dialog uncovers is already current. */+export function useReloadConnectorApps(serverId: string): () => Promise<void> {+ const queryClient = useQueryClient();+ return useCallback(+ () => queryClient.invalidateQueries({ queryKey: connectorAppsKey(serverId) }),+ [queryClient, serverId]+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-tab.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-tab.tsxnew file mode 100644index 000000000..83ef0b373--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps-tab.tsx@@ -0,0 +1,175 @@+import { ConnectorTile } from '@renderer/features/connectors/connector-tile';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useToast } from '@renderer/lib/hooks/use-toast';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import type { ConnectorApp, ConnectorApps } from '@shared/core/switch-servers/connector-apps';+import {+ type CardAction,+ type MenuAction,+ PUBLIC_URL_BANNER,+ STATE_BADGE,+ actionLabel,+ cardOrder,+ cardState,+ stateLabel,+ tileAction,+ tileStanding,+} from './connector-apps';++/** Whether an app can be set up or changed here now: a vendor needs the public URL first. */+export function changeBlocked(app: ConnectorApp, publicUrl: string | null): boolean {+ return publicUrl === null || app.setup_blocked !== null;+}++/**+ * Opens the dialog for an app's action, and says what it did once it is+ * done. Shared by the tiles and the profile, so a fix does the same thing+ * from either.+ */+export function useConnectorAppDialogs(serverId: string, publicUrl: string | null) {+ const showSetup = useShowModal('connectorAppSetupModal');+ const showSecret = useShowModal('connectorAppSecretModal');+ const showRemove = useShowModal('connectorAppRemoveModal');+ const showMove = useShowModal('connectorAppMoveModal');+ const { toast } = useToast();+ const done = (message: string) => toast({ title: message });+ return (app: ConnectorApp, action: Exclude<CardAction, 'check'> | MenuAction) => {+ const base = { serverId, app, onSuccess: done };+ switch (action) {+ case 'set_up':+ case 'enter_again':+ return showSetup({ ...base, publicUrl, mode: action });+ case 'switch_app':+ return showSetup({ ...base, publicUrl, mode: 'switch' });+ case 'update_secret':+ return showSecret(base);+ case 'remove':+ return showRemove(base);+ case 'manage_here':+ return showMove(base);+ }+ };+}++/**+ * The server operator's connector apps, as tiles like Discover's: the ones+ * that need attention first, then those not set up, then those working. A+ * tile opens the app's profile; the button beside its badge is only ever+ * the one thing that needs doing.+ */+export function ConnectorAppsTab({+ serverId,+ apps,+ catalog,+ query,+ checkFailures,+ onOpen,+}: {+ serverId: string;+ apps: {+ data: ConnectorApps | null | undefined;+ isError: boolean;+ error: unknown;+ refetch: () => unknown;+ };+ catalog: ConnectionCatalogEntry[] | undefined;+ query: string;+ checkFailures: Record<string, string>;+ onOpen: (slug: string) => void;+}) {+ const publicUrl = apps.data?.public_url ?? null;+ const open = useConnectorAppDialogs(serverId, publicUrl);++ if (apps.isError)+ return (+ <Alert variant="destructive">+ <AlertDescription>{failureText(apps.error, 'Could not load the apps.')}</AlertDescription>+ <AlertAction>+ <Button size="sm" variant="outline" onClick={() => void apps.refetch()}>+ Retry+ </Button>+ </AlertAction>+ </Alert>+ );+ if (apps.data === undefined)+ return (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading the apps…+ </p>+ );+ if (apps.data === null)+ return (+ <p className="text-sm text-foreground-muted">This server has no connector apps to set up.</p>+ );++ const categories = new Map(catalog?.map((entry) => [entry.slug, entry.category]));+ const needle = query.trim().toLocaleLowerCase();+ const shown = cardOrder(apps.data.apps, checkFailures).filter(+ (app) =>+ !needle ||+ [app.name, categories.get(app.slug) ?? ''].some((text) =>+ text.toLocaleLowerCase().includes(needle)+ )+ );+ return (+ <div className="space-y-3">+ {publicUrl === null && (+ <Alert>+ <AlertDescription>{PUBLIC_URL_BANNER}</AlertDescription>+ </Alert>+ )}+ {shown.length === 0 ? (+ <p className="text-sm text-foreground-muted">+ {needle ? `No app matches “${query.trim()}”.` : 'This server has no apps to set up.'}+ </p>+ ) : (+ <div+ role="group"+ aria-label="Connector apps"+ className="grid grid-cols-[repeat(auto-fill,minmax(320px,1fr))] gap-3"+ >+ {shown.map((app) => {+ const failure = checkFailures[app.slug] ?? null;+ const state = cardState(app, failure);+ const action = tileAction(app, failure);+ return (+ <ConnectorTile+ key={app.slug}+ slug={app.slug}+ name={app.name}+ inert={false}+ onOpen={() => onOpen(app.slug)}+ control={+ action && (+ <Button+ size="sm"+ variant={action === 'set_up' ? 'default' : 'outline'}+ aria-label={actionLabel(app, action)}+ disabled={changeBlocked(app, publicUrl)}+ onClick={() => open(app, action)}+ >+ {action === 'set_up' ? 'Set up' : actionLabel(app, action)}+ </Button>+ )+ }+ >+ <span className="mt-1 flex flex-wrap items-center gap-2 text-xs text-foreground-muted">+ {categories.get(app.slug)}+ <Badge variant={STATE_BADGE[state]}>{stateLabel(state)}</Badge>+ </span>+ <span className="mt-2 block text-sm text-foreground-muted">+ {tileStanding(app, failure)}+ </span>+ </ConnectorTile>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps.tsnew file mode 100644index 000000000..505cb02b9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/connector-apps.ts@@ -0,0 +1,519 @@+/**+ * What the Admin page's Connector apps tab shows, decided here and only+ * displayed by the components: each app's state, the one sentence and button+ * that go with it, the order, which actions it offers, and the wording of+ * every dialog. Labels follow what Google and GitHub call things, so the+ * operator can copy values across. The gateway dashboard's page reads the+ * same rules from its own copy, until that page is retired.+ */+import type {+ ConnectorApp,+ ConnectorAppField,+ ConnectorAppImpact,+} from '@shared/core/switch-servers/connector-apps';++export type CardState = 'ready' | 'not_set_up' | 'configured' | 'attention';++export type AttentionCause =+ | 'setup_blocked'+ | 'check_failed'+ | 'unreadable'+ | 'load_error'+ | 'saved_ignored'+ | 'stale';++export type CardAction = 'set_up' | 'manage_here' | 'check' | 'update_secret' | 'enter_again';++export interface Attention {+ cause: AttentionCause;+ sentence: string;+ /** The one fix offered beside the sentence; null where there is nothing to press. */+ action: CardAction | null;+}++export type MenuAction = 'update_secret' | 'switch_app' | 'remove';++export type Audience = 'internal' | 'external';++export interface Instruction {+ text: string;+ /** A value to paste at the vendor, offered with a copy button. */+ copy: string | null;+ /** The vendor's page for this step, where it has one of its own. */+ link: { label: string; href: string } | null;+}++export interface SecretField {+ name: Exclude<ConnectorAppField, 'client_id'>;+ label: string;+ /** A file the browser reads (the .pem), never shown. */+ file: boolean;+}++const GOOGLE = 'google-workspace';++export function vendorName(app: Pick<ConnectorApp, 'slug' | 'kind' | 'name'>): string {+ if (app.kind === 'github_app') return 'GitHub';+ if (app.slug === GOOGLE) return 'Google';+ return app.name;+}++/** "12 people in 3 workspaces", "1 person in 1 workspace". */+export function peopleIn(usage: ConnectorAppImpact): string {+ const people = usage.connected_members === 1 ? '1 person' : `${usage.connected_members} people`;+ const workspaces = usage.workspaces === 1 ? '1 workspace' : `${usage.workspaces} workspaces`;+ return `${people} in ${workspaces}`;+}++function variables(app: ConnectorApp): string {+ return app.configuration_variables.join(' and ');+}++/** Copied into Switch, and waiting for the configuration to be removed. */+export function waitingForRestart(app: ConnectorApp): boolean {+ return (+ app.source === 'configuration' &&+ app.saved_ignored &&+ app.saved_client_id !== null &&+ app.saved_client_id === app.client_id+ );+}++/** What needs the operator, most pressing first; null when nothing does. */+export function attention(app: ConnectorApp, checkFailure: string | null): Attention | null {+ // A configured app keeps working: only setting one up here is blocked.+ if (app.setup_blocked !== null && app.source !== 'configuration')+ return { cause: 'setup_blocked', sentence: app.setup_blocked, action: 'set_up' };+ if (checkFailure !== null)+ return { cause: 'check_failed', sentence: checkFailure, action: 'update_secret' };+ if (app.unreadable)+ return {+ cause: 'unreadable',+ sentence: "Switch can't read the saved secret any more.",+ action: 'enter_again',+ };+ if (app.load_error !== null)+ return { cause: 'load_error', sentence: app.load_error, action: 'enter_again' };+ if (app.saved_ignored && !waitingForRestart(app))+ return {+ cause: 'saved_ignored',+ sentence: `Saved here, but ${variables(app)} is still set, so Switch uses that. Remove it and restart Switch.`,+ action: 'manage_here',+ };+ if (app.stale_connections > 0)+ return {+ cause: 'stale',+ sentence:+ app.stale_connections === 1+ ? '1 person still needs to reconnect.'+ : `${app.stale_connections} people still need to reconnect.`,+ action: null,+ };+ return null;+}++export function cardState(app: ConnectorApp, checkFailure: string | null): CardState {+ if (attention(app, checkFailure) !== null) return 'attention';+ if (app.source === 'configuration') return 'configured';+ if (app.source === 'saved') return 'ready';+ return 'not_set_up';+}++export function stateLabel(state: CardState): string {+ switch (state) {+ case 'ready':+ return 'Ready';+ case 'not_set_up':+ return 'Not set up';+ case 'configured':+ return 'Set on the server';+ case 'attention':+ return 'Needs attention';+ }+}++const ORDER: Record<CardState, number> = {+ attention: 0,+ not_set_up: 1,+ configured: 2,+ ready: 3,+};++/** Cards that need attention first, then not set up, then working. */+export function cardOrder(+ apps: ConnectorApp[],+ checkFailures: Record<string, string>+): ConnectorApp[] {+ return [...apps].sort(+ (a, b) =>+ ORDER[cardState(a, checkFailures[a.slug] ?? null)] -+ ORDER[cardState(b, checkFailures[b.slug] ?? null)] || a.name.localeCompare(b.name)+ );+}++export function notSetUpSentence(app: ConnectorApp): string {+ return app.kind === 'github_app'+ ? "People can't connect GitHub until you add Switch's GitHub App."+ : `People can't connect ${app.name} until you add Switch's ${vendorName(app)} client.`;+}++/** The card's one obvious button. */+export function primaryAction(app: ConnectorApp, checkFailure: string | null): CardAction | null {+ const state = cardState(app, checkFailure);+ if (state === 'not_set_up') return 'set_up';+ if (state === 'attention') {+ const fix = attention(app, checkFailure)?.action ?? null;+ return fix ?? (app.source === 'none' ? null : 'check');+ }+ if (state === 'configured')+ return app.deprecated || waitingForRestart(app) ? null : 'manage_here';+ return 'check';+}++export function actionLabel(app: ConnectorApp, action: CardAction): string {+ switch (action) {+ case 'set_up':+ return `Set up ${app.kind === 'github_app' ? 'GitHub' : app.name}`;+ case 'manage_here':+ return 'Manage it here instead';+ case 'check':+ return 'Check it works';+ case 'update_secret':+ return 'Update secret';+ case 'enter_again':+ return 'Enter it again';+ }+}++/** The ⋯ menu: changes split by what they do to the people connected. */+export function menuActions(app: ConnectorApp): MenuAction[] {+ if (app.source === 'saved') return ['update_secret', 'switch_app', 'remove'];+ // Saved, but unusable: it can be entered again, or removed.+ if (app.source === 'none' && app.saved_client_id !== null) return ['remove'];+ return [];+}++export function menuLabel(app: ConnectorApp, action: MenuAction): string {+ switch (action) {+ case 'update_secret':+ return app.kind === 'github_app' ? 'Update secret or private key' : 'Update secret';+ case 'switch_app':+ return 'Use a different app';+ case 'remove':+ return 'Remove';+ }+}++export function configuredSentence(app: ConnectorApp): string {+ if (app.deprecated)+ return 'Using HOSTED_GITHUB_CONFIG_PATH, which names no private key, so GitHub can be connected but not granted. Set up the GitHub App here instead, after unsetting it.';+ const one = app.configuration_variables.length === 1;+ const from = `From ${variables(app)}. Change ${one ? 'it' : 'them'} there, or remove ${one ? 'it' : 'them'} to manage it here.`;+ if (waitingForRestart(app))+ return `${from} A copy is saved here, same client. Remove the ${one ? 'variable' : 'variables'} and restart Switch to use the copy.`;+ return from;+}++export function secretFields(app: Pick<ConnectorApp, 'kind'>): SecretField[] {+ const secret: SecretField = { name: 'client_secret', label: 'Client secret', file: false };+ return app.kind === 'github_app'+ ? [secret, { name: 'private_key', label: 'Private key', file: true }]+ : [secret];+}++/** "ends in ab12", or a key's fingerprint. */+export function secretSummary(app: ConnectorApp): string | null {+ const secret = app.secrets.client_secret;+ const parts = [];+ if (secret?.set) parts.push(secret.last4 ? `Secret ends in ${secret.last4}` : 'Secret set');+ const key = app.secrets.private_key;+ if (key?.set) parts.push(key.fingerprint ? `Key ${key.fingerprint}` : 'Key set');+ return parts.length ? parts.join(' · ') : null;+}++export function usedBy(app: ConnectorApp): string {+ return `Used by ${peopleIn(app)}`;+}++/** Google's choice of who may connect; it changes only the instructions. */+export function asksWhoConnects(app: Pick<ConnectorApp, 'slug'>): boolean {+ return app.slug === GOOGLE;+}++export function audienceText(audience: Audience): string {+ return audience === 'internal'+ ? "Under Audience, choose Internal. Only people in your Google organization can connect, and Google doesn't need to review the app."+ : "Under Audience, choose External, and add the people who will try it as test users. Until Google verifies the app, only test users can connect, and they must reconnect every 7 days. Because Switch reads Drive, Google's review includes a security assessment renewed every year.";+}++const GOOGLE_CLOUD = 'https://console.cloud.google.com';++/** Step 1 of setting up: creating the app at the vendor, one page at a time. */+export function setupInstructions(+ app: ConnectorApp,+ audience: Audience,+ publicUrl: string | null+): Instruction[] {+ const redirect = app.redirect_uri;+ if (app.kind === 'github_app')+ return [+ {+ text: "In GitHub, create a new GitHub App: Settings, Developer settings, GitHub Apps. For an App owned by an organization, start from the organization's settings instead.",+ copy: null,+ link: { label: 'Open GitHub', href: 'https://github.com/settings/apps/new' },+ },+ { text: "Set the Homepage URL to Switch's public URL:", copy: publicUrl, link: null },+ { text: 'Set the Callback URL to:', copy: redirect, link: null },+ { text: 'Keep Expire user authorization tokens turned on.', copy: null, link: null },+ {+ text: "Under Webhook, untick Active. Switch doesn't use GitHub's webhooks, and GitHub asks for a webhook URL while it is ticked.",+ copy: null,+ link: null,+ },+ {+ text: 'Under Repository permissions, set Contents and Pull requests to Read and write.',+ copy: null,+ link: null,+ },+ {+ text: "Under Where can this GitHub App be installed, choose Any account, so people can install it on their own accounts and organizations. Choose Only on this account only if every member's repositories are in your own organization.",+ copy: null,+ link: null,+ },+ {+ text: 'Create the GitHub App. On its page, generate a client secret, then a private key, and keep the downloaded .pem file.',+ copy: null,+ link: null,+ },+ ];+ if (app.slug === GOOGLE)+ return [+ {+ text: 'In Google Cloud, create a project for Switch, or pick an existing one.',+ copy: null,+ link: { label: 'Create a project', href: `${GOOGLE_CLOUD}/projectcreate` },+ },+ {+ text: 'In Google Auth Platform, under Branding, enter an app name people will recognise and a support email.',+ copy: null,+ link: { label: 'Open Branding', href: `${GOOGLE_CLOUD}/auth/branding` },+ },+ {+ text: audienceText(audience),+ copy: null,+ link: { label: 'Open Audience', href: `${GOOGLE_CLOUD}/auth/audience` },+ },+ {+ text: 'Under Clients, create a client of type Web application.',+ copy: null,+ link: { label: 'Open Clients', href: `${GOOGLE_CLOUD}/auth/clients` },+ },+ {+ text: 'Add this under Authorized redirect URIs, create the client, and copy its Client ID and Client secret:',+ copy: redirect,+ link: null,+ },+ {+ text: 'Enable the Google Drive, Docs, Sheets, Slides and Calendar APIs for the project.',+ copy: null,+ link: { label: 'Open the API Library', href: `${GOOGLE_CLOUD}/apis/library` },+ },+ ];+ return [+ {+ text: `Register an OAuth client for Switch at ${app.name}, with this redirect URI:`,+ copy: redirect,+ link: null,+ },+ ];+}++export const UPDATE_SECRET_NOTE = 'Nobody is disconnected.';++/** The warning before switching to another app. */+export function switchWarning(app: ConnectorApp, impact: ConnectorAppImpact): string[] {+ const lines = [+ `Everyone connected through the current app (${peopleIn(impact)}) will need to reconnect, and their agents lose ${app.name} until they do.`,+ ];+ if (app.kind === 'github_app')+ lines.push('They will also need to choose their repositories again.');+ lines.push(+ `If the old app's secret leaked, also delete it at ${vendorName(app)}: tokens already handed to agents stay valid for up to an hour.`+ );+ return lines;+}++export function removeWarning(app: ConnectorApp): string {+ const name = app.name;+ if (app.connected_members === 0) return `Nobody will be able to connect ${name}.`;+ const people =+ app.connected_members === 1 ? 'the 1 person' : `the ${app.connected_members} people`;+ return `Nobody will be able to connect ${name}, and ${people} connected now lose it. They can still disconnect.`;+}++export interface ChecklistItem {+ text: string;+ done: boolean;+}++const HELM_VALUES: Record<string, string> = {+ github: 'switchCore.githubConnectionsSecret and switchCore.githubAppPrivateKeyPath',+ [GOOGLE]: 'switchCore.googleWorkspaceClientSecret',+};++/** Moving off configuration: copy in, remove the configuration, restart. */+export function moveChecklist(app: ConnectorApp): ChecklistItem[] {+ const helm = HELM_VALUES[app.slug];+ 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}.` : ''}`,+ done: false,+ },+ { text: 'Restart Switch.', done: false },+ ];+}++export const sentBackTo = (publicUrl: string): string => `People are sent back to ${publicUrl}.`;++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.';++/** The badge variant for a state: attention reads as a problem, working as done. */+export const STATE_BADGE = {+ attention: 'destructive',+ not_set_up: 'secondary',+ configured: 'outline',+ ready: 'outline',+} as const satisfies Record<CardState, string>;++/**+ * The tile's one line: what needs doing, or who it serves. The long account+ * of where a configured app comes from is the profile's.+ */+export function tileStanding(app: ConnectorApp, checkFailure: string | null): string {+ const needs = attention(app, checkFailure);+ if (needs !== null) return needs.sentence;+ if (cardState(app, checkFailure) === 'not_set_up') return notSetUpSentence(app);+ return usedBy(app);+}++/**+ * The button a tile carries beside its badge: setting up, or the one fix+ * for what needs attention. Checking and moving off configuration are not+ * urgent, so they are the profile's.+ */+export function tileAction(+ app: ConnectorApp,+ checkFailure: string | null+): Exclude<CardAction, 'check' | 'manage_here'> | null {+ const action = primaryAction(app, checkFailure);+ return action === 'check' || action === 'manage_here' ? null : action;+}++export interface DetailRow {+ label: string;+ value: string;+ /** An identifier, shown in a fixed-width face with a copy button. */+ code: boolean;+ href: string | null;+}++export interface DetailSection {+ title: string;+ rows: DetailRow[];+}++/** What GitHub and Google call each value; anything newer is named from its key. */+const DETAIL_LABELS: Record<string, string> = {+ client_secret: 'Client secret',+ private_key: 'Private key',+ slug: 'GitHub App',+};++function detailLabel(name: string): string {+ const known = DETAIL_LABELS[name];+ if (known) return known;+ const words = name.replace(/_/g, ' ');+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function row(label: string, value: string, code = false, href: string | null = null): DetailRow {+ return { label, value, code, href };+}++/**+ * An app's details in the same three sections for every app, so the+ * operator finds a value in the same place whichever app it is: what+ * identifies it at the vendor, how Switch holds it, and what it means for+ * the people who connect. The values an app has are read from what the+ * server sends (its fields and its secrets), so an app added later shows+ * its own with no change here; a section with nothing to say is left out.+ */+export function appDetails(+ app: ConnectorApp,+ publicUrl: string | null,+ formatDate: (iso: string) => string+): DetailSection[] {+ const credentials: DetailRow[] = [];+ const clientId = app.client_id ?? app.saved_client_id;+ if (clientId !== null) credentials.push(row('Client ID', clientId, true));+ for (const [name, value] of Object.entries(app.fields)) {+ if (!value) continue;+ credentials.push(+ name === 'slug' && app.kind === 'github_app'+ ? row(detailLabel(name), value, false, `https://github.com/apps/${value}`)+ : row(detailLabel(name), value)+ );+ }+ for (const [name, secret] of Object.entries(app.secrets)) {+ const label = detailLabel(name);+ if (!secret.set) credentials.push(row(label, 'Not set'));+ else if (secret.fingerprint) credentials.push(row(label, secret.fingerprint, true));+ else if (secret.last4) credentials.push(row(label, `•••• ${secret.last4}`));+ else credentials.push(row(label, 'Set'));+ }++ const setup: DetailRow[] = [+ row(+ 'Source',+ app.source === 'configuration'+ ? `Server configuration (${variables(app)})`+ : app.source === 'saved'+ ? 'Saved in Switch'+ : 'Not set up'+ ),+ ];+ if (app.redirect_uri !== null)+ setup.push(+ row(app.kind === 'github_app' ? 'Callback URL' : 'Redirect URI', app.redirect_uri, true)+ );+ if (app.updated_at !== null)+ setup.push(+ row(+ 'Last changed',+ `${app.updated_by_name ?? 'A deleted account'} · ${formatDate(app.updated_at)}`+ )+ );++ const people: DetailRow[] = [];+ if (publicUrl !== null) people.push(row('Sent back to', publicUrl));+ if (app.install_url !== null)+ people.push(row('Install page', app.install_url, false, app.install_url));+ if (app.stale_connections > 0)+ people.push(+ row(+ 'Need to reconnect',+ app.stale_connections === 1 ? '1 person' : `${app.stale_connections} people`+ )+ );++ return [+ { title: 'Credentials', rows: credentials },+ { title: 'Setup', rows: setup },+ { title: 'For people who connect', rows: people },+ ].filter((section) => section.rows.length > 0);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/copy-button.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/copy-button.tsxnew file mode 100644index 000000000..535805c1a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/copy-button.tsx@@ -0,0 +1,28 @@+import { Check, Copy } from 'lucide-react';+import { useState } from 'react';+import { Button } from '@renderer/lib/ui/button';++/** Copies `value`, and says so for two seconds. */+export function CopyButton({ value }: { value: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={copied ? 'Copied' : `Copy ${value}`}+ title={copied ? 'Copied' : 'Copy'}+ onClick={() =>+ void navigator.clipboard.writeText(value).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ })+ }+ >+ {copied ? (+ <Check className="size-3.5 text-foreground-success" />+ ) : (+ <Copy className="size-3.5" />+ )}+ </Button>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches-tab.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches-tab.tsxnew file mode 100644index 000000000..386a4d350--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches-tab.tsx@@ -0,0 +1,178 @@+import { format } from 'date-fns';+import { useState } from 'react';+import {+ switchOffConfirmation,+ workspaceSwitchNote,+} from '@renderer/features/connectors/connector-copy';+import { ConnectorTile } from '@renderer/features/connectors/connector-tile';+import {+ useConnectorCatalog,+ useReloadConnectors,+ useWorkspaceServices,+} from '@renderer/features/connectors/connectors-queries';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { Switch } from '@renderer/lib/ui/switch';+import type { WorkspaceService } from '@shared/core/switch-servers/connection-catalog';+import { switchStanding, switchTiles } from './workspace-switches';++type Outcome = { warning: string | null; error: string | null };++/**+ * A workspace admin's switch for each service, as tiles like Discover's.+ * Switching one off reaches other people's running sessions, so when anyone+ * is connected or any agent uses it, it asks first, naming both counts. A+ * switch shows what the server says: it never flips before the server has+ * answered, and a failure leaves it as it was, with the reason under it.+ */+export function WorkspaceSwitchesTab({+ workspaceId,+ query,+}: {+ workspaceId: string;+ query: string;+}) {+ const services = useWorkspaceServices(workspaceId);+ const catalog = useConnectorCatalog(workspaceId);+ const reload = useReloadConnectors(workspaceId);+ const confirm = useShowModal('confirmActionModal');+ const [pending, setPending] = useState<ReadonlySet<string>>(new Set());+ const [outcomes, setOutcomes] = useState<Record<string, Outcome>>({});++ const change = async (service: WorkspaceService, enabled: boolean) => {+ setPending((now) => new Set(now).add(service.slug));+ setOutcomes((now) => ({ ...now, [service.slug]: { warning: null, error: null } }));+ try {+ const result = await rpc.workspaces.setWorkspaceService({+ workspaceId,+ service: service.slug,+ enabled,+ });+ setOutcomes((now) => ({ ...now, [service.slug]: { warning: result.warning, error: null } }));+ await reload();+ } catch (cause) {+ setOutcomes((now) => ({+ ...now,+ [service.slug]: {+ warning: null,+ error: failureText(+ cause,+ `Could not switch ${service.name} ${enabled ? 'on' : 'off'} for the workspace.`+ ),+ },+ }));+ } finally {+ setPending((now) => {+ const next = new Set(now);+ next.delete(service.slug);+ return next;+ });+ }+ };+ const flip = (service: WorkspaceService, enabled: boolean) => {+ const asked = enabled ? null : switchOffConfirmation(service);+ if (asked)+ confirm({+ title: asked.title,+ description: asked.description,+ confirmLabel: 'Switch off',+ onSuccess: () => void change(service, false),+ });+ else void change(service, enabled);+ };++ if (services.isError)+ return (+ <Alert variant="destructive">+ <AlertDescription>+ {failureText(services.error, "Could not load the workspace's services.")}+ </AlertDescription>+ <AlertAction>+ <Button size="sm" variant="outline" onClick={() => void services.refetch()}>+ Retry+ </Button>+ </AlertAction>+ </Alert>+ );+ if (services.data === undefined)+ return (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading the workspace's services…+ </p>+ );+ if (services.data === null)+ return (+ <p className="text-sm text-foreground-muted">+ This server can't switch services on or off for a workspace. Every service it offers is+ on.+ </p>+ );++ const tiles = switchTiles(services.data, catalog.data, query);+ if (tiles.length === 0)+ return (+ <p className="text-sm text-foreground-muted">+ {query.trim()+ ? `No service matches “${query.trim()}”.`+ : 'This server offers no services to switch.'}+ </p>+ );+ return (+ <div+ role="group"+ aria-label="Workspace connectors"+ className="grid grid-cols-[repeat(auto-fill,minmax(320px,1fr))] gap-3"+ >+ {tiles.map(({ service, category }) => {+ const outcome = outcomes[service.slug];+ const busy = pending.has(service.slug);+ return (+ <ConnectorTile+ key={service.slug}+ slug={service.slug}+ name={service.name}+ inert={false}+ onOpen={null}+ control={+ <>+ {busy && <Spinner />}+ <Switch+ aria-label={`${service.name} for this workspace`}+ checked={service.enabled}+ disabled={busy}+ onCheckedChange={(on) => flip(service, on)}+ />+ </>+ }+ >+ {category && (+ <span className="mt-1 block text-xs text-foreground-muted">{category}</span>+ )}+ <span className="mt-2 block text-sm text-foreground-muted">+ {switchStanding(service)}+ </span>+ {service.updated_at !== null && (+ <span className="mt-1 block text-xs text-foreground-muted">+ {workspaceSwitchNote(service, (iso) => format(new Date(iso), 'MMM d, yyyy'))}+ </span>+ )}+ {outcome?.warning && (+ <span role="status" className="mt-1 block text-xs text-foreground-warning">+ {outcome.warning}+ </span>+ )}+ {outcome?.error && (+ <span role="alert" className="mt-1 block text-xs text-destructive">+ {outcome.error}+ </span>+ )}+ </ConnectorTile>+ );+ })}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches.tsnew file mode 100644index 000000000..91e10ca0a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/workspace-switches.ts@@ -0,0 +1,44 @@+import type {+ ConnectionCatalogEntry,+ WorkspaceService,+} from '@shared/core/switch-servers/connection-catalog';++export type SwitchTile = {+ service: WorkspaceService;+ /** The catalog's category; null while the catalog is not read, or lists no such service. */+ category: string | null;+};++/**+ * The workspace's switches as tiles, narrowed by the search, in the server's+ * order. The order never follows the switches' state, so a tile stays where+ * it was when it is flipped. The category comes from the catalog, which the+ * switches' own list does not carry.+ */+export function switchTiles(+ services: WorkspaceService[],+ catalog: ConnectionCatalogEntry[] | undefined,+ query: string+): SwitchTile[] {+ const categories = new Map(catalog?.map((entry) => [entry.slug, entry.category]));+ const needle = query.trim().toLocaleLowerCase();+ return services+ .map((service) => ({ service, category: categories.get(service.slug) ?? null }))+ .filter(+ ({ service, category }) =>+ !needle ||+ [service.name, category ?? ''].some((text) => text.toLocaleLowerCase().includes(needle))+ );+}++/** Who a switch reaches: the members who have connected the service, and the agents using it. */+export function switchStanding(+ service: Pick<WorkspaceService, 'connected_members' | 'granted_agents'>+): string {+ const members = service.connected_members;+ const agents = service.granted_agents;+ if (members === 0 && agents === 0) return 'Nobody has connected it yet';+ const connected = `${members} ${members === 1 ? 'member' : 'members'} connected`;+ const using = `${agents} ${agents === 1 ? 'agent uses' : 'agents use'} it`;+ return `${connected} · ${using}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.tsnew file mode 100644index 000000000..37e7bed18--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from 'vitest';+import { LocalAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';+import { AgentTabStore } from '@renderer/features/managed-agents/agent-tab-store';+import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';+import type { Agent } from '@shared/core/agents/agents';+import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { ELSEWHERE_TITLE, agentLinkFor, openAgentConnections } from './agent-links';++const LOCAL: Agent = {+ id: 'local-1',+ locationId: 'location-1',+ name: 'm1-cc',+ providerId: 'claude',+ switchAgentId: 'switch-local',+ apiEndpoint: null,+ workspaceId: 'workspace',+ serverId: 'server',+ status: null,+ autoApprove: false,+ ownerName: null,+ providerConfig: null,+ createdAt: '2026-10-16T00:00:00Z',+ updatedAt: '2026-10-16T00:00:00Z',+};++const MANAGED: ManagedAgentView = {+ serverId: 'server',+ workspaceId: 'workspace',+ agentId: 'switch-managed',+ name: 'm3-managed',+ displayName: 'M3',+ iconUrl: null,+ description: '',+ machine: null,+ desiredState: 'running',+ revision: 1,+ definition: {+ provider: 'claude',+ model: null,+ advancedConfig: {},+ instructions: '',+ autoApprove: false,+ directory: null,+ isolation: 'shared',+ },+ status: null,+};++describe("a Used by chip's link", () => {+ it("opens a local agent's page by its location and name", () => {+ expect(agentLinkFor('switch-local', [LOCAL], [MANAGED])).toEqual({+ kind: 'local',+ agentId: 'local-1',+ locationId: 'location-1',+ agentName: 'm1-cc',+ });+ });++ it("opens a managed agent's page under the name the sidebar gives it", () => {+ expect(agentLinkFor('switch-managed', [LOCAL], [MANAGED])).toEqual({+ kind: 'managed',+ serverId: 'server',+ agentId: 'switch-managed',+ name: 'M3',+ });+ });++ it('opens a managed agent that still has a local row as managed', () => {+ const moved = { ...LOCAL, switchAgentId: 'switch-managed' };+ expect(agentLinkFor('switch-managed', [moved], [MANAGED]).kind).toBe('managed');+ });++ it('leads nowhere for an agent this Console does not have, and says why', () => {+ expect(agentLinkFor('switch-other', [LOCAL], [MANAGED])).toEqual({+ kind: 'elsewhere',+ title: ELSEWHERE_TITLE,+ });+ expect(agentLinkFor('switch-managed', [LOCAL], null).kind).toBe('elsewhere');+ });+});++describe("opening an agent's Connections tab", () => {+ const stores = () => ({ local: new LocalAgentTabStore(), managed: new AgentTabStore() });++ it('selects the tab on a local agent, then opens its page', () => {+ const tabs = stores();+ const navigate = vi.fn();+ openAgentConnections(+ agentLinkFor('switch-local', [LOCAL], null) as Parameters<typeof openAgentConnections>[0],+ navigate as unknown as NavigateFnTyped,+ tabs+ );+ expect(tabs.local.tabFor('local-1')).toBe('connections');+ expect(navigate).toHaveBeenCalledWith('location', {+ locationId: 'location-1',+ agentName: 'm1-cc',+ });+ });++ it('selects the tab on a managed agent, then opens its page', () => {+ const tabs = stores();+ const navigate = vi.fn();+ openAgentConnections(+ agentLinkFor('switch-managed', [], [MANAGED]) as Parameters<typeof openAgentConnections>[0],+ navigate as unknown as NavigateFnTyped,+ tabs+ );+ expect(tabs.managed.tabFor('switch-managed')).toBe('connections');+ expect(navigate).toHaveBeenCalledWith('managedAgent', {+ serverId: 'server',+ agentId: 'switch-managed',+ name: 'M3',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.tsnew file mode 100644index 000000000..eddc7e585--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/agent-links.ts@@ -0,0 +1,64 @@+import type { LocalAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';+import type { AgentTabStore } from '@renderer/features/managed-agents/agent-tab-store';+import { managedAgentLabel } from '@renderer/features/managed-agents/managed-agent-state';+import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';+import type { Agent } from '@shared/core/agents/agents';+import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';++/**+ * Where an agent named on a connector's profile leads: its Connections tab,+ * on the page this Console shows it on, or nowhere for an agent that lives in+ * another Console.+ */+export type AgentLink =+ | { kind: 'local'; agentId: string; locationId: string; agentName: string }+ | { kind: 'managed'; serverId: string; agentId: string; name: string }+ | { kind: 'elsewhere'; title: string };++export const ELSEWHERE_TITLE =+ 'This agent runs from another Switch Console, so it has no page here.';++/**+ * The link for the Switch agent `agentId`. The server runs a managed agent, so+ * one this Console also keeps a local row for opens as managed, the way the+ * sidebar shows it. `managedAgents` is null or undefined while the server has+ * no agent management or the list has not come back.+ */+export function agentLinkFor(+ agentId: string,+ localAgents: readonly Agent[],+ managedAgents: readonly ManagedAgentView[] | null | undefined+): AgentLink {+ const managed = managedAgents?.find((agent) => agent.agentId === agentId);+ if (managed)+ return {+ kind: 'managed',+ serverId: managed.serverId,+ agentId: managed.agentId,+ name: managedAgentLabel(managed),+ };+ const local = localAgents.find((agent) => agent.switchAgentId === agentId);+ if (local)+ return {+ kind: 'local',+ agentId: local.id,+ locationId: local.locationId,+ agentName: local.name,+ };+ return { kind: 'elsewhere', title: ELSEWHERE_TITLE };+}++/** Opens a linked agent's page on its Connections tab. */+export function openAgentConnections(+ link: Exclude<AgentLink, { kind: 'elsewhere' }>,+ navigate: NavigateFnTyped,+ tabs: { local: LocalAgentTabStore; managed: AgentTabStore }+): void {+ if (link.kind === 'local') {+ tabs.local.setTab(link.agentId, 'connections');+ navigate('location', { locationId: link.locationId, agentName: link.agentName });+ return;+ }+ tabs.managed.setTab(link.agentId, 'connections');+ navigate('managedAgent', { serverId: link.serverId, agentId: link.agentId, name: link.name });+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-flow.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-flow.tsnew file mode 100644index 000000000..0f7d7938f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-flow.ts@@ -0,0 +1,86 @@+import type { ServiceFlow } from '@shared/core/switch-servers/service-connection';+import { RpcError } from '@shared/lib/ipc/rpc-error';++/**+ * A service sign-in as the dialog holds it: the flow Switch is running for+ * it, if any, and what the person is shown.+ */+export type ConnectFlowState = {+ connected: boolean;+ flowId: string | null;+ flow: ServiceFlow | null;+ busy: boolean;+ warning: string | null;+ error: string | null;+};++export type ConnectFlowEvent =+ /** An action begins: start, cancel or disconnect. */+ | { type: 'act' }+ | { type: 'started'; flowId: string }+ /** The flow is still under way, or failed; `failure` is what to say if it failed without saying why. */+ | { type: 'polled'; flow: ServiceFlow; failure: string }+ | { type: 'poll_failed'; error: string }+ /** The server kept the connection; the flow is over. */+ | { type: 'connected'; warning: string | null }+ | { type: 'cancelled' }+ | { type: 'cancel_failed'; cause: unknown; error: string }+ | { type: 'disconnected'; warning: string | null }+ /** Starting or disconnecting failed; nothing about a flow changes. */+ | { type: 'failed'; error: string };++export function initialConnectFlow(connected: boolean): ConnectFlowState {+ return { connected, flowId: null, flow: null, busy: false, warning: null, error: null };+}++const NO_FLOW = { flowId: null, flow: null } as const;++/**+ * The sign-in's state after `event`. A flow that failed keeps its id, so the+ * person can cancel it and start over with the reason still showing. A cancel+ * the server answers with 410 found the flow already gone, which is what+ * cancelling wanted.+ */+export function connectFlowReducer(+ state: ConnectFlowState,+ event: ConnectFlowEvent+): ConnectFlowState {+ switch (event.type) {+ case 'act':+ return { ...state, busy: true, error: null };+ case 'started':+ return { ...state, busy: false, flowId: event.flowId, flow: null, warning: null };+ case 'polled':+ return {+ ...state,+ flow: event.flow,+ error: event.flow.status === 'failed' ? (event.flow.error ?? event.failure) : state.error,+ };+ case 'poll_failed':+ return { ...state, ...NO_FLOW, error: event.error };+ case 'connected':+ return { ...state, ...NO_FLOW, busy: false, connected: true, warning: event.warning };+ case 'cancelled':+ return { ...state, ...NO_FLOW, busy: false, error: null };+ case 'cancel_failed':+ return isGone(event.cause)+ ? { ...state, ...NO_FLOW, busy: false, error: null }+ : { ...state, busy: false, error: event.error };+ case 'disconnected':+ return { ...state, busy: false, connected: false, warning: event.warning };+ case 'failed':+ return { ...state, busy: false, error: event.error };+ }+}++/**+ * Whether the dialog may close: never mid-call, and not while a sign-in is+ * under way unless an error is showing, so a refusal can never strand it.+ */+export function canCloseConnectFlow(state: ConnectFlowState): boolean {+ return !state.busy && (state.flowId === null || state.error !== null);+}++function isGone(cause: unknown): boolean {+ return cause instanceof RpcError && cause.numberField('status') === 410;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-service-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-service-modal.tsxnew file mode 100644index 000000000..43bd9a33c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connect-service-modal.tsx@@ -0,0 +1,78 @@+import { ManagedGitHubStep } from '@renderer/features/switch-servers/managed-github-step';+import { workspaceServiceCalls } from '@renderer/features/switch-servers/service-calls';+import { ServiceConnectStep } from '@renderer/features/switch-servers/service-connect-step';+import { ServiceKeyStep } from '@renderer/features/switch-servers/service-key-step';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { offersAddAgent } from './grant-agents';++/**+ * Connecting one service from its Connectors profile: GitHub's own step, a key+ * form, or the generic sign-in, as the catalog entry calls for. A service the+ * person then adds agents to from its page closes the dialog as soon as it is+ * connected, so the page, with its Add agent search open, is what they see+ * next. GitHub's stays open once connected, showing the repositories reached,+ * until Done; the page behind is already current. `startAt: 'replace'` opens+ * on the form that replaces a connected key, which keeps every agent's access.+ */+export function ConnectServiceModal({+ serverId,+ workspaceId,+ connection,+ startAt,+ onConnected,+ onClose,+}: {+ serverId: string;+ workspaceId: string;+ connection: ConnectionCatalogEntry;+ startAt: 'connect' | 'replace';+ /** Runs as soon as the service is connected, with the warning Switch gave. */+ onConnected: (warning: string | null) => void;+} & BaseModalProps) {+ const calls = workspaceServiceCalls(workspaceId);+ const connected = (warning: string | null) => {+ onConnected(warning);+ if (offersAddAgent(connection)) onClose();+ };++ if (startAt === 'replace' && connection.key)+ return (+ <ServiceKeyStep+ calls={calls}+ connection={connection}+ form={connection.key}+ replacing+ onBack={onClose}+ onConnected={onConnected}+ />+ );+ if (connection.slug === 'github')+ return (+ <ManagedGitHubStep+ serverId={serverId}+ onBack={onClose}+ onDone={onClose}+ onConnected={onConnected}+ />+ );+ if (connection.key)+ return (+ <ServiceKeyStep+ calls={calls}+ connection={connection}+ form={connection.key}+ replacing={false}+ onBack={onClose}+ onConnected={connected}+ />+ );+ return (+ <ServiceConnectStep+ calls={calls}+ connection={connection}+ onBack={onClose}+ onConnected={connected}+ />+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsxnew file mode 100644index 000000000..fadd2636b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-agents-section.tsx@@ -0,0 +1,439 @@+import { ExternalLink, Plus, Search, X } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { localAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';+import { agentTabStore } from '@renderer/features/managed-agents/agent-tab-store';+import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';+import { agentProviderLabelFor } from '@renderer/lib/components/agent-picker';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate } from '@renderer/lib/layout/navigation-provider';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';+import { Button } from '@renderer/lib/ui/button';+import {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+} from '@renderer/lib/ui/input-group';+import { Spinner } from '@renderer/lib/ui/spinner';+import { cn } from '@renderer/utils/utils';+import type {+ ConnectionAgent,+ ConnectionCatalogEntry,+} from '@shared/core/switch-servers/connection-catalog';+import { agentLinkFor, openAgentConnections } from './agent-links';+import {+ useConnectionAgents,+ useGitHubConnection,+ useReloadConnectors,+} from './connectors-queries';+import { NO_REPOSITORIES_NOTE } from './github-access';+import { GitHubAddAgentChoice } from './github-add-agent-choice';+import {+ type GitHubGrantChoice,+ connectedGitHub,+ emptyGitHubGrant,+ githubGrantResources,+} from './github-grant';+import {+ OPEN_AGENT_NOTE,+ addAgentIntro,+ addableAgents,+ agentsSummary,+ agentsUnlistedText,+ noAgentsText,+ offersAddAgent,+} from './grant-agents';++/**+ * The agents using the connector, drawn as a room's participants are: a+ * heading with the count, a card per agent, and an "Add agent" that opens a+ * search of the person's other agents under the cards. Adding one turns the+ * service on for it there and then; the cross on a card turns it off again.+ * A card opens the agent's Connections tab; an agent from another Console has+ * no page here, so its card is plain.+ */+export const ConnectorAgentsSection = observer(function ConnectorAgentsSection({+ serverId,+ workspaceId,+ connection,+ connected,+ adding,+ onAddingChange,+ notice,+}: {+ serverId: string;+ workspaceId: string;+ connection: ConnectionCatalogEntry;+ /** The person has a usable connection, so agents can be added. */+ connected: boolean;+ adding: boolean;+ onAddingChange: (adding: boolean) => void;+ /** What connecting left to say, shown above the search while it is open. */+ notice: string | null;+}) {+ const name = connection.name;+ const agents = useConnectionAgents(workspaceId, connection.slug);+ const remote = useWorkspaceAgents(workspaceId);+ const iconFor = (agentId: string) =>+ remote.data?.find((agent) => agent.id === agentId)?.iconUrl ?? null;+ const usedBy = agents.data?.filter((agent) => agent.granted) ?? [];+ const { navigate } = useNavigate();+ const managed = useManagedAgents(serverId);+ const local = agentsStore.agentsInWorkspace(workspaceId);+ const canAdd = connected && offersAddAgent(connection) && agents.data != null;+ const reload = useReloadConnectors(workspaceId);+ const [removingId, setRemovingId] = useState<string | null>(null);+ const [removal, setRemoval] = useState<{ error: string | null; warning: string | null }>({+ error: null,+ warning: null,+ });+ async function remove(agent: ConnectionAgent) {+ setRemovingId(agent.agent_id);+ setRemoval({ error: null, warning: null });+ try {+ const warning = await rpc.workspaces.removeServiceGrant({+ workspaceId,+ agentId: agent.agent_id,+ service: connection.slug,+ });+ setRemoval({ error: null, warning });+ await reload();+ } catch (cause) {+ setRemoval({+ error: failureText(cause, `Could not turn ${name} off for ${agent.name}.`),+ warning: null,+ });+ } finally {+ setRemovingId(null);+ }+ }++ return (+ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-baseline gap-2">+ <h2 className="text-sm font-semibold text-foreground">Agents</h2>+ {agents.data && (+ <span className="text-xs text-foreground-muted">{agentsSummary(usedBy.length)}</span>+ )}+ </div>+ {canAdd && (+ <Button+ variant="outline"+ size="sm"+ aria-expanded={adding}+ onClick={() => onAddingChange(!adding)}+ >+ <Plus className="size-3.5" />+ Add agent+ </Button>+ )}+ </div>++ {agents.isPending && (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading your agents…+ </p>+ )}+ {agents.isError && (+ <p role="alert" className="text-sm text-destructive">+ {failureText(agents.error, 'Could not load which of your agents use it.')}+ </p>+ )}+ {agents.data === null && (+ <p className="text-sm text-foreground-muted">{agentsUnlistedText(name)}</p>+ )}+ {agents.data && agents.data.length === 0 && (+ <p className="text-sm text-foreground-muted">{noAgentsText(name)}</p>+ )}+ {agents.data && agents.data.length > 0 && usedBy.length === 0 && (+ <p className="text-sm text-foreground-muted">None of your agents use {name} yet.</p>+ )}+ {usedBy.length > 0 && (+ <div role="list" aria-label="Agents" className="grid grid-cols-2 gap-2.5">+ {usedBy.map((agent) => {+ const link = agentLinkFor(agent.agent_id, local, managed.data);+ const body = (+ <>+ <span className="flex size-7 shrink-0 items-center justify-center">+ <AgentAvatar+ name={agent.name}+ iconUrl={iconFor(agent.agent_id)}+ serverId={serverId}+ size={26}+ />+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium text-foreground">{agent.name}</span>+ <span className="truncate text-xs text-foreground-muted">+ {agentProviderLabelFor(agent.agent_id, workspaceId)}+ </span>+ </span>+ </>+ );+ return (+ <div+ key={agent.agent_id}+ role="listitem"+ title={link.kind === 'elsewhere' ? link.title : undefined}+ className={cn(+ 'group relative flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] py-3 pr-9 pl-3.5 transition-colors',+ link.kind !== 'elsewhere' && 'hover:bg-[var(--fill)]'+ )}+ >+ {link.kind === 'elsewhere' ? (+ body+ ) : (+ <button+ type="button"+ title={`Open ${agent.name}'s Connections tab`}+ onClick={() =>+ openAgentConnections(link, navigate, {+ local: localAgentTabStore,+ managed: agentTabStore,+ })+ }+ className="focus-visible:ring-ring flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-sm text-left focus-visible:ring-2 focus-visible:outline-none"+ >+ {/* Stretched over the card, so the whole card opens the agent while+ the cross beside it keeps its own target. */}+ <span aria-hidden className="absolute inset-0 rounded-[10px]" />+ {body}+ </button>+ )}+ <button+ type="button"+ aria-label={`Turn ${name} off for ${agent.name}`}+ title={`Turn ${name} off for ${agent.name}`}+ disabled={removingId !== null}+ onClick={() => void remove(agent)}+ className="absolute top-1.5 right-1.5 z-10 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100 disabled:cursor-wait"+ >+ {removingId === agent.agent_id ? <Spinner /> : <X className="size-3.5" />}+ </button>+ </div>+ );+ })}+ </div>+ )}+ {removal.error && (+ <p role="alert" className="text-xs text-destructive">+ Not turned off — {removal.error}+ </p>+ )}+ {removal.warning && (+ <p role="status" className="text-xs text-foreground-muted">+ {removal.warning}+ </p>+ )}++ {canAdd && adding && agents.data && (+ <AddAgentPanel+ serverId={serverId}+ workspaceId={workspaceId}+ connection={connection}+ agents={agents.data}+ iconFor={iconFor}+ notice={notice}+ />+ )}+ {!offersAddAgent(connection) && (+ <p className="text-xs text-foreground-muted">+ Turn it on for an agent from the agent's Connections tab.+ </p>+ )}+ {connection.slug === 'github' && usedBy.length > 0 && (+ <p className="text-xs text-foreground-muted">+ Each agent has its own repositories and access, changed on its Connections tab.+ </p>+ )}+ </section>+ );+});++/**+ * Search the person's agents and turn the service on for one. An agent others+ * can address is offered with a note in place of what runs it, since whoever+ * addresses it would have it act as the person. For GitHub, the repositories+ * and access every added agent gets are chosen above the search, and no+ * agent can be added until some are; each agent's own choice is on its+ * Connections tab.+ */+const AddAgentPanel = observer(function AddAgentPanel({+ serverId,+ workspaceId,+ connection,+ agents,+ iconFor,+ notice,+}: {+ serverId: string;+ workspaceId: string;+ connection: ConnectionCatalogEntry;+ agents: ConnectionAgent[];+ iconFor: (agentId: string) => string | null;+ notice: string | null;+}) {+ const name = connection.name;+ const isGitHub = connection.slug === 'github';+ const reload = useReloadConnectors(workspaceId);+ const github = useGitHubConnection(workspaceId, isGitHub);+ const [choice, setChoice] = useState<GitHubGrantChoice | null>(null);+ const [choosing, setChoosing] = useState(false);+ useEffect(() => {+ if (isGitHub && choice === null && github.data) setChoice(emptyGitHubGrant(github.data));+ }, [isGitHub, choice, github.data]);+ const [filter, setFilter] = useState('');+ const [busyId, setBusyId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [warning, setWarning] = useState<string | null>(null);+ const candidates = addableAgents(agents, filter);+ const query = filter.trim();+ const reach = connectedGitHub(github.data);+ const resources = isGitHub ? (choice ? githubGrantResources(choice) : null) : {};+ const noRepositories = reach !== null && reach.installations.length === 0;++ async function add(agentId: string) {+ if (resources === null) return;+ setBusyId(agentId);+ setError(null);+ try {+ const result = await rpc.workspaces.setServiceGrant({+ workspaceId,+ agentId,+ service: connection.slug,+ access: isGitHub && choice ? choice.access : null,+ resources,+ });+ setWarning(result);+ await reload();+ } catch (cause) {+ setError(failureText(cause, `Could not turn ${name} on for the agent.`));+ } finally {+ setBusyId(null);+ }+ }++ return (+ <div className="flex flex-col gap-2 pt-1">+ {notice && (+ <p role="status" className="rounded-md border p-3 text-sm text-foreground-muted">+ {notice}+ </p>+ )}+ {isGitHub && reach && !noRepositories && choice ? (+ <GitHubAddAgentChoice+ github={reach}+ choice={choice}+ onChange={setChoice}+ choosing={choosing}+ onChoosingChange={setChoosing}+ />+ ) : (+ <p className="text-sm text-foreground-muted">{addAgentIntro(connection)}</p>+ )}+ {isGitHub && github.isError && (+ <p role="alert" className="text-xs text-destructive">+ {failureText(github.error, 'Could not load your GitHub repositories.')}+ </p>+ )}+ {isGitHub && noRepositories && (+ <div className="flex items-center gap-3 rounded-lg border border-border p-3">+ <p className="flex-1 text-sm text-foreground-muted">{NO_REPOSITORIES_NOTE}</p>+ <Button+ size="sm"+ variant="outline"+ onClick={() => void rpc.switchServers.openGitHubInstallation(serverId)}+ >+ Choose repositories <ExternalLink className="size-3.5" />+ </Button>+ </div>+ )}+ <InputGroup>+ <InputGroupAddon>+ <Search className="size-3.5 text-foreground-muted" />+ </InputGroupAddon>+ <InputGroupInput+ autoFocus+ placeholder="Search your agents…"+ aria-label="Search agents to add"+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ />+ {filter !== '' && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ size="icon-xs"+ aria-label="Clear the search"+ onClick={() => setFilter('')}+ >+ <X className="size-3.5" />+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>++ {error !== null && <p className="text-xs text-destructive">Not added — {error}</p>}+ {warning !== null && (+ <p role="status" className="text-xs text-foreground-muted">+ {warning}+ </p>+ )}++ {candidates.length === 0 ? (+ <p className="px-1 py-2 text-sm text-foreground-muted">+ {query === ''+ ? `Every one of your agents already uses ${name}.`+ : `No agent here matches “${query}”.`}+ </p>+ ) : (+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {candidates.map((agent) => {+ const busy = busyId === agent.agent_id;+ return (+ <button+ key={agent.agent_id}+ type="button"+ disabled={busyId !== null || resources === null}+ onClick={() => void add(agent.agent_id)}+ className={cn(+ 'flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]',+ busyId !== null && 'cursor-wait'+ )}+ >+ <AgentAvatar+ name={agent.name}+ iconUrl={iconFor(agent.agent_id)}+ serverId={serverId}+ size={22}+ />+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">+ {agent.name}+ </span>+ <span+ className={cn(+ 'shrink-0 text-xs',+ agent.addressing_open+ ? 'text-amber-600 dark:text-amber-500'+ : 'text-foreground-muted'+ )}+ >+ {agent.addressing_open+ ? OPEN_AGENT_NOTE+ : agentProviderLabelFor(agent.agent_id, workspaceId)}+ </span>+ <span className="shrink-0 text-xs font-medium text-foreground">+ {busy ? 'Adding…' : 'Add'}+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-card-state.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-card-state.tsnew file mode 100644index 000000000..0c7c444cd--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-card-state.ts@@ -0,0 +1,61 @@+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';++export type ConnectorCardKind =+ | 'coming_soon'+ | 'unavailable'+ | 'workspace_off'+ | 'reconnect'+ | 'connected'+ | 'connect';++export type ConnectorCardState = {+ kind: ConnectorCardKind;+ /** The card's badge. */+ label: string;+ /** Why, under the badge; null when the badge says it all. */+ detail: string | null;+ tone: 'muted' | 'problem' | 'good';+};++/**+ * The one state a connector's card shows. When several apply, the first of+ * these wins: not built yet, not usable on this server (its reason is the+ * server's), switched off in this workspace, needing a fresh sign-in,+ * connected, and otherwise ready to connect. A server without the workspace+ * switch sends no `workspace_enabled`, which reads as on.+ */+export function connectorCardState(entry: ConnectionCatalogEntry): ConnectorCardState {+ if (entry.status === 'coming_soon')+ return { kind: 'coming_soon', label: 'Coming soon', detail: null, tone: 'muted' };+ if (entry.unavailable_reason !== null)+ return {+ kind: 'unavailable',+ label: 'Unavailable',+ detail: entry.unavailable_reason,+ tone: 'muted',+ };+ if (entry.workspace_enabled === false)+ return {+ kind: 'workspace_off',+ label: 'Off in this workspace',+ detail: 'A workspace admin has switched it off.',+ tone: 'muted',+ };+ if (entry.status === 'needs_reauthorization' || entry.status === 'error')+ return {+ kind: 'reconnect',+ label: entry.status === 'error' ? 'Connection failed' : 'Reconnect needed',+ detail: `Switch can no longer use your ${entry.name} connection. Connect again.`,+ tone: 'problem',+ };+ if (entry.status === 'connected')+ return { kind: 'connected', label: 'Connected', detail: null, tone: 'good' };+ return { kind: 'connect', label: 'Not connected', detail: null, tone: 'muted' };+}++/** The badge variant for a card's tone. */+export const TONE_BADGE = {+ problem: 'destructive',+ good: 'outline',+ muted: 'secondary',+} as const satisfies Record<ConnectorCardState['tone'], string>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-copy.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-copy.tsnew file mode 100644index 000000000..47c03a124--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-copy.ts@@ -0,0 +1,73 @@+import type {+ ConnectionCatalogEntry,+ WorkspaceService,+} from '@shared/core/switch-servers/connection-catalog';++/** The most agents the disconnect dialog names before counting the rest. */+const NAMED_AGENTS = 4;++/**+ * What disconnecting says before it happens: how many of the person's agents+ * lose the service and which (the first four, then how many more), or, where+ * that cannot be known, that every one does; and, for a key, that Switch can+ * only forget it, not revoke it.+ */+export function disconnectCopy(+ entry: Pick<ConnectionCatalogEntry, 'name' | 'auth_type'>,+ grantedAgents: string[] | null+): { title: string; lines: string[] } {+ const { name } = entry;+ const lines = [+ grantedAgents === null+ ? `Disconnecting removes every agent's access to ${name}.`+ : grantedAgents.length === 0+ ? `None of your agents use ${name}.`+ : grantedAgents.length === 1+ ? `${grantedAgents[0]} loses ${name}.`+ : `${grantedAgents.length} agents lose ${name}: ${namedAgents(grantedAgents)}. Disconnecting removes their access.`,+ ];+ if (entry.auth_type === 'api_key') {+ lines.push('Switch removes the key it keeps.');+ lines.push(`Switch can't revoke this key at ${name}; delete it there.`);+ } else {+ lines.push(`Switch removes the sign-in it keeps for ${name}.`);+ }+ return { title: `Disconnect ${name}?`, lines };+}++function namedAgents(names: string[]): string {+ const named = names.slice(0, NAMED_AGENTS);+ const rest = names.length - named.length;+ const last = rest > 0 ? `${rest} more` : named.pop()!;+ return `${named.join(', ')} and ${last}`;+}++/**+ * What an admin is asked before switching a service off for the workspace, or+ * null when nobody is connected and no agent uses it: switching it off then+ * changes nothing anyone has, and is done without asking.+ */+export function switchOffConfirmation(+ service: Pick<WorkspaceService, 'name' | 'connected_members' | 'granted_agents'>+): { title: string; description: string } | null {+ const members = service.connected_members;+ const agents = service.granted_agents;+ if (members === 0 && agents === 0) return null;+ const connected = `${members} ${members === 1 ? 'member is' : 'members are'} connected`;+ const using = `${agents} ${agents === 1 ? 'agent uses' : 'agents use'} it`;+ return {+ title: `Switch ${service.name} off for this workspace?`,+ description: `${connected} and ${using}. Their sessions lose it within a minute.`,+ };+}++/** Who last changed a workspace switch, and when; a switch nobody touched is on by default. */+export function workspaceSwitchNote(+ service: Pick<WorkspaceService, 'enabled' | 'updated_by_name' | 'updated_at'>,+ formatTime: (iso: string) => string+): string {+ if (service.updated_at === null) return 'On by default.';+ const state = service.enabled ? 'on' : 'off';+ const who = service.updated_by_name ?? 'a deleted account';+ return `Switched ${state} by ${who}, ${formatTime(service.updated_at)}.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-profile.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-profile.tsxnew file mode 100644index 000000000..2939c5474--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-profile.tsx@@ -0,0 +1,193 @@+import { ArrowLeft } from 'lucide-react';+import { useState } from 'react';+import { ConnectionIcon } from '@renderer/features/switch-servers/connection-icon';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { ConnectorAgentsSection } from './connector-agents-section';+import { TONE_BADGE, connectorCardState } from './connector-card-state';+import {+ connectedAsLine,+ isYours,+ profileConnectAction,+ signInLabel,+ tokenLifetimeLabel,+ workspaceOffNotice,+} from './connectors-catalog';+import { useReloadConnectors } from './connectors-queries';+import { GitHubAccessSection } from './github-access-section';+import { offersAddAgent } from './grant-agents';+import { useConnectService } from './use-connect-service';++const ACTION_LABEL = {+ connect: 'Connect to Switch',+ reconnect: 'Reconnect',+ replace: 'Replace key',+} as const;++/**+ * One connector, in place of the catalog: who the person is connected as and+ * what they allowed, which of their agents use it, and the way to connect,+ * reconnect or disconnect. When the workspace has it off, a member is told+ * who can switch it on and an admin is offered the switch. Opened right after+ * connecting, the Add agent search under the agents starts open.+ */+export function ConnectorProfile({+ serverId,+ workspaceId,+ connection,+ administers,+ justConnected,+ onBack,+}: {+ serverId: string;+ workspaceId: string;+ connection: ConnectionCatalogEntry;+ administers: boolean;+ /** Set when the profile opens because the service was just connected, with the warning Switch gave. */+ justConnected: { warning: string | null } | null;+ onBack: () => void;+}) {+ const reload = useReloadConnectors(workspaceId);+ const connect = useConnectService(serverId, workspaceId);+ const showDisconnect = useShowModal('disconnectServiceModal');+ const [enabling, setEnabling] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [adding, setAdding] = useState(justConnected !== null);+ const [notice, setNotice] = useState(justConnected?.warning ?? null);+ const afterConnected = (warning: string | null) => {+ if (!offersAddAgent(connection)) return;+ setNotice(warning);+ setAdding(true);+ };++ const state = connectorCardState(connection);+ const offNotice = workspaceOffNotice(connection, administers);+ // Whatever the server or workspace says, a connection the person has can be disconnected.+ const hasConnection = isYours(connection);+ const connectedAs = connectedAsLine(connection);+ const action = profileConnectAction(connection);++ const enable = async () => {+ setEnabling(true);+ setError(null);+ try {+ await rpc.workspaces.setWorkspaceService({+ workspaceId,+ service: connection.slug,+ enabled: true,+ });+ await reload();+ if (!hasConnection && connection.connectable)+ connect({ ...connection, workspace_enabled: true }, 'connect', afterConnected);+ } catch (cause) {+ setError(failureText(cause, `Could not switch ${connection.name} on for the workspace.`));+ } finally {+ setEnabling(false);+ }+ };++ return (+ <div className="flex flex-col gap-8">+ <div className="flex flex-col gap-4">+ <Button variant="ghost" size="sm" className="-ml-2 w-fit" onClick={onBack}>+ <ArrowLeft className="size-4" />+ Connectors+ </Button>+ <header className="flex items-start gap-4">+ <ConnectionIcon slug={connection.slug} name={connection.name} size="xl" />+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex items-center gap-2">+ <h1 className="truncate text-3xl font-semibold tracking-tight text-foreground">+ {connection.name}+ </h1>+ {state.kind !== 'connect' && state.kind !== 'connected' && (+ <Badge variant={TONE_BADGE[state.tone]}>{state.label}</Badge>+ )}+ </div>+ <p className="text-sm text-foreground-muted">{connection.description}</p>+ {connectedAs && <p className="text-sm">{connectedAs}</p>}+ {state.detail && <p className="text-sm text-foreground-muted">{state.detail}</p>}+ </div>+ <div className="flex shrink-0 gap-2">+ {action && (+ <Button+ variant={action === 'replace' ? 'outline' : 'default'}+ disabled={!connection.connectable}+ onClick={() =>+ connect(connection, action === 'replace' ? 'replace' : 'connect', afterConnected)+ }+ >+ {ACTION_LABEL[action]}+ </Button>+ )}+ {hasConnection && (+ <Button variant="outline" onClick={() => showDisconnect({ workspaceId, connection })}>+ Disconnect+ </Button>+ )}+ </div>+ </header>+ </div>++ {offNotice && (+ <div className="flex items-center gap-3 rounded-lg border border-border p-3">+ <p className="flex-1 text-sm">{offNotice.text}</p>+ {offNotice.canEnable && (+ <Button size="sm" disabled={enabling} onClick={() => void enable()}>+ {enabling && <Spinner />}+ {hasConnection || !connection.connectable+ ? 'Enable for the workspace'+ : 'Enable for the workspace and connect'}+ </Button>+ )}+ </div>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}++ <section className="flex flex-col gap-4">+ <h2 className="text-sm font-semibold text-foreground">General</h2>+ <div className="grid grid-cols-3 gap-6">+ <Fact label="Category">+ <span className="inline-flex items-center rounded-md border border-border px-2 py-0.5 text-sm">+ {connection.category}+ </span>+ </Fact>+ <Fact label="Sign-in">{signInLabel(connection)}</Fact>+ <Fact label="Agent access lasts">{tokenLifetimeLabel(connection)}</Fact>+ </div>+ </section>++ {connection.slug === 'github' && state.kind === 'connected' && (+ <GitHubAccessSection serverId={serverId} workspaceId={workspaceId} />+ )}++ <ConnectorAgentsSection+ serverId={serverId}+ workspaceId={workspaceId}+ connection={connection}+ connected={state.kind === 'connected'}+ adding={adding}+ onAddingChange={setAdding}+ notice={notice}+ />+ </div>+ );+}++function Fact({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div>+ <h3 className="text-xs font-medium tracking-wide text-foreground-muted uppercase">{label}</h3>+ <div className="mt-1.5 text-sm text-foreground">{children}</div>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-tile.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-tile.tsxnew file mode 100644index 000000000..b4ac90b2e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connector-tile.tsx@@ -0,0 +1,64 @@+import type { ReactNode } from 'react';+import { ConnectionIcon } from '@renderer/features/switch-servers/connection-icon';+import { cn } from '@renderer/utils/utils';++/**+ * One connector as a tile: its icon, its name and the lines under it, with+ * its one control at the top right. Every list of connectors draws its tiles+ * with this, so Discover and the Admin page read as the same thing.+ *+ * A tile that opens something is a button over its whole area, the control+ * keeping its own target above it. One that opens nothing is plain content,+ * so it never invites a click it would ignore. The lines are phrasing+ * content (spans), since they may sit inside that button.+ */+export function ConnectorTile({+ slug,+ name,+ inert,+ onOpen,+ control,+ children,+}: {+ slug: string;+ name: string;+ /** Shown faded and opening nothing: a service not built yet. */+ inert: boolean;+ /** What the whole tile opens; null for a tile whose control is all it offers. */+ onOpen: (() => void) | null;+ control: ReactNode;+ children: ReactNode;+}) {+ const lines = (+ <>+ <span className="block truncate text-sm font-medium text-foreground">{name}</span>+ {children}+ </>+ );+ return (+ <div+ className={cn(+ 'relative flex items-start gap-3 rounded-lg border border-border p-4 transition-colors',+ inert ? 'opacity-60' : onOpen && 'hover:bg-background-tertiary-2'+ )}+ >+ <ConnectionIcon slug={slug} name={name} size="lg" />+ {onOpen ? (+ <button+ type="button"+ disabled={inert}+ onClick={onOpen}+ className="focus-visible:ring-ring min-w-0 flex-1 rounded-sm text-left focus-visible:ring-2 focus-visible:outline-none enabled:cursor-pointer disabled:cursor-not-allowed"+ >+ {/* Stretched over the tile, so the whole tile opens it while the+ control beside it keeps its own target. */}+ <span aria-hidden className="absolute inset-0 rounded-lg" />+ {lines}+ </button>+ ) : (+ <div className="min-w-0 flex-1">{lines}</div>+ )}+ {control && <div className="relative z-10 flex shrink-0 items-center gap-2">{control}</div>}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-catalog.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-catalog.tsnew file mode 100644index 000000000..e14f90dc1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-catalog.ts@@ -0,0 +1,148 @@+import { filterConnections } from '@renderer/features/switch-servers/connections-filter';+import {+ FLAGS_NOT_READ_YET,+ type ServerFeatureFlags,+} from '@shared/core/feature-flags/feature-flags';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import type { ConnectorCardState } from './connector-card-state';++export type ConnectorsTab = 'yours' | 'discover';++/** Whether a service belongs on Yours: the person has a connection to it, working or not. */+export function isYours(entry: ConnectionCatalogEntry): boolean {+ return entry.status !== 'not_connected' && entry.status !== 'coming_soon';+}++/**+ * The catalog cards a tab lists, narrowed by the search. Yours holds what the+ * person has connected; Discover holds the whole catalog, connected services+ * included, so a search there finds anything.+ */+export function connectorsInTab(+ entries: ConnectionCatalogEntry[],+ tab: ConnectorsTab,+ query: string+): ConnectionCatalogEntry[] {+ const needle = query.trim().toLocaleLowerCase();+ const inTab = entries.filter(+ (entry) =>+ (tab === 'discover' || isYours(entry)) &&+ (!needle ||+ [entry.name, entry.category, entry.description].some((text) =>+ text.toLocaleLowerCase().includes(needle)+ ))+ );+ return filterConnections(inTab, '');+}++/**+ * The card's own control, beside the part that opens the profile: a way to+ * connect where the profile would offer Connect, and a mark (not a button)+ * only when the card's one state is connected. A connection the server or+ * the workspace has made unusable shows that state instead, and is still+ * there to disconnect on the profile. Disconnecting stays on the profile, so+ * the grid can never remove anyone's access by a stray click.+ */+export function cardQuickAction(+ entry: ConnectionCatalogEntry,+ state: ConnectorCardState+): 'connect' | 'connected' | null {+ if (state.kind === 'connected') return 'connected';+ return profileConnectAction(entry) === 'connect' && entry.connectable ? 'connect' : null;+}++/**+ * Whether the page is there at all. It is behind the server's+ * `service_connections` flag: with it off, the catalog route is not mounted,+ * so the page is absent rather than drawn empty. Until the flags have been+ * read it waits; flags that could never be read count as off.+ */+export function connectorsPageAccess(+ flags: ServerFeatureFlags | null+): 'loading' | 'absent' | 'shown' {+ if (flags === null || (flags.fetchedAt === null && flags.error === FLAGS_NOT_READ_YET))+ return 'loading';+ return flags.flags.service_connections ? 'shown' : 'absent';+}++/**+ * What the profile says and offers when the workspace has the service off: a+ * member is told who can switch it on; an admin is offered to switch it on.+ * Null when it is on, or the server has no workspace switch.+ */+export function workspaceOffNotice(+ entry: ConnectionCatalogEntry,+ administers: boolean+): { text: string; canEnable: boolean } | null {+ if (entry.workspace_enabled !== false) return null;+ return administers+ ? { text: `${entry.name} is switched off for this workspace.`, canEnable: true }+ : { text: 'Not enabled in this workspace. Ask a workspace admin.', canEnable: false };+}++/**+ * The profile's way to connect: connect, sign in again, (GitHub) choose+ * repositories, or replace a connected key. None while the workspace has the+ * service off, whose notice says what to do instead. A reason the server+ * gives does not take it away: a service can often be connected where it+ * cannot be granted, and the button is disabled where it cannot.+ */+export function profileConnectAction(+ entry: ConnectionCatalogEntry+): 'connect' | 'reconnect' | 'replace' | null {+ if (entry.status === 'coming_soon' || entry.workspace_enabled === false) return null;+ if (entry.status === 'not_connected') return 'connect';+ if (entry.status === 'needs_reauthorization' || entry.status === 'error') return 'reconnect';+ return entry.auth_type === 'api_key' ? 'replace' : null;+}++/**+ * The profile header's line about the connection; null when there is none.+ * A key's line names no access level: Switch can't read what a key allows.+ */+export function connectedAsLine(entry: ConnectionCatalogEntry): string | null {+ if (entry.status === 'not_connected' || entry.status === 'coming_soon') return null;+ const access =+ entry.auth_type === 'api_key'+ ? null+ : entry.consent === 'write'+ ? 'Read and write'+ : entry.consent === 'read'+ ? 'Read'+ : null;+ const who =+ entry.auth_type === 'api_key'+ ? entry.external_identity+ ? `Connected with ${entry.external_identity}`+ : 'Connected with your key'+ : entry.external_identity+ ? `Connected as ${entry.external_identity}`+ : 'Connected';+ return access ? `${who} · ${access}` : who;+}++/** What agents can do with a key, for the profile's side column; null for a sign-in. */+export function keyAccessText(entry: ConnectionCatalogEntry): string | null {+ if (entry.auth_type !== 'api_key') return null;+ return `Whatever the key allows at ${entry.name}. Switch can't read a key's scopes.`;+}++/** How the service is connected, for the profile's side column. */+export function signInLabel(entry: ConnectionCatalogEntry): string {+ if (entry.slug === 'github') return 'GitHub App';+ return entry.auth_type === 'api_key' ? 'Key' : `Sign in at ${entry.name}`;+}++/** How long what an agent is handed lasts, for the profile's side column. */+export function tokenLifetimeLabel(entry: ConnectionCatalogEntry): string {+ if (entry.auth_type === 'api_key') return "The key itself, which doesn't expire";+ const seconds = entry.token_lifetime;+ if (seconds === null) return 'Not stated';+ if (seconds < 3600) return plural(Math.round(seconds / 60), 'minute');+ if (seconds < 86_400) return plural(Math.round(seconds / 3600), 'hour');+ return plural(Math.round(seconds / 86_400), 'day');+}++function plural(count: number, unit: string): string {+ return `${count} ${unit}${count === 1 ? '' : 's'}`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-queries.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-queries.tsnew file mode 100644index 000000000..7c4e6df74--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-queries.ts@@ -0,0 +1,100 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback, useEffect, useState } from 'react';+import { events, rpc } from '@renderer/lib/ipc';+import type { ServerFeatureFlags } from '@shared/core/feature-flags/feature-flags';+import { featureFlagsChangedChannel } from '@shared/events/featureFlagEvents';++/** The workspace's catalog, shared with an agent's Connections tab and Service access row. */+export const catalogKey = (workspaceId: string) => ['workspace-service-connections', workspaceId];+const agentsKey = (workspaceId: string, service: string) => [+ 'connection-agents',+ workspaceId,+ service,+];+const workspaceServicesKey = (workspaceId: string) => ['workspace-services', workspaceId];+/** The person's GitHub connection and what it reaches, shared with the agent settings' Service access row. */+export const githubKey = (workspaceId: string) => ['workspace-github', workspaceId];++export function useConnectorCatalog(workspaceId: string) {+ return useQuery({+ queryKey: catalogKey(workspaceId),+ queryFn: () => rpc.workspaces.getServiceConnections(workspaceId),+ retry: false,+ });+}++export function useConnectionAgents(workspaceId: string, service: string) {+ return useQuery({+ queryKey: agentsKey(workspaceId, service),+ queryFn: () => rpc.workspaces.getConnectionAgents({ workspaceId, service }),+ retry: false,+ });+}++/**+ * The person's GitHub connection: who they are and the repositories each+ * installation reaches. Re-read as the window regains focus, since those are+ * chosen on GitHub, in the browser.+ */+export function useGitHubConnection(workspaceId: string, enabled: boolean) {+ return useQuery({+ queryKey: githubKey(workspaceId),+ queryFn: () => rpc.workspaces.getGitHubConnection(workspaceId),+ enabled,+ retry: false,+ refetchOnWindowFocus: true,+ });+}++/** The workspace's switches, for its admins; null data means the server has none. */+export function useWorkspaceServices(workspaceId: string) {+ return useQuery({+ queryKey: workspaceServicesKey(workspaceId),+ queryFn: () => rpc.workspaces.getWorkspaceServices(workspaceId),+ retry: false,+ });+}++/**+ * Re-read everything a connection, grant or switch change can move: the+ * catalog, who uses each service, the admin's switches, and the agent pages+ * that read the same connections and grants.+ */+export function useReloadConnectors(workspaceId: string): () => Promise<void> {+ const queryClient = useQueryClient();+ return useCallback(async () => {+ await Promise.all(+ [+ catalogKey(workspaceId),+ ['connection-agents', workspaceId],+ workspaceServicesKey(workspaceId),+ githubKey(workspaceId),+ ['agent-service-grants', workspaceId],+ ].map((queryKey) => queryClient.invalidateQueries({ queryKey }))+ );+ }, [queryClient, workspaceId]);+}++/**+ * The server's feature flags as Console last read them, kept current; null+ * until the first answer. Unlike `useFeatureFlags`, which reads every flag as+ * off until then, this lets a page wait rather than act on flags not yet read.+ */+export function useServerFeatureFlags(serverId: string): ServerFeatureFlags | null {+ const [flags, setFlags] = useState<ServerFeatureFlags | null>(null);+ useEffect(() => {+ setFlags(null);+ let current = true;+ const off = events.on(featureFlagsChangedChannel, (state) => {+ if (state.serverId === serverId) setFlags(state);+ });+ void rpc.featureFlags.get(serverId).then((res) => {+ if (current && res?.success) setFlags(res.data);+ });+ return () => {+ current = false;+ off();+ };+ }, [serverId]);+ return flags;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-view.tsxnew file mode 100644index 000000000..6ce466de0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/connectors-view.tsx@@ -0,0 +1,328 @@+import { ArrowRight, Check, Plug, Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { ServerPage } from '@renderer/features/switch-servers/server-page';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { SearchInput } from '@renderer/lib/ui/search-input';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { TONE_BADGE, connectorCardState } from './connector-card-state';+import { ConnectorProfile } from './connector-profile';+import { ConnectorTile } from './connector-tile';+import {+ type ConnectorsTab,+ cardQuickAction,+ connectorsInTab,+ connectorsPageAccess,+} from './connectors-catalog';+import { useConnectorCatalog, useServerFeatureFlags } from './connectors-queries';+import { offersAddAgent } from './grant-agents';+import { useConnectService } from './use-connect-service';++function useServerId(): string {+ return useParams('connectors').params.serverId;+}++const ConnectorsTitlebar = observer(function ConnectorsTitlebar() {+ return <ServerSectionTitlebar serverId={useServerId()} icon={Plug} label="Connectors" />;+});++const DESCRIPTION =+ 'Connect the services your agents work with. An agent uses one only once you turn it on for that agent.';++/**+ * The connector catalog of the workspace in scope on the server. Behind the+ * server's `service_connections` flag: with it off there is no page, and+ * reaching it anyway goes to Your Agents rather than drawing an empty one.+ */+const ConnectorsPanel = observer(function ConnectorsPanel() {+ const serverId = useServerId();+ const { navigate } = useNavigate();+ const access = connectorsPageAccess(useServerFeatureFlags(serverId));+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ useEffect(() => {+ if (access === 'absent') navigate('serverAgents', { serverId });+ }, [access, navigate, serverId]);++ if (access !== 'shown' || workspaceId === null)+ return (+ <ServerPage width={880} title="Connectors" description={DESCRIPTION}>+ <Spinner />+ </ServerPage>+ );+ // Keyed so a workspace switch starts from the catalog, not another workspace's profile.+ return (+ <Connectors+ key={workspaceId}+ serverId={serverId}+ workspaceId={workspaceId}+ administers={administersWorkspaceInScope(serverId)}+ />+ );+});++/**+ * The catalog, or one connector's profile in front of it. Which is open is a+ * view param, so the sidebar's Connectors entry and the history arrows move+ * between the two as they do between a room and Your Rooms. Whether the+ * profile opened because the service was just connected is this page's own+ * business, kept here and dropped as soon as the person moves on.+ */+function Connectors({+ serverId,+ workspaceId,+ administers,+}: {+ serverId: string;+ workspaceId: string;+ administers: boolean;+}) {+ const catalog = useConnectorCatalog(workspaceId);+ const [tab, setTab] = useState<ConnectorsTab>('yours');+ const [query, setQuery] = useState('');+ const { navigate } = useNavigate();+ const open = useParams('connectors').params.connector ?? null;+ const [justConnected, setJustConnected] = useState<{+ slug: string;+ warning: string | null;+ } | null>(null);+ useEffect(() => {+ if (justConnected && justConnected.slug !== open) setJustConnected(null);+ }, [open, justConnected]);+ const openProfile = (slug: string) => navigate('connectors', { serverId, connector: slug });+ const connect = useConnectService(serverId, workspaceId);++ const tabs = [+ { value: 'yours', label: 'Yours' },+ { value: 'discover', label: 'Discover' },+ ] as const satisfies readonly { value: ConnectorsTab; label: string }[];++ const opened = open === null ? null : catalog.data?.find((entry) => entry.slug === open);+ // The profile replaces the whole page, title included: it is a place of its+ // own, reached from the catalog, with the way back at its top. Same column+ // as `ServerPage`, so moving between the two does not shift the content.+ // A failed re-read keeps the last data, so the profile says so rather than+ // showing what may no longer be true as if it were.+ if (opened)+ return (+ <div className="relative z-10 flex min-h-0 flex-1 flex-col bg-background">+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">+ <div className="mx-auto w-full space-y-4 px-10 py-8" style={{ maxWidth: 880 }}>+ {catalog.isError && (+ <CatalogError error={catalog.error} onRetry={() => void catalog.refetch()} />+ )}+ <ConnectorProfile+ key={opened.slug}+ serverId={serverId}+ workspaceId={workspaceId}+ connection={opened}+ administers={administers}+ justConnected={+ justConnected?.slug === opened.slug ? { warning: justConnected.warning } : null+ }+ onBack={() => navigate('connectors', { serverId })}+ />+ </div>+ </div>+ </div>+ );++ return (+ <ServerPage+ width={880}+ title="Connectors"+ description={DESCRIPTION}+ action={+ // Turning a service on or off for everyone is the Admin page's; only+ // the way there is here, for whoever may.+ administers && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => navigate('admin', { serverId, section: 'connectors' })}+ >+ Manage in Admin+ <ArrowRight className="size-3.5" />+ </Button>+ )+ }+ >+ <div className="flex items-center gap-3">+ <SegmentedControl ariaLabel="Connectors" value={tab} onChange={setTab} options={tabs} />+ <SearchInput+ containerClassName="flex-1"+ aria-label="Search connectors"+ placeholder="Search by name, category or description"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ </div>+ {catalog.isError ? (+ <CatalogError error={catalog.error} onRetry={() => void catalog.refetch()} />+ ) : !catalog.data ? (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading connectors…+ </p>+ ) : (+ <ConnectorGrid+ entries={connectorsInTab(catalog.data, tab, query)}+ tab={tab}+ query={query}+ onOpen={openProfile}+ onConnect={(entry) =>+ connect(entry, 'connect', (warning) => {+ if (!offersAddAgent(entry)) return;+ openProfile(entry.slug);+ setJustConnected({ slug: entry.slug, warning });+ })+ }+ />+ )}+ </ServerPage>+ );+}++function CatalogError({ error, onRetry }: { error: unknown; onRetry: () => void }) {+ return (+ <Alert variant="destructive">+ <AlertDescription>{failureText(error, 'Could not load the connectors.')}</AlertDescription>+ <AlertAction>+ <Button size="sm" variant="outline" onClick={onRetry}>+ Retry+ </Button>+ </AlertAction>+ </Alert>+ );+}++function ConnectorGrid({+ entries,+ tab,+ query,+ onOpen,+ onConnect,+}: {+ entries: ConnectionCatalogEntry[];+ tab: ConnectorsTab;+ query: string;+ onOpen: (slug: string) => void;+ onConnect: (entry: ConnectionCatalogEntry) => void;+}) {+ if (entries.length === 0)+ return (+ <p className="text-sm text-foreground-muted">+ {query.trim()+ ? `No connector matches “${query.trim()}”.`+ : tab === 'yours'+ ? 'You have not connected anything yet. Find a service under Discover.'+ : 'This server offers no connectors.'}+ </p>+ );+ return (+ <div+ role="group"+ aria-label="Connectors"+ className="grid grid-cols-[repeat(auto-fill,minmax(320px,1fr))] gap-3"+ >+ {entries.map((entry) => (+ <ConnectorCard+ key={entry.slug}+ entry={entry}+ onOpen={() => onOpen(entry.slug)}+ onConnect={() => onConnect(entry)}+ />+ ))}+ </div>+ );+}++/**+ * One catalog card, showing one state with its reason. The whole card opens+ * the profile; the control at its top right connects in one click, or marks+ * a connection that is there and usable. Disconnecting is only on the profile.+ */+function ConnectorCard({+ entry,+ onOpen,+ onConnect,+}: {+ entry: ConnectionCatalogEntry;+ onOpen: () => void;+ onConnect: () => void;+}) {+ const state = connectorCardState(entry);+ const quick = cardQuickAction(entry, state);+ return (+ <ConnectorTile+ slug={entry.slug}+ name={entry.name}+ inert={state.kind === 'coming_soon'}+ onOpen={onOpen}+ control={+ quick === 'connect' ? (+ <Button+ variant="outline"+ size="icon"+ aria-label={`Connect ${entry.name}`}+ title={`Connect ${entry.name}`}+ onClick={onConnect}+ >+ <Plus className="size-4" />+ </Button>+ ) : quick === 'connected' ? (+ <span+ role="img"+ aria-label={`${entry.name} connected`}+ title="Connected"+ className="flex size-8 items-center justify-center rounded-md border border-border-success bg-background-success text-foreground-success"+ >+ <Check className="size-4" />+ </span>+ ) : null+ }+ >+ <span className="mt-1 line-clamp-2 block text-sm text-foreground-muted">+ {entry.description}+ </span>+ <span className="mt-2 flex flex-wrap items-center gap-2 text-xs text-foreground-muted">+ {entry.category}+ {state.kind !== 'connect' && state.kind !== 'connected' && (+ <Badge variant={TONE_BADGE[state.tone]}>{state.label}</Badge>+ )}+ </span>+ {state.detail && (+ <span className="mt-1 block text-xs text-foreground-muted">{state.detail}</span>+ )}+ </ConnectorTile>+ );+}++export const connectorsView = {+ WrapView: ({+ children,+ }: {+ children: React.ReactNode;+ serverId: string;+ /** The connector whose profile is open in front of the catalog. */+ connector?: string;+ }) => <>{children}</>,+ TitlebarSlot: ConnectorsTitlebar,+ MainPanel: ConnectorsPanel,+ canActivate: (params: unknown): GuardResult => {+ const serverId =+ typeof params === 'object' && params !== null+ ? (params as { serverId?: unknown }).serverId+ : undefined;+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };+ return { ok: true };+ },+} satisfies ViewDefinition<{ serverId: string; connector?: string }>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/disconnect-dialog.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/disconnect-dialog.tsxnew file mode 100644index 000000000..29e513523--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/disconnect-dialog.tsx@@ -0,0 +1,124 @@+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { useCloseGuard } from '@renderer/lib/modal/use-close-guard';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Spinner } from '@renderer/lib/ui/spinner';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { disconnectCopy } from './connector-copy';+import { useConnectionAgents, useReloadConnectors } from './connectors-queries';++/**+ * Disconnecting a service from its profile, in the profile's workspace, after+ * saying which of the person's agents lose it. The page is re-read before the+ * dialog closes, so the profile it uncovers is already current. A warning+ * Switch answers with stays on screen until the person closes the dialog.+ */+export function DisconnectServiceDialog({+ workspaceId,+ connection,+ onSuccess,+ onClose,+}: {+ workspaceId: string;+ connection: ConnectionCatalogEntry;+} & BaseModalProps) {+ const agents = useConnectionAgents(workspaceId, connection.slug);+ const reload = useReloadConnectors(workspaceId);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [warning, setWarning] = useState<string | null>(null);+ const [done, setDone] = useState(false);+ useCloseGuard(busy);+ // Null where the server cannot list them, or they could not be read: every agent then.+ const granted = agents.data?.filter((agent) => agent.granted).map((agent) => agent.name) ?? null;+ const copy = disconnectCopy(connection, granted);++ const disconnect = async () => {+ setBusy(true);+ setError(null);+ try {+ const result =+ connection.slug === 'github'+ ? await rpc.workspaces.disconnectGitHub(workspaceId)+ : await rpc.workspaces.disconnectService({ workspaceId, service: connection.slug });+ await reload();+ if (result.warning) {+ setWarning(result.warning);+ setDone(true);+ } else onSuccess(undefined);+ } catch (cause) {+ setError(failureText(cause, `Could not disconnect ${connection.name}.`));+ } finally {+ setBusy(false);+ }+ };++ return (+ <>+ <DialogHeader showCloseButton={!busy}>+ <DialogTitle>{done ? `${connection.name} disconnected` : copy.title}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ {done ? (+ <p role="status" className="rounded-md border p-3 text-sm text-foreground-muted">+ {warning}+ </p>+ ) : (+ <>+ {agents.isPending && (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Checking which of your agents use {connection.name}…+ </p>+ )}+ {agents.isError && (+ <p role="alert" className="text-sm text-destructive">+ {failureText(+ agents.error,+ `Could not check which of your agents use ${connection.name}.`+ )}+ </p>+ )}+ {!agents.isPending &&+ copy.lines.map((line) => (+ <p key={line} className="text-sm">+ {line}+ </p>+ ))}+ </>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </DialogContentArea>+ <DialogFooter>+ {done ? (+ <Button onClick={() => onSuccess(undefined)}>Done</Button>+ ) : (+ <>+ <Button variant="outline" disabled={busy} onClick={onClose}>+ Cancel+ </Button>+ <Button+ variant="destructive"+ disabled={busy || agents.isPending}+ onClick={() => void disconnect()}+ >+ {busy && <Spinner />}+ Disconnect+ </Button>+ </>+ )}+ </DialogFooter>+ </>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access-section.tsxnew file mode 100644index 000000000..f5f9a1e58--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access-section.tsx@@ -0,0 +1,161 @@+import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-react';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@renderer/lib/ui/collapsible';+import { Spinner } from '@renderer/lib/ui/spinner';+import { useGitHubConnection } from './connectors-queries';+import {+ NO_REPOSITORIES_NOTE,+ SSO_HIDDEN_NOTE,+ repositoriesActionLabel,+ repositoriesSummary,+} from './github-access';+import { type GitHubInstallation, connectedGitHub, matchingRepositories } from './github-grant';+import { RepositorySearchInput } from './repository-search-input';++/** Above this many, an opened account's directory gets a search above it. */+const SEARCH_FROM = 8;+/** How many names the directory shows before asking for a narrower search. */+const DIRECTORY_ROWS = 100;++/**+ * The repositories the person's GitHub connection reaches, on the connector's+ * page: one card per account the App is installed on, stacked, each opening+ * to a directory of names searched rather than scrolled once it is long.+ * Chosen on GitHub, so the action goes there, and re-read whenever the window+ * regains focus.+ */+export function GitHubAccessSection({+ serverId,+ workspaceId,+}: {+ serverId: string;+ workspaceId: string;+}) {+ const github = useGitHubConnection(workspaceId, true);+ const reach = connectedGitHub(github.data);+ return (+ <section className="flex flex-col gap-3" aria-label="Repositories">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-baseline gap-2">+ <h2 className="text-sm font-semibold text-foreground">Repositories</h2>+ {reach && (+ <span className="text-xs text-foreground-muted">{repositoriesSummary(reach)}</span>+ )}+ </div>+ {reach && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => void rpc.switchServers.openGitHubInstallation(serverId)}+ >+ {repositoriesActionLabel(reach)} <ExternalLink className="size-3.5" />+ </Button>+ )}+ </div>+ {github.isPending && (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading repository access…+ </p>+ )}+ {github.isError && (+ <p role="alert" className="text-sm text-destructive">+ {failureText(github.error, 'Could not load repository access.')}+ </p>+ )}+ {reach &&+ (reach.installations.length === 0 ? (+ <p className="text-sm text-foreground-muted">{NO_REPOSITORIES_NOTE}</p>+ ) : (+ <div role="list" aria-label="Accounts" className="flex flex-col gap-2.5">+ {reach.installations.map((installation) => (+ <InstallationCard key={installation.id} installation={installation} />+ ))}+ </div>+ ))}+ {reach && (reach.sso_hidden_organizations?.length ?? 0) > 0 && (+ <p role="alert" className="text-sm text-foreground-warning">+ {SSO_HIDDEN_NOTE}+ </p>+ )}+ </section>+ );+}++/** One account the App is installed on: its name and count, opening to its directory. */+function InstallationCard({ installation }: { installation: GitHubInstallation }) {+ const [open, setOpen] = useState(false);+ const count = installation.repositories.length;+ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <div+ role="listitem"+ className="rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3"+ >+ <CollapsibleTrigger+ className="flex w-full cursor-pointer items-center gap-2 text-left"+ aria-label={`${open ? 'Hide' : 'Show'} the repositories under ${installation.account}`}+ >+ {open ? (+ <ChevronDown className="size-4 shrink-0 text-foreground-muted" />+ ) : (+ <ChevronRight className="size-4 shrink-0 text-foreground-muted" />+ )}+ <span className="flex min-w-0 flex-1 items-baseline gap-2">+ <span className="truncate text-sm font-medium text-foreground">+ {installation.account}+ </span>+ <span className="text-xs text-foreground-muted">+ {count} {count === 1 ? 'repository' : 'repositories'}+ </span>+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-3">+ <RepositoryDirectory installation={installation} />+ </CollapsibleContent>+ </div>+ </Collapsible>+ );+}++/**+ * An account's repositories laid out as a directory: names in columns, in a+ * fixed-height area, with a search above once there are many.+ */+function RepositoryDirectory({ installation }: { installation: GitHubInstallation }) {+ const [query, setQuery] = useState('');+ const shown = matchingRepositories(installation, query, []);+ return (+ <div className="flex flex-col gap-2">+ {installation.repositories.length > SEARCH_FROM && (+ <RepositorySearchInput+ value={query}+ onChange={setQuery}+ label={`Search the repositories under ${installation.account}`}+ placeholder="Search repositories…"+ />+ )}+ {shown.length === 0 ? (+ <p className="px-1 text-xs text-foreground-muted">No repository matches “{query}”.</p>+ ) : (+ <ul+ aria-label={`Repositories under ${installation.account}`}+ className="grid max-h-64 grid-cols-2 gap-x-6 gap-y-0.5 overflow-auto text-sm xl:grid-cols-3"+ >+ {shown.slice(0, DIRECTORY_ROWS).map((repository) => (+ <li key={repository.id} className="truncate py-0.5" title={repository.name}>+ {repository.name}+ </li>+ ))}+ {shown.length > DIRECTORY_ROWS && (+ <li className="col-span-full py-0.5 text-xs text-foreground-muted">+ {shown.length - DIRECTORY_ROWS} more; search to narrow the list.+ </li>+ )}+ </ul>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access.tsnew file mode 100644index 000000000..86593a2d9--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-access.ts@@ -0,0 +1,21 @@+import type { ConnectedGitHub } from './github-grant';++export const SSO_HIDDEN_NOTE =+ 'An organization’s single sign-on hides its installation of the app from this GitHub connection. Disconnect and connect GitHub again, and authorize the organization when GitHub asks.';+export const NO_REPOSITORIES_NOTE =+ 'Choose repositories on GitHub to finish setup. Your organization may require an owner’s approval.';++/** The count beside the heading: how many repositories, across how many accounts. */+export function repositoriesSummary(github: ConnectedGitHub): string {+ const total = github.installations.reduce((n, i) => n + i.repositories.length, 0);+ const accounts = github.installations.length;+ const repositories = `${total} ${total === 1 ? 'repository' : 'repositories'}`;+ return accounts > 1 ? `${repositories} across ${accounts} accounts` : repositories;+}++/** The section's action: choosing the first time, changing after. */+export function repositoriesActionLabel(github: ConnectedGitHub): string {+ return github.installations.some((i) => i.repositories.length > 0)+ ? 'Change repositories'+ : 'Choose repositories';+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsxnew file mode 100644index 000000000..dfd1f6007--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-add-agent-choice.tsx@@ -0,0 +1,57 @@+import { Button } from '@renderer/lib/ui/button';+import {+ type ConnectedGitHub,+ type GitHubGrantChoice,+ NOTHING_CHOSEN_NOTE,+ githubChoiceSummary,+} from './github-grant';+import { GitHubGrantPicker } from './github-grant-picker';++/**+ * What every agent added from GitHub's page gets, above the agent search: a+ * warning while nothing is chosen, the choice in a sentence once it is, and+ * a button that opens the picker in place and closes it again.+ */+export function GitHubAddAgentChoice({+ github,+ choice,+ onChange,+ choosing,+ onChoosingChange,+}: {+ github: ConnectedGitHub;+ choice: GitHubGrantChoice;+ onChange: (choice: GitHubGrantChoice) => void;+ choosing: boolean;+ onChoosingChange: (choosing: boolean) => void;+}) {+ const summary = githubChoiceSummary(github, choice);+ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-3">+ {summary === null ? (+ <p role="status" className="flex-1 text-sm text-foreground-warning">+ {NOTHING_CHOSEN_NOTE}+ </p>+ ) : (+ <p className="flex-1 text-sm text-foreground-muted">+ Agents you add get {summary}. Each can be changed later on its Connections tab.+ </p>+ )}+ <Button+ variant="outline"+ size="sm"+ aria-expanded={choosing}+ onClick={() => onChoosingChange(!choosing)}+ >+ {choosing ? 'Done' : summary === null ? 'Choose repositories' : 'Change'}+ </Button>+ </div>+ {choosing && (+ <div className="rounded-lg border border-border p-3">+ <GitHubGrantPicker github={github} value={choice} onChange={onChange} />+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant-picker.tsxnew file mode 100644index 000000000..6b98d80d0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant-picker.tsx@@ -0,0 +1,173 @@+import { X } from 'lucide-react';+import { useState } from 'react';+import { Button } from '@renderer/lib/ui/button';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import {+ type ConnectedGitHub,+ GITHUB_ACCESS_OPTIONS,+ type GitHubGrantChoice,+ chosenInstallation,+ chosenRepositories,+ matchingRepositories,+ withEveryRepository,+ withInstallation,+ withRepository,+ withoutRepository,+} from './github-grant';+import { RepositorySearchInput } from './repository-search-input';++/** How many matches the Add repository search lists before asking for more letters. */+const SEARCH_ROWS = 8;++/** One chosen repository, removable. Sized to read beside the page's text, not as a tag. */+export function RepositoryChip({ name, onRemove }: { name: string; onRemove: () => void }) {+ return (+ <li className="inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-[var(--surface-2)] py-1 pr-1 pl-2.5 text-sm text-foreground">+ <span className="truncate">{name}</span>+ <button+ type="button"+ aria-label={`Remove ${name}`}+ className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-foreground-muted hover:bg-[var(--fill-2)] hover:text-foreground"+ onClick={onRemove}+ >+ <X className="size-3.5" />+ </button>+ </li>+ );+}++/**+ * Chooses what an agent's GitHub access names: the account only where the+ * App is on several, the repositories as chips with a search to add one and+ * Add all for every one, and whether it may push.+ */+export function GitHubGrantPicker({+ github,+ value,+ onChange,+}: {+ github: ConnectedGitHub;+ value: GitHubGrantChoice;+ onChange: (choice: GitHubGrantChoice) => void;+}) {+ const [query, setQuery] = useState('');+ const installation = chosenInstallation(github, value);+ const chosen = chosenRepositories(github, value);+ const matches =+ installation && query.trim() !== ''+ ? matchingRepositories(installation, query, value.repositoryIds)+ : [];+ const allChosen =+ installation !== undefined && value.repositoryIds.length >= installation.repositories.length;++ return (+ <div className="flex flex-col gap-3">+ {github.installations.length > 1 && (+ <Select+ value={value.installationId === null ? null : String(value.installationId)}+ onValueChange={(next) => onChange(withInstallation(value, next ? Number(next) : null))}+ >+ <SelectTrigger aria-label="GitHub account" className="w-full">+ <SelectValue placeholder="Choose a GitHub account">{installation?.account}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {github.installations.map((candidate) => (+ <SelectItem key={candidate.id} value={String(candidate.id)}>+ {candidate.account}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ {installation && (+ <>+ <div className="flex items-center gap-2">+ <div className="flex-1">+ <RepositorySearchInput+ value={query}+ onChange={setQuery}+ label="Add repository"+ placeholder="Add repository…"+ />+ </div>+ <Button+ variant="outline"+ size="sm"+ disabled={allChosen}+ onClick={() => onChange(withEveryRepository(github, value))}+ >+ Add all+ </Button>+ </div>+ {query.trim() !== '' && matches.length === 0 && (+ <p className="px-1 text-xs text-foreground-muted">+ No repository it reaches matches “{query}”.+ </p>+ )}+ {matches.length > 0 && (+ <div+ role="listbox"+ aria-label="Matching repositories"+ className="divide-y divide-border overflow-hidden rounded-[10px] border border-border"+ >+ {matches.slice(0, SEARCH_ROWS).map((repository) => (+ <button+ key={repository.id}+ type="button"+ role="option"+ aria-selected={false}+ onClick={() => {+ onChange(withRepository(value, repository.id));+ setQuery('');+ }}+ className="flex w-full cursor-pointer items-center bg-background px-3 py-2 text-left text-sm transition-colors hover:bg-[var(--fill)]"+ >+ {repository.name}+ </button>+ ))}+ {matches.length > SEARCH_ROWS && (+ <p className="px-3 py-2 text-xs text-foreground-muted">+ {matches.length - SEARCH_ROWS} more match; type more of the name.+ </p>+ )}+ </div>+ )}+ <div className="flex flex-col gap-1.5">+ <span className="text-xs text-foreground-muted">+ {chosen.length === 0+ ? 'No repository chosen.'+ : `${chosen.length} of ${installation.repositories.length} chosen`}+ </span>+ {chosen.length > 0 && (+ <ul+ aria-label="Chosen repositories"+ className="flex max-h-40 flex-wrap gap-1.5 overflow-auto"+ >+ {chosen.map((repository) => (+ <RepositoryChip+ key={repository.id}+ name={repository.name}+ onRemove={() => onChange(withoutRepository(value, repository.id))}+ />+ ))}+ </ul>+ )}+ </div>+ </>+ )}+ <SegmentedControl+ ariaLabel="Access"+ value={value.access}+ onChange={(access) => onChange({ ...value, access })}+ options={GITHUB_ACCESS_OPTIONS}+ />+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant.tsnew file mode 100644index 000000000..139205d11--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/github-grant.ts@@ -0,0 +1,127 @@+import type { GitHubConnection } from '@shared/core/switch-servers/github-connection';++/**+ * What an agent's GitHub access names: one installation of the App, some of+ * its repositories, and whether the agent may push. Pure: the picker, the+ * Add agent panel and the agent's own form all build on this.+ */++export type GitHubAccess = 'read' | 'write';++export const GITHUB_ACCESS_OPTIONS = [+ { value: 'read', label: 'Read' },+ { value: 'write', label: 'Read and push' },+] as const;++export type ConnectedGitHub = Extract<GitHubConnection, { status: 'connected' }>;+export type GitHubInstallation = ConnectedGitHub['installations'][number];+export type GitHubRepository = GitHubInstallation['repositories'][number];++/** The connection where it is one, so its installations can be read. */+export function connectedGitHub(data: GitHubConnection | undefined): ConnectedGitHub | null {+ return data !== undefined && data.status === 'connected' ? data : null;+}++export interface GitHubGrantChoice {+ installationId: number | null;+ repositoryIds: number[];+ access: GitHubAccess;+}++/** Said while nothing is chosen: there is nothing yet to add an agent to. */+export const NOTHING_CHOSEN_NOTE =+ 'No repositories chosen yet. Choose some, then add the agents that should use them.';++/** The choice to start from: the first installation, no repositories, read only. */+export function emptyGitHubGrant(github: GitHubConnection | undefined): GitHubGrantChoice {+ const installation = github?.status === 'connected' ? github.installations[0] : undefined;+ return { installationId: installation?.id ?? null, repositoryIds: [], access: 'read' };+}++export function chosenInstallation(+ github: ConnectedGitHub,+ choice: GitHubGrantChoice+): GitHubInstallation | undefined {+ return github.installations.find((candidate) => candidate.id === choice.installationId);+}++/** The repositories the choice names, in the order chosen, by what the connection knows of them. */+export function chosenRepositories(+ github: ConnectedGitHub,+ choice: GitHubGrantChoice+): { id: number; name: string }[] {+ const installation = chosenInstallation(github, choice);+ return choice.repositoryIds.map((id) => ({+ id,+ name: installation?.repositories.find((r) => r.id === id)?.name ?? `repository ${id}`,+ }));+}++/** The resources a grant with this choice sends; null until it names a repository. */+export function githubGrantResources(+ choice: GitHubGrantChoice+): { installation_id: number; repository_ids: number[] } | null {+ if (choice.installationId === null || choice.repositoryIds.length === 0) return null;+ return { installation_id: choice.installationId, repository_ids: choice.repositoryIds };+}++/**+ * The choice as what an agent gets: "read access to 3 repositories", "read+ * and push access to 1 repository under example-org". The account is named+ * only where there is more than one to tell apart. Null while nothing is+ * chosen.+ */+export function githubChoiceSummary(+ github: ConnectedGitHub,+ choice: GitHubGrantChoice+): string | null {+ const count = choice.repositoryIds.length;+ if (count === 0) return null;+ const access = choice.access === 'write' ? 'read and push access to' : 'read access to';+ const installation = chosenInstallation(github, choice);+ const where =+ github.installations.length > 1 && installation ? ` under ${installation.account}` : '';+ return `${access} ${count} ${count === 1 ? 'repository' : 'repositories'}${where}`;+}++/** Those of the installation's repositories matching `query`, leaving out `exclude`. */+export function matchingRepositories(+ installation: GitHubInstallation,+ query: string,+ exclude: number[]+): GitHubRepository[] {+ const needle = query.trim().toLowerCase();+ return installation.repositories.filter(+ (repository) =>+ !exclude.includes(repository.id) &&+ (needle === '' || repository.name.toLowerCase().includes(needle))+ );+}++export function withRepository(choice: GitHubGrantChoice, id: number): GitHubGrantChoice {+ return choice.repositoryIds.includes(id)+ ? choice+ : { ...choice, repositoryIds: [...choice.repositoryIds, id] };+}++export function withoutRepository(choice: GitHubGrantChoice, id: number): GitHubGrantChoice {+ return { ...choice, repositoryIds: choice.repositoryIds.filter((other) => other !== id) };+}++/** Every repository of the chosen installation, keeping the order already chosen. */+export function withEveryRepository(+ github: ConnectedGitHub,+ choice: GitHubGrantChoice+): GitHubGrantChoice {+ const installation = chosenInstallation(github, choice);+ if (!installation) return choice;+ const rest = installation.repositories+ .map((r) => r.id)+ .filter((id) => !choice.repositoryIds.includes(id));+ return { ...choice, repositoryIds: [...choice.repositoryIds, ...rest] };+}++/** The choice for another installation: its repositories are different ones. */+export function withInstallation(choice: GitHubGrantChoice, id: number | null): GitHubGrantChoice {+ return { ...choice, installationId: id, repositoryIds: [] };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.tsnew file mode 100644index 000000000..62182b583--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/grant-agents.ts@@ -0,0 +1,45 @@+import type {+ ConnectionAgent,+ ConnectionCatalogEntry,+} from '@shared/core/switch-servers/connection-catalog';++/** Said of an agent others can address: whoever addresses it would have it act as its owner. */+export const OPEN_AGENT_NOTE = 'Others can address it; it would act as you.';++/**+ * Whether the person adds agents to `entry` from its page: a service a grant+ * simply switches on, and GitHub, whose grant names repositories chosen above+ * the agents. A minted service other than GitHub is granted from the agent's+ * Connections tab.+ */+export function offersAddAgent(entry: ConnectionCatalogEntry): boolean {+ return entry.pass_through || entry.slug === 'github';+}++/** What the Add agent search says an added agent gets, for a service with no choice to make. */+export function addAgentIntro(entry: ConnectionCatalogEntry): string {+ return `An agent you add acts as you at ${entry.name}, with what your connection allows.`;+}++/** The count beside the heading: how many of the person's agents use the service. */+export function agentsSummary(count: number): string {+ return `${count} ${count === 1 ? 'agent' : 'agents'}`;+}++/** The agents the search offers: those without the service, matching what was typed. */+export function addableAgents(agents: ConnectionAgent[], filter: string): ConnectionAgent[] {+ const query = filter.trim().toLowerCase();+ return agents.filter(+ (agent) => !agent.granted && (query === '' || agent.name.toLowerCase().includes(query))+ );+}++/** What the section says when the person has no agents in the workspace. */+export function noAgentsText(serviceName: string): string {+ return `You have no agents in this workspace yet. Once you add one, turn ${serviceName} on for it from the agent's Connections tab.`;+}++/** What stands in for the agents on a server that cannot list them. */+export function agentsUnlistedText(serviceName: string): string {+ return `This server can't list your agents here. Turn ${serviceName} on for an agent from the agent's Connections tab.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/repository-search-input.tsx b/console/apps/switch-console-desktop/src/renderer/features/connectors/repository-search-input.tsxnew file mode 100644index 000000000..e7f7daaa8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/repository-search-input.tsx@@ -0,0 +1,48 @@+import { Search, X } from 'lucide-react';+import {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+} from '@renderer/lib/ui/input-group';++/** The search field over a list of repositories, with a clear once something is typed. */+export function RepositorySearchInput({+ value,+ onChange,+ label,+ placeholder,+ autoFocus = false,+}: {+ value: string;+ onChange: (value: string) => void;+ label: string;+ placeholder: string;+ autoFocus?: boolean;+}) {+ return (+ <InputGroup>+ <InputGroupAddon>+ <Search className="size-3.5 text-foreground-muted" />+ </InputGroupAddon>+ <InputGroupInput+ autoFocus={autoFocus}+ placeholder={placeholder}+ aria-label={label}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ {value !== '' && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ size="icon-xs"+ aria-label="Clear the search"+ onClick={() => onChange('')}+ >+ <X className="size-3.5" />+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/connectors/use-connect-service.ts b/console/apps/switch-console-desktop/src/renderer/features/connectors/use-connect-service.tsnew file mode 100644index 000000000..cef0c944d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/connectors/use-connect-service.ts@@ -0,0 +1,36 @@+import { useCallback } from 'react';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { useReloadConnectors } from './connectors-queries';++/**+ * Opens the connect modal for a service, from its card or its profile, and+ * re-reads the page as soon as the service is connected, so the profile behind+ * the dialog is current, and again however the modal ends. `afterConnected`+ * runs as the service is connected, with the warning Switch gave, so the+ * caller can open the page's Add agent search.+ */+export function useConnectService(serverId: string, workspaceId: string) {+ const showConnect = useShowModal('connectServiceModal');+ const reload = useReloadConnectors(workspaceId);+ return useCallback(+ (+ connection: ConnectionCatalogEntry,+ startAt: 'connect' | 'replace',+ afterConnected: (warning: string | null) => void+ ) =>+ showConnect({+ serverId,+ workspaceId,+ connection,+ startAt,+ onConnected: (warning) => {+ void reload();+ afterConnected(warning);+ },+ onSuccess: () => void reload(),+ onClose: () => void reload(),+ }),+ [showConnect, reload, serverId, workspaceId]+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsxindex ba27e1563..c029e7bfa 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx@@ -1,7 +1,9 @@import { Bot, ExternalLink, MoreVertical, RotateCcw, Server, Trash2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-confirm-delete-agent';+import { useLocalAgentTab } from '@renderer/features/locations/hooks/use-local-agent-tab';import { agentsStore } from '@renderer/features/locations/stores/agents-store';+import { localAgentTabStore } from '@renderer/features/locations/stores/local-agent-tabs';import {asMounted,getLocationStore,@@ -28,6 +30,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import type { Agent } from '@shared/core/agents/agents';@@ -187,17 +190,30 @@ export const LocationTitlebar = observer(function LocationTitlebar() {: null;const mounted = locationViewKind(store) === 'ready' ? asMounted(store) : undefined;+ const { tabs, tab } = useLocalAgentTab(agent);return (<Titlebar+ leftClassName="min-w-0"leftSlot={- <div className="flex items-center gap-2">- <AgentCrumb agent={agent} />+ <div className="flex min-w-0 items-center gap-2">+ <div className="min-w-0 truncate">+ <AgentCrumb agent={agent} />+ </div>{agent?.ownerName && (- <span className="text-xs text-foreground-tertiary-passive">+ <span className="shrink-0 text-xs text-foreground-tertiary-passive">loaded · by {agent.ownerName}</span>)}+ {agent && tabs && (+ <SegmentedControl+ className="shrink-0"+ value={tab}+ onChange={(next) => localAgentTabStore.setTab(agent.id, next)}+ options={tabs}+ ariaLabel="Agent view"+ />+ )}</div>}rightSlot={diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex 29a7ed522..f96c76a5b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -5,10 +5,13 @@ import { AgentSaveBar } from '@renderer/features/locations/components/main-panelimport { SessionList } from '@renderer/features/locations/components/session-view/session-list';import { SettingsPanel } from '@renderer/features/locations/components/settings-view/settings-panel';import { SidecarPanel } from '@renderer/features/locations/components/settings-view/sidecar-panel';+import { useLocalAgentTab } from '@renderer/features/locations/hooks/use-local-agent-tab';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import {asMounted,getLocationStore,} from '@renderer/features/locations/stores/location-selectors';+import { AgentConnectionsTab } from '@renderer/features/managed-agents/agent-connections-tab';import { useParams } from '@renderer/lib/layout/navigation-provider';/**@@ -17,15 +20,29 @@ import { useParams } from '@renderer/lib/layout/navigation-provider';** It used to be three tabs down a side nav, which asked the reader to know* which of them held what before they could look at anything. The page is short- * enough to scroll instead.+ * enough to scroll instead. The one exception is Connections, a tab of its+ * own as on a managed agent's page, for an agent registered on a server with+ * service connections on.*/export const ActiveLocation = observer(function ActiveLocation() {const {- params: { locationId },+ params: { locationId, agentName },} = useParams('location');const store = asMounted(getLocationStore(locationId));+ const agent = agentsStore.agentAtLocation(locationId, agentName);+ const { tab } = useLocalAgentTab(agent);if (!store) return null;+ if (tab === 'connections' && agent?.workspaceId && agent.switchAgentId)+ return (+ <AgentConnectionsTab+ key={agent.id}+ workspaceId={agent.workspaceId}+ agentId={agent.switchAgentId}+ agentName={agent.name}+ cloud={false}+ />+ );return (<AgentEditsProvider>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants-settings-section.tsxindex 36ac8718c..2d0076f12 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants-settings-section.tsx@@ -1,41 +1,39 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { useState } from 'react';+import {+ type GitHubGrantChoice,+ connectedGitHub,+ emptyGitHubGrant,+ githubGrantResources,+} from '@renderer/features/connectors/github-grant';+import { GitHubGrantPicker } from '@renderer/features/connectors/github-grant-picker';+import {+ ownerOnlyRequest,+ ownerOnlyWarningText,+} from '@renderer/features/managed-agents/agent-connections';import { failureText } from '@renderer/lib/errors/describe-failure';import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { rpc } from '@renderer/lib/ipc';import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';-import { Checkbox } from '@renderer/lib/ui/checkbox';-import { SegmentedControl } from '@renderer/lib/ui/segmented-control';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';import { Spinner } from '@renderer/lib/ui/spinner';import { Switch } from '@renderer/lib/ui/switch';import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';import type { GitHubConnection } from '@shared/core/switch-servers/github-connection';-import { OWNER_ONLY_POLICY, type ServiceGrant } from '@shared/core/switch-servers/service-grants';+import type { ServiceGrant } from '@shared/core/switch-servers/service-grants';import {CLOUD_GITHUB_GRANT_NOTES,GITHUB_GRANT_NOTES,REMOVED_GRANT_NOTE,grantedRepositoryIds,grantedRepositoryNames,+ onOffGrantBlock,onOffGrantNote,} from './service-grants';type Access = 'read' | 'write';-const ACCESS_OPTIONS = [- { value: 'read', label: 'Read' },- { value: 'write', label: 'Read and push' },-] as const;-/*** What the agent may use of its owner's service connections: its grants, who* else can reach it and so its grants, and what a GitHub grant does on the@@ -159,23 +157,19 @@ export function ServiceGrantsRow({<span className="text-sm font-medium">Service access</span><p className="text-sm text-foreground-muted">What {agentName} may use of your own connections. Its sessions are given short-lived- access for what you grant, and nothing else.+ access for what you turn on, and nothing else.</p></div>{change.isError && (<span className="text-xs text-destructive">- {failureText(change.error, 'Could not change the grant.')}+ {failureText(change.error, 'Could not change its access.')}</span>)}{notice && <span className="text-xs text-foreground-muted">{notice}</span>}{grants.data.addressing_open && grants.data.grants.length > 0 && (<Alert variant="warning">- <AlertDescription>- Anyone who can address {agentName} can have it use these grants. Owner-only stops that,- but it still reads what others write in shared rooms, can be reached through your other- agents that are open, and posts results to shared rooms.- </AlertDescription>+ <AlertDescription>{ownerOnlyWarningText(agentName)}</AlertDescription><AlertAction><Buttonsize="sm"@@ -183,11 +177,9 @@ export function ServiceGrantsRow({disabled={change.isPending}onClick={() =>change.mutate(async () => {- await rpc.workspaces.updateAddressingPolicy({- workspaceId,- agentId,- policy: OWNER_ONLY_POLICY,- });+ await rpc.workspaces.updateAddressingPolicy(+ ownerOnlyRequest(workspaceId, agentId)+ );await queryClient.invalidateQueries({queryKey: ['agent-addressing-policy', workspaceId, agentId],});@@ -235,6 +227,7 @@ export function ServiceGrantsRow({<GitHubGrantFormgithub={github}current={githubGrant}+ agentName={agentName}busy={change.isPending}onCancel={githubGrant ? () => setEditing(false) : null}onSave={(access, resources) => set('github', access, resources)}@@ -254,7 +247,7 @@ export function ServiceGrantsRow({* A service whose agents use the owner's own token: the grant is on or off,* at the connection's level, and says what that means.*/-function OnOffGrant({+export function OnOffGrant({service,grant,agentName,@@ -269,9 +262,7 @@ function OnOffGrant({onTurnOn: () => void;onTurnOff: () => void;}) {- const connected = service.status === 'connected';- // 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 block = onOffGrantBlock(service, grant !== null);return (<div className="rounded-lg border border-border p-3"><div className="flex items-center gap-2">@@ -280,25 +271,18 @@ function OnOffGrant({<Switcharia-label={`${service.name} for ${agentName}`}checked={grant !== null}- disabled={busy || blocked}+ disabled={busy || block?.blocksOn === true}onCheckedChange={(on) => (on ? onTurnOn() : onTurnOff())}/></div>{grant && <p className="mt-1 text-sm text-foreground-muted">{grant.summary}</p>}- {service.unavailable_reason && (- <p className="mt-1 text-sm text-foreground-muted">{service.unavailable_reason}</p>- )}- {!grant && !connected && !service.unavailable_reason && (- <p className="mt-1 text-sm text-foreground-muted">- To turn {service.name} on, first connect it from the server's Connections.- </p>- )}+ {block && <p className="mt-1 text-sm text-foreground-muted">{block.reason}</p>}<p className="mt-1 text-xs text-foreground-muted">{onOffGrantNote(agentName, service)}</p></div>);}-function GrantCard({+export function GrantCard({grant,github,busy,@@ -342,27 +326,32 @@ function GrantCard({);}-function GitHubGrantForm({+export function GitHubGrantForm({github,current,+ agentName,busy,onCancel,onSave,}: {github: { data: GitHubConnection | undefined; isError: boolean; error: unknown };current: ServiceGrant | null;+ agentName: string;busy: boolean;onCancel: (() => void) | null;onSave: (access: Access, resources: Record<string, unknown>) => void;}) {- const [access, setAccess] = useState<Access>(current?.access ?? 'read');- const [installationId, setInstallationId] = useState<number | null>(- typeof current?.resources.installation_id === 'number'- ? current.resources.installation_id- : null- );- const [selected, setSelected] = useState<number[]>(- current ? grantedRepositoryIds(current.resources) : []+ const [choice, setChoice] = useState<GitHubGrantChoice>(() =>+ current+ ? {+ access: current.access ?? 'read',+ installationId:+ typeof current.resources.installation_id === 'number'+ ? current.resources.installation_id+ : null,+ repositoryIds: grantedRepositoryIds(current.resources),+ }+ : emptyGitHubGrant(github.data));if (github.isError)@@ -375,67 +364,28 @@ function GitHubGrantForm({if (github.data.status === 'not_connected')return (<p className="text-sm text-foreground-muted">- To grant GitHub, first connect your GitHub account from the server's Connections.+ To turn GitHub on, first connect your GitHub account from Connectors.</p>);- const installations = github.data.installations;- const installation = installations.find((candidate) => candidate.id === installationId);- const toggle = (id: number) =>- setSelected((now) => (now.includes(id) ? now.filter((other) => other !== id) : [...now, id]));+ const reach = connectedGitHub(github.data);+ const resources = githubGrantResources(choice);return (<div className="flex flex-col gap-3 rounded-lg border border-border p-3"><span className="text-sm font-medium">- {current ? 'Change the GitHub grant' : 'Grant GitHub'}+ {current+ ? `Change which repositories ${agentName} reaches`+ : `Turn GitHub on for ${agentName}`}</span>- <Select- value={installationId === null ? null : String(installationId)}- onValueChange={(value) => {- setInstallationId(value ? Number(value) : null);- setSelected([]);- }}- >- <SelectTrigger aria-label="GitHub account" className="w-full">- <SelectValue placeholder="Choose a GitHub account">{installation?.account}</SelectValue>- </SelectTrigger>- <SelectContent>- {installations.map((candidate) => (- <SelectItem key={candidate.id} value={String(candidate.id)}>- {candidate.account}- </SelectItem>- ))}- </SelectContent>- </Select>- {installation && (- <div role="group" aria-label="Repositories" className="max-h-48 space-y-1 overflow-auto">- {installation.repositories.map((repository) => (- <label key={repository.id} className="flex items-center gap-2 text-sm">- <Checkbox- checked={selected.includes(repository.id)}- onCheckedChange={() => toggle(repository.id)}- />- {repository.name}- </label>- ))}- </div>- )}- <SegmentedControl- ariaLabel="Access"- value={access}- onChange={setAccess}- options={ACCESS_OPTIONS}- />+ {reach && <GitHubGrantPicker github={reach} value={choice} onChange={setChoice} />}<div className="flex gap-2"><Buttonsize="sm"- disabled={busy || !installation || selected.length === 0}- onClick={() =>- installation &&- onSave(access, { installation_id: installation.id, repository_ids: selected })- }+ disabled={busy || resources === null}+ onClick={() => resources && onSave(choice.access, resources)}>- {current ? 'Save' : 'Grant'}+ {current ? 'Save' : 'Turn on'}</Button>{onCancel && (<Button size="sm" variant="ghost" onClick={onCancel}>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.test.tsindex b3c039865..7a66b4c4a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { grantedRepositoryIds, grantedRepositoryNames } from './service-grants';+import { grantedRepositoryIds, grantedRepositoryNames, onOffGrantBlock } from './service-grants';const GITHUB = {status: 'connected' as const,@@ -28,3 +28,47 @@ describe('GitHub grant helpers', () => {expect(grantedRepositoryIds({})).toEqual([]);});});++describe('turning an on/off grant on', () => {+ const service = {+ name: 'Example',+ status: 'connected' as const,+ unavailable_reason: null,+ workspace_enabled: true,+ };++ it('is allowed for a connected service the workspace has on, or with no workspace switch', () => {+ expect(onOffGrantBlock(service, false)).toBeNull();+ expect(onOffGrantBlock({ ...service, workspace_enabled: null }, false)).toBeNull();+ });++ it('is blocked with the workspace reason while the workspace has it off', () => {+ expect(onOffGrantBlock({ ...service, workspace_enabled: false }, false)).toEqual({+ reason:+ 'Example is not enabled in this workspace. Ask a workspace admin; they switch it on under Connectors.',+ blocksOn: true,+ });+ });++ it('still lets a grant be turned off, saying why it does nothing now', () => {+ expect(onOffGrantBlock({ ...service, workspace_enabled: false }, true)).toMatchObject({+ blocksOn: false,+ });+ });++ it("puts the server's reason before the workspace's", () => {+ expect(+ onOffGrantBlock(+ { ...service, unavailable_reason: 'Maintenance', workspace_enabled: false },+ false+ )+ ).toEqual({ reason: 'Maintenance', blocksOn: true });+ });++ it('sends a service nobody connected to Connectors', () => {+ expect(onOffGrantBlock({ ...service, status: 'not_connected' }, false)).toEqual({+ reason: 'To turn Example on, first connect it from Connectors.',+ blocksOn: true,+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.tsindex f2ed72501..137c1c80f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/service-grants.ts@@ -37,7 +37,7 @@ export const CLOUD_GITHUB_GRANT_NOTES = [APP_NOTE] as const;* simply ends the access.*/export const REMOVED_GRANT_NOTE =- 'Removing a grant stops Switch giving this access. On your computer, the agent may still use your own sign-in, and the session says so when it does.';+ 'Removing it stops Switch giving this access. On your computer, the agent may still use your own sign-in, and the session says so when it does.';/*** What turning on a service whose agents use the owner's own token means, and@@ -60,10 +60,38 @@ export function onOffGrantNote(: note;}+/**+ * Why an on/off grant cannot be turned on, or why one that is on does nothing+ * now; null when neither. The server's own reason comes first, then the+ * workspace's switch, then a missing connection. Turning a grant off is never+ * blocked, whatever the server or workspace says.+ */+export function onOffGrantBlock(+ service: Pick<+ ConnectionCatalogEntry,+ 'name' | 'status' | 'unavailable_reason' | 'workspace_enabled'+ >,+ granted: boolean+): { reason: string; blocksOn: boolean } | null {+ if (service.unavailable_reason !== null)+ return { reason: service.unavailable_reason, blocksOn: !granted };+ if (service.workspace_enabled === false)+ return {+ reason: `${service.name} is not enabled in this workspace. Ask a workspace admin; they switch it on under Connectors.`,+ blocksOn: !granted,+ };+ if (!granted && service.status !== 'connected')+ return {+ reason: `To turn ${service.name} on, first connect it from Connectors.`,+ blocksOn: true,+ };+ return null;+}+/** What a GitHub grant changes on the machine the agent runs on, and what it does not. */export const GITHUB_GRANT_NOTES = [APP_NOTE,- "Used first for this agent over HTTPS. For repositories outside the grant, or if Switch can't provide it, your own GitHub login is used and the session says so. SSH still uses your keys.",+ "Used first for this agent over HTTPS. For repositories not chosen here, or if Switch can't provide it, your own GitHub login is used and the session says so. SSH still uses your keys.","On your computer, the agent can still use anything you're signed in to.",'Not available on Windows yet.',] as const;diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex b7e75d45a..07ba1e1ff 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -8,6 +8,8 @@ import { AutoApproveSettingsSection } from '@renderer/features/locations/componeimport { CanManageAgentsSettingsSection } from '@renderer/features/locations/components/settings-view/sections/can-manage-agents-settings-section';import { ProviderSignInSettingsSection } from '@renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section';import { ServiceGrantsSettingsSection } from '@renderer/features/locations/components/settings-view/sections/service-grants-settings-section';+import { useLocalAgentTab } from '@renderer/features/locations/hooks/use-local-agent-tab';+import { agentsStore } from '@renderer/features/locations/stores/agents-store';import {asMounted,getLocationStore,@@ -21,6 +23,8 @@ export const SettingsPanel = observer(function SettingsPanel() {params: { locationId, agentName },} = useParams('location');const mounted = asMounted(getLocationStore(locationId));+ // With a Connections tab, the agent's grants are there and not here.+ const { tabs } = useLocalAgentTab(agentsStore.agentAtLocation(locationId, agentName));// Resolve the specific agent the page is scoped to (by its definition name),// so its settings render through the normal per-agent sections. Switch Console has@@ -50,7 +54,9 @@ export const SettingsPanel = observer(function SettingsPanel() {<AutoApproveSettingsSection locationId={locationId} agentId={agentId} /><AddressingPolicySettingsSection locationId={locationId} agentId={agentId} /><CanManageAgentsSettingsSection locationId={locationId} agentId={agentId} />- <ServiceGrantsSettingsSection locationId={locationId} agentId={agentId} />+ {tabs === null && (+ <ServiceGrantsSettingsSection locationId={locationId} agentId={agentId} />+ )}</section><AgentAdvancedSettingsSection locationId={locationId} agentId={agentId} /></div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-local-agent-tab.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-local-agent-tab.tsnew file mode 100644index 000000000..19d7c22c1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-local-agent-tab.ts@@ -0,0 +1,22 @@+import {+ localAgentTabs,+ localAgentTabStore,+ shownLocalAgentTab,+} from '@renderer/features/locations/stores/local-agent-tabs';+import { useAgentServiceGrants } from '@renderer/features/managed-agents/agent-connections-tab';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';+import type { Agent } from '@shared/core/agents/agents';++/** The tabs a local agent's page offers, or null for none, and which tab is showing. */+export function useLocalAgentTab(agent: Agent | null) {+ const serviceConnections = useFeatureFlags(agent?.serverId).service_connections;+ const registered = agent?.workspaceId != null && agent.switchAgentId !== null;+ const grants = useAgentServiceGrants(+ serviceConnections && registered,+ agent?.workspaceId ?? null,+ agent?.switchAgentId ?? ''+ );+ const tabs = localAgentTabs(registered, serviceConnections, grants.data);+ const chosen = agent ? localAgentTabStore.tabFor(agent.id) : 'overview';+ return { tabs, tab: shownLocalAgentTab(chosen, tabs) };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.test.tsnew file mode 100644index 000000000..79f443eb0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';+import { LocalAgentTabStore, localAgentTabs, shownLocalAgentTab } from './local-agent-tabs';++const GRANTS: ServiceGrants = { grants: [], addressing_open: false };++const values = (tabs: ReturnType<typeof localAgentTabs>) => tabs?.map((tab) => tab.value) ?? null;++describe("a local agent's tabs", () => {+ it('offers Overview and Connections for a registered agent whose grants are yours', () => {+ expect(values(localAgentTabs(true, true, GRANTS))).toEqual(['overview', 'connections']);+ });++ it('offers them while the grants load', () => {+ expect(values(localAgentTabs(true, true, undefined))).toEqual(['overview', 'connections']);+ });++ it('has no tabs for an agent not registered on a server', () => {+ expect(localAgentTabs(false, true, undefined)).toBeNull();+ });++ it('has no tabs when the server has service connections off', () => {+ expect(localAgentTabs(true, false, GRANTS)).toBeNull();+ });++ it("has no tabs for an agent you don't own, such as one loaded from someone else", () => {+ expect(localAgentTabs(true, true, null)).toBeNull();+ });++ it('shows the chosen tab, or Overview when the page has no tabs', () => {+ expect(shownLocalAgentTab('connections', localAgentTabs(true, true, GRANTS))).toBe(+ 'connections'+ );+ expect(shownLocalAgentTab('connections', localAgentTabs(true, true, null))).toBe('overview');+ });+});++describe('the local agent tab store', () => {+ it('keeps Connections for the agent it was chosen on, and starts another agent on Overview', () => {+ const store = new LocalAgentTabStore();+ store.setTab('local-1', 'connections');+ expect(store.tabFor('local-1')).toBe('connections');+ expect(store.tabFor('local-2')).toBe('overview');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.tsnew file mode 100644index 000000000..140da82a7--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/local-agent-tabs.ts@@ -0,0 +1,60 @@+import { makeAutoObservable } from 'mobx';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';++export type LocalAgentTab = 'overview' | 'connections';++export type LocalAgentTabOption = { value: LocalAgentTab; label: string };++const TABS: readonly LocalAgentTabOption[] = [+ { value: 'overview', label: 'Overview' },+ { value: 'connections', label: 'Connections' },+];++/**+ * The tabs a local agent's page offers, or null for none: the page is then+ * the one scrolling page it always was. Connections is the only reason for+ * tabs, so they need what it needs: the agent registered on a server, the+ * server's `service_connections` flag, and grants that are the caller's. A+ * server answers null for another person's agent, such as one loaded from+ * them. While the grants load the tabs are offered.+ */+export function localAgentTabs(+ registered: boolean,+ serviceConnections: boolean,+ grants: ServiceGrants | null | undefined+): readonly LocalAgentTabOption[] | null {+ return registered && serviceConnections && grants !== null ? TABS : null;+}++/** The tab to show: the one chosen, or Overview when the page has no tabs. */+export function shownLocalAgentTab(+ chosen: LocalAgentTab,+ tabs: readonly LocalAgentTabOption[] | null+): LocalAgentTab {+ return tabs === null ? 'overview' : chosen;+}++/**+ * Which tab the open local agent is showing, as a managed agent's is kept:+ * one selection, remembered against the agent's local id, so opening a+ * different agent starts on its overview.+ */+export class LocalAgentTabStore {+ private agentId: string | null = null;+ private tab: LocalAgentTab = 'overview';++ constructor() {+ makeAutoObservable(this, {}, { autoBind: true });+ }++ tabFor(agentId: string): LocalAgentTab {+ return this.agentId === agentId ? this.tab : 'overview';+ }++ setTab(agentId: string, tab: LocalAgentTab): void {+ this.agentId = agentId;+ this.tab = tab;+ }+}++export const localAgentTabStore = new LocalAgentTabStore();diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections-tab.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections-tab.tsxnew file mode 100644index 000000000..2b76e3c20--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections-tab.tsx@@ -0,0 +1,394 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { ChevronRight, X } from 'lucide-react';+import { type ReactNode, useEffect, useRef, useState } from 'react';+import {+ CLOUD_GITHUB_GRANT_NOTES,+ GITHUB_GRANT_NOTES,+ REMOVED_GRANT_NOTE,+} from '@renderer/features/locations/components/settings-view/sections/service-grants';+import {+ GitHubGrantForm,+ GrantCard,+ OnOffGrant,+} from '@renderer/features/locations/components/settings-view/sections/service-grants-settings-section';+import { ConnectionIcon } from '@renderer/features/switch-servers/connection-icon';+import { ServerPage } from '@renderer/features/switch-servers/server-page';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { cn } from '@renderer/utils/utils';+import {+ type AgentConnectionCard,+ agentConnectionCards,+ connectionCardDetail,+ connectionCardStatus,+ ownerOnlyRequest,+ ownerOnlyWarningText,+ showsOwnerOnlyWarning,+ unconnectedNote,+} from './agent-connections';++type Access = 'read' | 'write';++const DRAWER_WIDTH = 480;++/**+ * The agent's grants, under the key its Service access row reads, so the two+ * share one cache. Null when they are not the caller's.+ */+export function useAgentServiceGrants(shown: boolean, workspaceId: string | null, agentId: string) {+ return useQuery({+ queryKey: ['agent-service-grants', workspaceId, agentId],+ queryFn: () => rpc.workspaces.getServiceGrants({ workspaceId: workspaceId as string, agentId }),+ enabled: shown && workspaceId !== null,+ retry: false,+ });+}++/**+ * An agent's Connections tab, on a managed or a local agent's page: one card+ * per service its owner has connected, and a drawer to grant or change one.+ * The drawer sits over the page rather than replacing it: picking a service+ * is a look, not a move. `cloud` is for a cloud agent, whose sessions have no+ * GitHub sign-in of their own and run on no machine of the owner's.+ */+export function AgentConnectionsTab({+ workspaceId,+ agentId,+ agentName: label,+ cloud,+}: {+ workspaceId: string;+ /** The agent's id in Switch. */+ agentId: string;+ agentName: string;+ cloud: boolean;+}) {+ const queryClient = useQueryClient();+ const [openSlug, setOpenSlug] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [editing, setEditing] = useState(false);+ const grants = useAgentServiceGrants(true, workspaceId, agentId);+ // The agent's workspace, not whichever one is active on its server.+ const github = useQuery({+ queryKey: ['workspace-github', workspaceId],+ queryFn: () => rpc.workspaces.getGitHubConnection(workspaceId),+ retry: false,+ });+ const services = useQuery({+ queryKey: ['workspace-service-connections', workspaceId],+ queryFn: () => rpc.workspaces.getServiceConnections(workspaceId),+ retry: false,+ });++ const change = useMutation({+ mutationFn: async (run: () => Promise<string | null | void>) => run(),+ onSuccess: async (warning) => {+ setNotice(warning ?? null);+ setEditing(false);+ await queryClient.invalidateQueries({+ queryKey: ['agent-service-grants', workspaceId, agentId],+ });+ },+ });+ const set = (service: string, access: Access | null, resources: Record<string, unknown>) =>+ change.mutate(() =>+ rpc.workspaces.setServiceGrant({ workspaceId, agentId, service, access, resources })+ );+ const remove = (service: string) =>+ change.mutate(async () => {+ const warning = await rpc.workspaces.removeServiceGrant({ workspaceId, agentId, service });+ return [warning, cloud ? null : REMOVED_GRANT_NOTE].filter(Boolean).join(' ') || null;+ });+ const open = (slug: string | null) => {+ change.reset();+ setNotice(null);+ setEditing(false);+ setOpenSlug(slug);+ };++ const page = (children: ReactNode) => (+ <ServerPage+ width={900}+ title="Connections"+ description={`What ${label} may use of your own connections. Its sessions are given short-lived access for what you turn on, and nothing else.`}+ >+ {children}+ </ServerPage>+ );+ if (grants.isPending)+ return page(+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading service access…+ </p>+ );+ if (grants.isError)+ return page(+ <p role="alert" className="text-sm text-destructive">+ {failureText(grants.error, 'Could not load service access.')}+ </p>+ );+ // The page hides this tab once the grants come back null; this is the moment before.+ if (grants.data === null) return page(null);+ const current = grants.data;+ const { cards, unconnected } = agentConnectionCards(services.data ?? [], current.grants);+ const note = unconnectedNote(unconnected);+ const opened = cards.find((card) => card.slug === openSlug) ?? null;++ return (+ <div className="relative flex min-h-0 flex-1 flex-col">+ {page(+ <>+ {showsOwnerOnlyWarning(current) && (+ <Alert variant="warning">+ <AlertDescription>{ownerOnlyWarningText(label)}</AlertDescription>+ <AlertAction>+ <Button+ size="sm"+ variant="outline"+ disabled={change.isPending}+ onClick={() =>+ change.mutate(async () => {+ await rpc.workspaces.updateAddressingPolicy(+ ownerOnlyRequest(workspaceId, agentId)+ );+ await queryClient.invalidateQueries({+ queryKey: ['agent-addressing-policy', workspaceId, agentId],+ });+ })+ }+ >+ Make owner-only+ </Button>+ </AlertAction>+ </Alert>+ )}+ {change.isError && opened === null && (+ <p role="alert" className="text-sm text-destructive">+ {failureText(change.error, 'Could not make the agent owner-only.')}+ </p>+ )}+ {services.isError && (+ <p role="alert" className="text-sm text-destructive">+ {failureText(services.error, 'Could not load your connections.')}+ </p>+ )}+ {services.isPending ? (+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Loading your connections…+ </p>+ ) : (+ cards.length > 0 && (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {cards.map((card) => (+ <ConnectionCard+ key={card.slug}+ card={card}+ selected={card.slug === openSlug}+ onOpen={() => open(card.slug)}+ />+ ))}+ </div>+ )+ )}+ {services.isSuccess && cards.length === 0 && note === null && (+ <p className="text-sm text-foreground-muted">+ No service on this server can be turned on for {label} yet.+ </p>+ )}+ {note && <p className="text-sm text-foreground-muted">{note}</p>}+ </>+ )}+ {opened && (+ <ConnectionDrawer key={opened.slug} card={opened} onClose={() => open(null)}>+ {change.isError && (+ <p role="alert" className="text-xs text-destructive">+ {failureText(change.error, `Could not change its ${opened.name} access.`)}+ </p>+ )}+ {notice && <p className="text-xs text-foreground-muted">{notice}</p>}+ {opened.kind === 'on-off' && opened.service && (+ <OnOffGrant+ service={opened.service}+ grant={opened.grant}+ agentName={label}+ busy={change.isPending}+ onTurnOn={() => set(opened.slug, null, {})}+ onTurnOff={() => remove(opened.slug)}+ />+ )}+ {opened.kind === 'github' && (+ <GitHubDrawerBody+ card={opened}+ github={github}+ agentName={label}+ cloud={cloud}+ busy={change.isPending}+ editing={editing}+ onEdit={setEditing}+ onSave={(access, resources) => set('github', access, resources)}+ onRemove={() => remove('github')}+ />+ )}+ {opened.kind === 'other' && opened.grant && (+ <GrantCard+ grant={opened.grant}+ github={github.data}+ busy={change.isPending}+ onChange={null}+ removeNote={cloud ? null : REMOVED_GRANT_NOTE}+ onRemove={() => remove(opened.slug)}+ />+ )}+ </ConnectionDrawer>+ )}+ </div>+ );+}++function ConnectionCard({+ card,+ selected,+ onOpen,+}: {+ card: AgentConnectionCard;+ selected: boolean;+ onOpen: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onOpen}+ aria-expanded={selected}+ className={cn(+ 'flex w-full items-start gap-3 rounded-lg border p-4 text-left transition-colors',+ 'focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',+ selected ? 'border-foreground/30 bg-background-2' : 'border-border hover:bg-background-2'+ )}+ >+ <ConnectionIcon slug={card.slug} name={card.name} />+ <span className="flex min-w-0 flex-1 flex-col items-start gap-1.5">+ <span className="flex w-full min-w-0 items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{card.name}</span>+ <Badge variant="outline">{connectionCardStatus(card)}</Badge>+ <ChevronRight className="size-4 shrink-0 text-foreground-muted" aria-hidden />+ </span>+ <span className="text-sm text-foreground-muted">{connectionCardDetail(card)}</span>+ </span>+ </button>+ );+}++/**+ * The drawer over the page's right edge. It is not modal: the cards stay in+ * view, focus moves in when it opens and back to its card when it closes, and+ * Escape closes it wherever focus is.+ */+function ConnectionDrawer({+ card,+ onClose,+ children,+}: {+ card: AgentConnectionCard;+ onClose: () => void;+ children: ReactNode;+}) {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const opener = document.activeElement;+ ref.current?.focus();+ return () => {+ if (opener instanceof HTMLElement) opener.focus();+ };+ }, []);+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === 'Escape') onClose();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [onClose]);++ return (+ <div+ ref={ref}+ role="dialog"+ aria-label={card.name}+ tabIndex={-1}+ style={{ width: DRAWER_WIDTH, maxWidth: '100%' }}+ className="absolute inset-y-0 right-0 z-20 flex flex-col border-l border-border bg-background shadow-lg focus:outline-none"+ >+ <div className="flex shrink-0 items-center gap-2 border-b border-border p-3 pl-4">+ <ConnectionIcon slug={card.slug} name={card.name} />+ <h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{card.name}</h3>+ <Button+ variant="ghost"+ size="sm"+ className="size-7 p-0"+ aria-label={`Close ${card.name}`}+ onClick={onClose}+ >+ <X className="size-4" />+ </Button>+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">{children}</div>+ </div>+ );+}++function GitHubDrawerBody({+ card,+ github,+ agentName,+ cloud,+ busy,+ editing,+ onEdit,+ onSave,+ onRemove,+}: {+ card: AgentConnectionCard;+ github: Parameters<typeof GitHubGrantForm>[0]['github'];+ agentName: string;+ cloud: boolean;+ busy: boolean;+ /** Whether the form for changing an existing grant is open. */+ editing: boolean;+ onEdit: (editing: boolean) => void;+ onSave: (access: Access, resources: Record<string, unknown>) => void;+ onRemove: () => void;+}) {+ const { grant } = card;+ return (+ <>+ {grant && (+ <GrantCard+ grant={grant}+ github={github.data}+ busy={busy}+ onChange={() => onEdit(true)}+ removeNote={cloud ? null : REMOVED_GRANT_NOTE}+ onRemove={onRemove}+ />+ )}+ {(editing || !grant) && (+ <GitHubGrantForm+ github={github}+ current={grant}+ agentName={agentName}+ busy={busy}+ onCancel={grant ? () => onEdit(false) : null}+ onSave={onSave}+ />+ )}+ <ul className="list-disc space-y-1 pl-5 text-xs text-foreground-muted">+ {(cloud ? CLOUD_GITHUB_GRANT_NOTES : GITHUB_GRANT_NOTES).map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ </>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.test.tsnew file mode 100644index 000000000..00f109a48--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.test.ts@@ -0,0 +1,179 @@+import { describe, expect, it } from 'vitest';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import type { ServiceGrant } from '@shared/core/switch-servers/service-grants';+import {+ agentConnectionCards,+ connectionCardDetail,+ connectionCardStatus,+ ownerOnlyRequest,+ ownerOnlyWarningText,+ showsOwnerOnlyWarning,+ unconnectedNote,+} from './agent-connections';++function service(+ slug: string,+ overrides: Partial<ConnectionCatalogEntry> = {}+): ConnectionCatalogEntry {+ return {+ slug,+ name: slug[0].toUpperCase() + slug.slice(1),+ category: 'Tools',+ description: `What ${slug} is.`,+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'connected',+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: null,+ loopback_ports: null,+ key: null,+ external_identity: null,+ workspace_enabled: null,+ consent: null,+ ...overrides,+ };+}++function grant(slug: string, overrides: Partial<ServiceGrant> = {}): ServiceGrant {+ return {+ service: slug,+ name: slug[0].toUpperCase() + slug.slice(1),+ access: 'read',+ resources: {},+ summary: `Uses your ${slug}.`,+ ...overrides,+ };+}++const slugs = (services: ConnectionCatalogEntry[], grants: ServiceGrant[]) =>+ agentConnectionCards(services, grants).cards.map((card) => [card.slug, card.kind]);++describe("an agent's connection cards", () => {+ it('has a card for each service you connected, GitHub with its repo picker and the rest on/off', () => {+ expect(+ slugs(+ [service('github', { pass_through: false }), service('atlassian'), service('datadog')],+ []+ )+ ).toEqual([+ ['github', 'github'],+ ['atlassian', 'on-off'],+ ['datadog', 'on-off'],+ ]);+ });++ it('keeps a card for a connection that needs reconnecting', () => {+ expect(slugs([service('atlassian', { status: 'needs_reauthorization' })], [])).toEqual([+ ['atlassian', 'on-off'],+ ]);+ });++ it('names the services you have not connected instead of giving them cards', () => {+ const { cards, unconnected } = agentConnectionCards(+ [service('atlassian'), service('datadog', { status: 'not_connected' })],+ []+ );+ expect(cards.map((card) => card.slug)).toEqual(['atlassian']);+ expect(unconnected).toEqual(['Datadog']);+ });++ it('leaves out coming-soon and switched-off placeholders, and services nothing here can grant', () => {+ const { cards, unconnected } = agentConnectionCards(+ [+ service('notion', { status: 'coming_soon' }),+ service('linear', { enabled: false, status: 'not_connected' }),+ service('gitlab', { pass_through: false }),+ ],+ []+ );+ expect(cards).toEqual([]);+ expect(unconnected).toEqual([]);+ });++ it('never hides a grant: one on a disconnected or unlisted service still has a card to remove it', () => {+ expect(+ slugs(+ [+ service('datadog', { status: 'not_connected' }),+ service('gitlab', { pass_through: false }),+ ],+ [grant('datadog'), grant('gitlab'), grant('retired')]+ )+ ).toEqual([+ ['datadog', 'on-off'],+ ['gitlab', 'other'],+ ['retired', 'other'],+ ]);+ });++ it('shows what the agent has: on or off, and the access level for GitHub', () => {+ const [github, atlassian, datadog] = agentConnectionCards(+ [service('github', { pass_through: false }), service('atlassian'), service('datadog')],+ [grant('github', { access: 'write' }), grant('atlassian')]+ ).cards;+ expect(connectionCardStatus(github)).toBe('Read and push');+ expect(connectionCardStatus(atlassian)).toBe('On');+ expect(connectionCardStatus(datadog)).toBe('Off');+ });++ it("says what a grant does, else why it can't be turned on, else what the service is", () => {+ const [granted, unavailable, stale, plain] = agentConnectionCards(+ [+ service('atlassian'),+ service('datadog', { unavailable_reason: 'Maintenance' }),+ service('google', { status: 'error' }),+ service('box'),+ ],+ [grant('atlassian')]+ ).cards;+ expect(connectionCardDetail(granted)).toBe('Uses your atlassian.');+ expect(connectionCardDetail(unavailable)).toBe('Maintenance');+ expect(connectionCardDetail(stale)).toBe(+ 'Your Google connection needs reconnecting. Reconnect it from Connectors.'+ );+ expect(connectionCardDetail(plain)).toBe('What box is.');+ });+});++describe('the note naming unconnected services', () => {+ it('sends them to Connectors', () => {+ expect(unconnectedNote(['Datadog'])).toBe(+ 'Not connected: Datadog. Connect it from Connectors to turn it on here.'+ );+ expect(unconnectedNote(['Atlassian', 'Datadog'])).toBe(+ 'Not connected: Atlassian, Datadog. Connect them from Connectors to turn them on here.'+ );+ });++ it('is absent when everything is connected', () => {+ expect(unconnectedNote([])).toBeNull();+ });+});++describe('the owner-only warning', () => {+ it('shows for an open agent that holds a grant', () => {+ expect(showsOwnerOnlyWarning({ addressing_open: true, grants: [grant('datadog')] })).toBe(true);+ });++ it('does not show for an owner-only agent, or an open one with nothing granted', () => {+ expect(showsOwnerOnlyWarning({ addressing_open: false, grants: [grant('datadog')] })).toBe(+ false+ );+ expect(showsOwnerOnlyWarning({ addressing_open: true, grants: [] })).toBe(false);+ });++ it('says owner-only means only you can address it, and what it still does in shared rooms', () => {+ expect(ownerOnlyWarningText('m2')).toBe(+ 'Anyone who can address m2 can have it use these grants. Owner-only stops that: only you can address it. It still reads what others write in shared rooms and posts results there.'+ );+ });++ it("makes the agent its owner's alone, not reachable through the owner's other agents", () => {+ const request = ownerOnlyRequest('workspace', 'agent');+ expect(request).toMatchObject({ workspaceId: 'workspace', agentId: 'agent' });+ expect(request.policy.rules).toHaveLength(1);+ expect(request.policy.rules[0]).toMatchObject({ owner: true, owner_agents: false, agents: [] });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.tsnew file mode 100644index 000000000..89936fa65--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-connections.ts@@ -0,0 +1,107 @@+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';+import type { ServiceGrant, ServiceGrants } from '@shared/core/switch-servers/service-grants';++/**+ * One card on an agent's Connections tab. GitHub's grant names repositories;+ * an on/off service hands the agent the owner's own token; `other` is a grant+ * on a service this page has nothing to change on, which can only be removed.+ */+export type AgentConnectionCard = {+ slug: string;+ name: string;+ kind: 'github' | 'on-off' | 'other';+ /** Its catalog entry; null for a grant whose service the catalog no longer lists. */+ service: ConnectionCatalogEntry | null;+ grant: ServiceGrant | null;+};++const GITHUB = 'github';++/** A service this page can grant: GitHub, or one whose agents use the owner's own token. */+function grantable(service: ConnectionCatalogEntry): boolean {+ return (+ service.enabled &&+ service.status !== 'coming_soon' &&+ (service.slug === GITHUB || service.pass_through)+ );+}++/**+ * The cards on an agent's Connections tab, in catalog order: every service+ * the owner has connected that a grant can be made on, and every grant the+ * agent holds, whatever its connection's state, so a grant is never hidden.+ * `unconnected` names the grantable services the owner has not connected.+ */+export function agentConnectionCards(+ services: readonly ConnectionCatalogEntry[],+ grants: readonly ServiceGrant[]+): { cards: AgentConnectionCard[]; unconnected: string[] } {+ const grantOf = (slug: string) => grants.find((grant) => grant.service === slug) ?? null;+ const cards: AgentConnectionCard[] = [];+ const unconnected: string[] = [];+ for (const service of services) {+ const grant = grantOf(service.slug);+ const offered = grantable(service);+ if (grant === null && !offered) continue;+ if (grant === null && service.status === 'not_connected') {+ unconnected.push(service.name);+ continue;+ }+ cards.push({+ slug: service.slug,+ name: service.name,+ kind: !offered ? 'other' : service.slug === GITHUB ? 'github' : 'on-off',+ service,+ grant,+ });+ }+ for (const grant of grants) {+ if (services.some((service) => service.slug === grant.service)) continue;+ cards.push({ slug: grant.service, name: grant.name, kind: 'other', service: null, grant });+ }+ return { cards, unconnected };+}++/** The card's badge: what the agent has of the service now. */+export function connectionCardStatus(card: AgentConnectionCard): string {+ if (card.grant === null) return 'Off';+ if (card.kind === 'on-off') return 'On';+ return card.grant.access === 'write' ? 'Read and push' : 'Read';+}++/**+ * The card's one line: what the grant lets the agent do, or why it cannot be+ * turned on, or what the service is.+ */+export function connectionCardDetail(card: AgentConnectionCard): string {+ if (card.grant) return card.grant.summary;+ const { service } = card;+ if (service === null) return '';+ if (service.unavailable_reason !== null) return service.unavailable_reason;+ if (service.status === 'needs_reauthorization' || service.status === 'error')+ return `Your ${service.name} connection needs reconnecting. Reconnect it from Connectors.`;+ return service.description;+}++/** The note under the cards naming the services not connected yet; null when there are none. */+export function unconnectedNote(names: readonly string[]): string | null {+ if (names.length === 0) return null;+ const them = names.length === 1 ? 'it' : 'them';+ return `Not connected: ${names.join(', ')}. Connect ${them} from Connectors to turn ${them} on here.`;+}++/** Whether to warn that anyone who can address the agent can use its grants. */+export function showsOwnerOnlyWarning(grants: ServiceGrants): boolean {+ return grants.addressing_open && grants.grants.length > 0;+}++/** The warning shown with {@link showsOwnerOnlyWarning}. */+export function ownerOnlyWarningText(label: string): string {+ return `Anyone who can address ${label} can have it use these grants. Owner-only stops that: only you can address it. It still reads what others write in shared rooms and posts results there.`;+}++/** What "Make owner-only" asks the server for: its owner alone, none of the owner's agents. */+export function ownerOnlyRequest(workspaceId: string, agentId: string) {+ return { workspaceId, agentId, policy: ownerOnlyPolicy() };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.tsindex ef293c765..12b986382 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tab-store.ts@@ -1,6 +1,6 @@import { makeAutoObservable } from 'mobx';-export type AgentTab = 'chats' | 'settings';+export type AgentTab = 'chats' | 'connections' | 'settings';/*** Which tab the open agent is showing, as the room page's tab is kept: onediff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.tsnew file mode 100644index 000000000..ee7044096--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';+import { AgentTabStore } from './agent-tab-store';+import { agentTabs, shownAgentTab } from './agent-tabs';++const GRANTS: ServiceGrants = { grants: [], addressing_open: false };++const values = (tabs: ReturnType<typeof agentTabs>) => tabs.map((tab) => tab.value);++describe('the agent tab store', () => {+ it('keeps Connections for the agent it was chosen on, and starts another agent on Chats', () => {+ const store = new AgentTabStore();+ store.setTab('agent-1', 'connections');+ expect(store.tabFor('agent-1')).toBe('connections');+ expect(store.tabFor('agent-2')).toBe('chats');+ });+});++describe("a managed agent's tabs", () => {+ it('offers Connections between Chats and Settings for an agent whose grants are yours', () => {+ expect(values(agentTabs(true, GRANTS))).toEqual(['chats', 'connections', 'settings']);+ });++ it('offers Connections while the grants load, since the page lists only your agents', () => {+ expect(values(agentTabs(true, undefined))).toEqual(['chats', 'connections', 'settings']);+ });++ it("hides Connections for an agent you don't own: the server answers its grants with null", () => {+ expect(values(agentTabs(true, null))).toEqual(['chats', 'settings']);+ });++ it('hides Connections when the server has service connections off', () => {+ expect(values(agentTabs(false, GRANTS))).toEqual(['chats', 'settings']);+ });++ it('shows the chosen tab, or Chats when Connections was chosen and is no longer offered', () => {+ expect(shownAgentTab('connections', agentTabs(true, GRANTS))).toBe('connections');+ expect(shownAgentTab('connections', agentTabs(true, null))).toBe('chats');+ expect(shownAgentTab('settings', agentTabs(false, GRANTS))).toBe('settings');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.tsnew file mode 100644index 000000000..02811d191--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-tabs.ts@@ -0,0 +1,27 @@+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';+import type { AgentTab } from './agent-tab-store';++export type AgentTabOption = { value: AgentTab; label: string };++const CHATS: AgentTabOption = { value: 'chats', label: 'Chats' };+const CONNECTIONS: AgentTabOption = { value: 'connections', label: 'Connections' };+const SETTINGS: AgentTabOption = { value: 'settings', label: 'Settings' };++/**+ * The tabs a managed agent's page offers. Connections needs the server's+ * `service_connections` flag, and goes once the server answers the agent's+ * grants with null: they are not the caller's, so there is nothing to show.+ * While the grants load it is offered, since this page lists only the+ * caller's own agents.+ */+export function agentTabs(+ serviceConnections: boolean,+ grants: ServiceGrants | null | undefined+): readonly AgentTabOption[] {+ return serviceConnections && grants !== null ? [CHATS, CONNECTIONS, SETTINGS] : [CHATS, SETTINGS];+}++/** The tab to show: the one chosen, or Chats when the chosen one is not offered. */+export function shownAgentTab(chosen: AgentTab, tabs: readonly AgentTabOption[]): AgentTab {+ return tabs.some((tab) => tab.value === chosen) ? chosen : 'chats';+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsxindex 77385b06c..80c70e57c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-page.tsx@@ -75,17 +75,30 @@ const NO_EDITS: Edits = { values: {}, form: {} };* A managed agent, on the same page a Console agent has: who it is, the machine* it runs on, how it behaves, and its sessions. Every edit on it is one set of* pending changes for the page's save bar; the server checks the definition- * against the agent's machine and refuses it whole.+ * against the agent's machine and refuses it whole. `serviceGrants` shows its+ * Service access, which a page with a Connections tab shows there instead.*/-export function ManagedAgentPage({ agent }: { agent: ManagedAgentView }) {+export function ManagedAgentPage({+ agent,+ serviceGrants,+}: {+ agent: ManagedAgentView;+ serviceGrants: boolean;+}) {return (<AgentEditsProvider>- <ManagedAgentPageContent agent={agent} />+ <ManagedAgentPageContent agent={agent} serviceGrants={serviceGrants} /></AgentEditsProvider>);}-function ManagedAgentPageContent({ agent }: { agent: ManagedAgentView }) {+function ManagedAgentPageContent({+ agent,+ serviceGrants,+}: {+ agent: ManagedAgentView;+ serviceGrants: boolean;+}) {const queryClient = useQueryClient();const showAddToRoom = useShowModal('addAgentToRoomModal');const schemaQuery = useAdvancedConfigSchema(agent.serverId);@@ -275,13 +288,15 @@ function ManagedAgentPageContent({ agent }: { agent: ManagedAgentView }) {agentName={agent.name}showName={false}/>- <ServiceGrantsRow- serverId={agent.serverId}- workspaceId={agent.workspaceId}- agentId={agent.agentId}- agentName={managedAgentLabel(agent)}- cloud={agent.machine !== null && isCloudMachine(agent.machine)}- />+ {serviceGrants && (+ <ServiceGrantsRow+ serverId={agent.serverId}+ workspaceId={agent.workspaceId}+ agentId={agent.agentId}+ agentName={managedAgentLabel(agent)}+ cloud={agent.machine !== null && isCloudMachine(agent.machine)}+ />+ )}<SettingRowtitle="Directory"info={{diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsxindex b2a29e740..c3c8b460e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx@@ -28,13 +28,14 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/lib/ui/dropdown-menu';-import { SegmentedControl } from '@renderer/lib/ui/segmented-control';-import { cn } from '@renderer/utils/utils';-import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';+import { isCloudMachine, type ManagedAgentView } from '@shared/core/managed-agents/managed-agents';import { AgentChats, openAgentChat } from './agent-chats';-import { type AgentTab, agentTabStore } from './agent-tab-store';+import { AgentConnectionsTab, useAgentServiceGrants } from './agent-connections-tab';+import { agentTabStore } from './agent-tab-store';+import { agentTabs, shownAgentTab } from './agent-tabs';import { ManagedAgentPage } from './managed-agent-page';import { managedAgentLabel } from './managed-agent-state';+import { TabbedAgentTitlebar } from './tabbed-agent-titlebar';import { MANAGED_AGENTS_KEY, useManagedAgents } from './use-managed-agents';type ManagedAgentParams = {@@ -45,10 +46,21 @@ type ManagedAgentParams = {roomId?: string;};-const TABS = [- { value: 'chats', label: 'Chats' },- { value: 'settings', label: 'Settings' },-] as const satisfies readonly { value: AgentTab; label: string }[];+/** The tabs the agent's page offers, and which of them is showing. */+function useAgentTab(serverId: string, agentId: string, agent: ManagedAgentView | null) {+ const flags = useFeatureFlags(serverId);+ const grants = useAgentServiceGrants(+ flags.service_connections,+ agent?.workspaceId ?? null,+ agentId+ );+ const tabs = agentTabs(flags.service_connections, grants.data);+ return {+ tabbed: flags.agent_chats,+ tabs,+ tab: shownAgentTab(agentTabStore.tabFor(agentId), tabs),+ };+}const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {const { params } = useParams('managedAgent');@@ -56,8 +68,7 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {const agent = agents.data?.find((listed) => listed.agentId === params.agentId) ?? null;const server = switchServersStore.servers.find((s) => s.id === params.serverId) ?? null;const label = agent ? managedAgentLabel(agent) : params.name;- const tabbed = useFeatureFlags(params.serverId).agent_chats;- const tab = agentTabStore.tabFor(params.agentId);+ const { tabbed, tabs, tab } = useAgentTab(params.serverId, params.agentId, agent);const chat = tabbed && agent && tab === 'chats' ? openAgentChat(agent, params.roomId) : null;const activities = useAgentActivities(params.serverId, chat ?? undefined);const breadcrumb = (@@ -93,24 +104,11 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {/>);return (- <Titlebar- className="border-b border-border"- leftClassName={cn(- 'w-[300px] shrink-0 self-stretch',- tab === 'chats' && 'border-r border-border'- )}- leftSlot={- <div className="flex min-w-0 items-center gap-3">- {breadcrumb}- <SegmentedControl- value={tab}- onChange={(next) => agentTabStore.setTab(params.agentId, next)}- options={TABS}- ariaLabel="Agent view"- />- </div>- }- rightClassName="min-w-0 flex-1 justify-between gap-3 pl-4"+ <TabbedAgentTitlebar+ breadcrumb={breadcrumb}+ tab={tab}+ tabs={tabs}+ onTab={(next) => agentTabStore.setTab(params.agentId, next)}rightSlot={<><span className="truncate text-sm font-medium">{chat?.name}</span>@@ -228,7 +226,7 @@ const ManagedAgentPanel = observer(function ManagedAgentPanel() {const { params } = useParams('managedAgent');const agents = useManagedAgents(params.serverId);const agent = agents.data?.find((listed) => listed.agentId === params.agentId);- const tabbed = useFeatureFlags(params.serverId).agent_chats;+ const { tabbed, tab } = useAgentTab(params.serverId, params.agentId, agent ?? null);if (agents.error)return (<ServerPage width={900} title={params.name} description="">@@ -259,10 +257,19 @@ const ManagedAgentPanel = observer(function ManagedAgentPanel() {</p></ServerPage>);- if (!tabbed) return <ManagedAgentPage key={agent.agentId} agent={agent} />;- const tab = agentTabStore.tabFor(agent.agentId);+ if (!tabbed) return <ManagedAgentPage key={agent.agentId} agent={agent} serviceGrants />;if (tab === 'chats') return <AgentChats key={agent.agentId} agent={agent} />;- return <ManagedAgentPage key={agent.agentId} agent={agent} />;+ if (tab === 'connections')+ return (+ <AgentConnectionsTab+ key={agent.agentId}+ workspaceId={agent.workspaceId}+ agentId={agent.agentId}+ agentName={managedAgentLabel(agent)}+ cloud={agent.machine !== null && isCloudMachine(agent.machine)}+ />+ );+ return <ManagedAgentPage key={agent.agentId} agent={agent} serviceGrants={false} />;});export const managedAgentView = {diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsxnew file mode 100644index 000000000..7658d3edb--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/tabbed-agent-titlebar.tsx@@ -0,0 +1,50 @@+import type { ReactNode } from 'react';+import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import { cn } from '@renderer/utils/utils';+import type { AgentTab } from './agent-tab-store';+import type { AgentTabOption } from './agent-tabs';++/**+ * A tabbed agent's titlebar: its crumb and tabs on the left, `rightSlot` on+ * the right. On Chats the left side is as wide as the chat list below it, so+ * the two line up; on the other tabs it takes the width it needs. Either way+ * the tabs keep their width and a long name is what gives way.+ */+export function TabbedAgentTitlebar({+ breadcrumb,+ tab,+ tabs,+ onTab,+ rightSlot,+}: {+ breadcrumb: ReactNode;+ tab: AgentTab;+ tabs: readonly AgentTabOption[];+ onTab: (tab: AgentTab) => void;+ rightSlot: ReactNode;+}) {+ return (+ <Titlebar+ className="border-b border-border"+ leftClassName={cn(+ 'min-w-0 self-stretch',+ tab === 'chats' && 'w-[300px] shrink-0 border-r border-border'+ )}+ leftSlot={+ <div className="flex min-w-0 items-center gap-3">+ <div className="min-w-0 truncate">{breadcrumb}</div>+ <SegmentedControl+ className="shrink-0"+ value={tab}+ onChange={onTab}+ options={tabs}+ ariaLabel="Agent view"+ />+ </div>+ }+ rightClassName="min-w-0 flex-1 justify-between gap-3 pl-4"+ rightSlot={rightSlot}+ />+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.tsnew file mode 100644index 000000000..0b00d629b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts@@ -0,0 +1,33 @@+export type WorkspaceNavView =+ | 'server'+ | 'serverAgents'+ | 'serverRooms'+ | 'connectors'+ | 'templates'+ | 'admin'+ | 'managedServer';++/**+ * The active server's destinations, in order. Connectors follows Your Rooms+ * only where the server has service connections on: with them off its routes+ * are not mounted, so there is nothing to show. Server is only for a server+ * this Console runs: the others are run by someone else, and there is nothing+ * here to start, stop or update. Admin is only for whoever administers the+ * workspace (the server's operator among them), and, holding only connector+ * settings, only where service connections are on.+ */+export function workspaceNavViews(server: {+ managed: boolean;+ serviceConnections: boolean;+ administers: boolean;+}): WorkspaceNavView[] {+ return [+ 'server',+ 'serverAgents',+ 'serverRooms',+ ...(server.serviceConnections ? (['connectors'] as const) : []),+ 'templates',+ ...(server.serviceConnections && server.administers ? (['admin'] as const) : []),+ ...(server.managed ? (['managedServer'] as const) : []),+ ];+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsxindex d45cc5f0e..881dff55b 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx@@ -1,14 +1,26 @@-import { Bot, DoorOpen, FileText, House, Server } from 'lucide-react';+import {+ Bot,+ DoorOpen,+ FileText,+ House,+ type LucideIcon,+ Plug,+ Server,+ ShieldCheck,+} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useRoomHealth } from '@renderer/features/switch-rooms/connection-health';import { ManagedServerDot } from '@renderer/features/switch-servers/managed-server-dot';import { FROZEN, isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';+import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { isCurrentView, useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';import { cn } from '@renderer/utils/utils';import { connectionNeedsAttention } from '@shared/core/switch-rooms/connection-health';import { SidebarMenu, SidebarMenuButton } from './sidebar-primitives';+import { type WorkspaceNavView, workspaceNavViews } from './workspace-nav-views';/*** The active server's own destinations, under the workspace switcher.@@ -23,62 +35,67 @@ export const WorkspaceNav = observer(function WorkspaceNav() {const { params: homeParams } = useParams('server');const { params: agentsParams } = useParams('serverAgents');const { params: roomsParams } = useParams('serverRooms');+ const { params: connectorsParams } = useParams('connectors');const { params: templatesParams } = useParams('templates');+ const { params: adminParams } = useParams('admin');const { params: managedServerParams } = useParams('managedServer');const active = switchServersStore.activeServer;const health = useRoomHealth(active?.id ?? null);+ const serviceConnections = useFeatureFlags(active?.id ?? null).service_connections;const warningCount =health.data?.agents.filter((agent) => connectionNeedsAttention(agent.state)).length ?? 0;if (!active) return null;// While the server can't answer, only the way to it stays live.const frozen = isFrozenServer(active);- const destinations = [- { view: 'server', icon: House, label: 'Home', params: homeParams },- { view: 'serverAgents', icon: Bot, label: 'Your Agents', params: agentsParams },- { view: 'serverRooms', icon: DoorOpen, label: 'Your Rooms', params: roomsParams },- { view: 'templates', icon: FileText, label: 'Templates', params: templatesParams },- // Only for a server this Console runs: the others are run by someone else,- // and there is nothing here to start, stop or update.- ...(active.managed- ? [- {- view: 'managedServer',- icon: Server,- label: 'Server',- params: managedServerParams,- } as const,- ]- : []),- ] as const;+ const destinations: Record<+ WorkspaceNavView,+ { icon: LucideIcon; label: string; params: { serverId?: string } | undefined }+ > = {+ server: { icon: House, label: 'Home', params: homeParams },+ serverAgents: { icon: Bot, label: 'Your Agents', params: agentsParams },+ serverRooms: { icon: DoorOpen, label: 'Your Rooms', params: roomsParams },+ connectors: { icon: Plug, label: 'Connectors', params: connectorsParams },+ templates: { icon: FileText, label: 'Templates', params: templatesParams },+ admin: { icon: ShieldCheck, label: 'Admin', params: adminParams },+ managedServer: { icon: Server, label: 'Server', params: managedServerParams },+ };+ const shown = workspaceNavViews({+ managed: active.managed,+ serviceConnections,+ administers: administersWorkspaceInScope(active.id),+ });return (<SidebarMenu className="flex flex-col gap-[2px] px-2 pt-2">- {destinations.map(({ view, icon: Icon, label, params }) => (- <SidebarMenuButton- key={view}- isActive={isCurrentView(currentView, view) && params?.serverId === active.id}- onClick={() => navigate(view, { serverId: active.id })}- className={cn(frozen && view !== 'managedServer' && FROZEN)}- >- <Icon className="size-[15px] shrink-0" />- {label}- {view === 'managedServer' && (- <span className="ml-auto flex items-center pr-0.5">- <ManagedServerDot server={active} size={7} />- </span>- )}- {view === 'serverAgents' && (warningCount > 0 || health.isError) && (- <span- className="ml-auto text-xs text-foreground-warning"- title="Agent room connections need attention"- aria-label="Agent room connections need attention"- >- {health.isError ? '!' : warningCount}- </span>- )}- </SidebarMenuButton>- ))}+ {shown.map((view) => {+ const { icon: Icon, label, params } = destinations[view];+ return (+ <SidebarMenuButton+ key={view}+ isActive={isCurrentView(currentView, view) && params?.serverId === active.id}+ onClick={() => navigate(view, { serverId: active.id })}+ className={cn(frozen && view !== 'managedServer' && FROZEN)}+ >+ <Icon className="size-[15px] shrink-0" />+ {label}+ {view === 'managedServer' && (+ <span className="ml-auto flex items-center pr-0.5">+ <ManagedServerDot server={active} size={7} />+ </span>+ )}+ {view === 'serverAgents' && (warningCount > 0 || health.isError) && (+ <span+ className="ml-auto text-xs text-foreground-warning"+ title="Agent room connections need attention"+ aria-label="Agent room connections need attention"+ >+ {health.isError ? '!' : warningCount}+ </span>+ )}+ </SidebarMenuButton>+ );+ })}</SidebarMenu>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectionsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectionsModal.tsxdeleted file mode 100644index c88a31232..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectionsModal.tsx+++ /dev/null@@ -1,43 +0,0 @@-import { useQueryClient } from '@tanstack/react-query';-import { useState } from 'react';-import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';-import { Button } from '@renderer/lib/ui/button';-import { DialogFooter } from '@renderer/lib/ui/dialog';-import { ConnectionsGrid, useConnectionCatalog } from './connections-step';-import { ManagedGitHubStep } from './managed-github-step';-import { ServiceConnectStep } from './service-connect-step';-import { ServiceKeyStep } from './service-key-step';--/** A server's connection catalog, opened from its Your Agents page. */-export function ConnectionsModal({ serverId, onClose }: { serverId: string } & BaseModalProps) {- const queryClient = useQueryClient();- const catalog = useConnectionCatalog(serverId);- const [query, setQuery] = useState('');- const [open, setOpen] = useState<string | null>(null);- const back = () => {- setOpen(null);- void catalog.reload();- // Agents' service access reads the connections by workspace.- void queryClient.invalidateQueries({ queryKey: ['workspace-github'] });- void queryClient.invalidateQueries({ queryKey: ['workspace-service-connections'] });- };-- if (open === 'github') return <ManagedGitHubStep serverId={serverId} onBack={back} />;- const opened = catalog.connections?.find((connection) => connection.slug === open);- if (opened?.key)- return (- <ServiceKeyStep serverId={serverId} connection={opened} form={opened.key} onBack={back} />- );- if (opened) return <ServiceConnectStep serverId={serverId} connection={opened} onBack={back} />;-- return (- <>- <ConnectionsGrid catalog={catalog} query={query} onQueryChange={setQuery} onOpen={setOpen} />- <DialogFooter>- <Button variant="outline" onClick={onClose}>- Close- </Button>- </DialogFooter>- </>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connection-icon.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connection-icon.tsxindex fc7a7a136..7fe31ea95 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connection-icon.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connection-icon.tsx@@ -44,17 +44,33 @@ export function hasConnectionIcon(slug: string): boolean {return svgBySlug.has(slug);}+const TILE_SIZE = {+ md: { tile: 'size-9 rounded-md text-sm', mark: 'size-6' },+ lg: { tile: 'size-11 rounded-lg text-base', mark: 'size-7' },+ xl: { tile: 'size-16 rounded-xl text-2xl', mark: 'size-10' },+} as const;+/** A connection's brand logo on a neutral tile, or its monogram for a slug this build has no logo for. */-export function ConnectionIcon({ slug, name }: { slug: string; name: string }) {+export function ConnectionIcon({+ slug,+ name,+ size = 'md',+}: {+ slug: string;+ name: string;+ /** The tile's size: the catalog's lists use `md`. */+ size?: keyof typeof TILE_SIZE;+}) {const svg = svgBySlug.get(slug);+ const { tile, mark } = TILE_SIZE[size];return (<spanaria-hidden- className="flex size-9 shrink-0 items-center justify-center rounded-md bg-background-2 text-sm font-semibold text-foreground-muted"+ className={`flex shrink-0 items-center justify-center bg-background-2 font-semibold text-foreground-muted ${tile}`}>{svg ? (<span- className={`size-6 ${MARK_COLOR[slug] ?? ''}`}+ className={`${mark} ${MARK_COLOR[slug] ?? ''}`}// Bundled brand assets, not user input.dangerouslySetInnerHTML={{ __html: svg.replace('<svg ', '<svg class="size-full" ') }}/>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-filter.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-filter.test.tsindex 522a3bf63..c2fd86de1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-filter.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-filter.test.ts@@ -18,6 +18,8 @@ function entry(name: string, category: string): ConnectionCatalogEntry {loopback_ports: null,key: null,external_identity: null,+ consent: null,+ workspace_enabled: null,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsxindex c8093efdc..c5ea21e1c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/connections-step.tsx@@ -15,6 +15,7 @@ import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connectimport { ConnectionIcon } from './connection-icon';import { filterConnections } from './connections-filter';import { ManagedGitHubStep } from './managed-github-step';+import { serverServiceCalls } from './service-calls';import { ServiceConnectStep } from './service-connect-step';import { ServiceKeyStep } from './service-key-step';@@ -70,7 +71,7 @@ export function ConnectionsGrid({<DialogContentArea className="space-y-4 pt-0"><p className="text-sm text-foreground-muted">Connect the services your agents can work with. Each agent uses a service only once you- grant it, from the agent's settings.+ grant it, from the agent's Connections tab.</p><SearchInputaria-label="Search connections"@@ -181,9 +182,18 @@ export function ConnectionsStep({const opened = catalog.connections?.find((connection) => connection.slug === open);if (opened?.key)return (- <ServiceKeyStep serverId={serverId} connection={opened} form={opened.key} onBack={back} />+ <ServiceKeyStep+ calls={serverServiceCalls(serverId)}+ connection={opened}+ form={opened.key}+ replacing={false}+ onBack={back}+ />+ );+ if (opened)+ return (+ <ServiceConnectStep calls={serverServiceCalls(serverId)} connection={opened} onBack={back} />);- if (opened) return <ServiceConnectStep serverId={serverId} connection={opened} onBack={back} />;const githubConnected = catalog.connections?.some((connection) => connection.slug === 'github' && connection.status === 'connected'diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-github-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-github-step.tsxindex 53f37a7e7..b892fbdd8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-github-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-github-step.tsx@@ -11,7 +11,8 @@ import {DialogTitle,} from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';-import type { GitHubConnection, GitHubFlow } from '@shared/core/switch-servers/github-connection';+import { cn } from '@renderer/utils/utils';+import type { GitHubConnection } from '@shared/core/switch-servers/github-connection';const SSO_HIDDEN ='An organization’s single sign-on hides its installation of the app from this GitHub connection. Disconnect and connect GitHub again, and authorize the organization when GitHub asks.';@@ -30,6 +31,8 @@ export function ManagedGitHubStep({onBack,onSkip,onContinue,+ onConnected,+ onDone,}: {serverId: string;onBack: () => void;@@ -37,10 +40,16 @@ export function ManagedGitHubStep({onSkip?: () => void;/** Offers Continue to agent once repositories are accessible. */onContinue?: () => void;+ /** Runs as the sign-in connects, with the warning Switch gave. */+ onConnected?: (warning: string | null) => void;+ /**+ * Offers Done once connected, in place of Back and Disconnect, and Cancel+ * before: for a page that has those of its own, as a connector's does.+ */+ onDone?: () => void;}) {const [connection, setConnection] = useState<GitHubConnection | null>(null);const [flowId, setFlowId] = useState<string | null>(null);- const [flow, setFlow] = useState<GitHubFlow | null>(null);const [busy, setBusy] = useState(false);const [warning, setWarning] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);@@ -60,6 +69,7 @@ export function ManagedGitHubStep({useEffect(() => {void load();}, [load]);+ // The sign-in is over once the server has kept the connection, or failed it.useEffect(() => {if (!flowId) return;let alive = true;@@ -68,14 +78,17 @@ export function ManagedGitHubStep({try {const result = await rpc.switchServers.getGitHubFlow(serverId, flowId);if (!alive) return;- setFlow(result);if (result.status === 'failed')- setError('GitHub authorization failed. Cancel and try again.');- else if (result.status !== 'ready') timer = setTimeout(() => void poll(), 2000);+ setError(result.error ?? 'GitHub authorization failed. Cancel and try again.');+ else if (result.status === 'connected') {+ setFlowId(null);+ setWarning(result.warning);+ await load();+ onConnected?.(result.warning);+ } else timer = setTimeout(() => void poll(), 2000);} catch (cause) {if (alive) {setFlowId(null);- setFlow(null);setError(failureText(cause, 'Could not check GitHub authorization.'));}}@@ -85,7 +98,7 @@ export function ManagedGitHubStep({alive = false;clearTimeout(timer);};- }, [serverId, flowId]);+ }, [serverId, flowId, load, onConnected]);useEffect(() => {if (!watching) return;let alive = true;@@ -144,28 +157,14 @@ export function ManagedGitHubStep({const connected = connection?.status === 'connected';return (<>- <DialogHeader showCloseButton={!busy && !flowId}>+ <DialogHeader showCloseButton={!flowId}><DialogTitle>{connected && !flowId ? 'GitHub connected' : 'Connect GitHub'}</DialogTitle></DialogHeader><DialogContentArea className="space-y-5 pt-0">{flowId ? (- <div className="space-y-3">- {flow?.status === 'ready' ? (- <>- <p className="flex items-center gap-2 text-sm">- <CircleCheck className="size-5 text-foreground-success" />- Authorized as <strong>{flow.login}</strong>- </p>- <p className="text-sm text-foreground-muted">- Confirm this is the GitHub account you want to connect to Switch.- </p>- </>- ) : (- <p className="flex items-center gap-2 text-sm">- <Spinner /> Complete authorization in your browser, then return here.- </p>- )}- </div>+ <p className="flex items-center gap-2 text-sm">+ <Spinner /> Complete authorization in your browser, then return here.+ </p>) : connected ? (<><p className="flex items-center gap-2 text-sm">@@ -222,10 +221,12 @@ export function ManagedGitHubStep({<Spinner /> Choose repositories in GitHub. Access will update here automatically.</p>)}- <p className="text-xs text-foreground-muted">- Disconnecting removes credentials saved by Switch. You can also revoke authorization- or uninstall the app in GitHub settings. No cloud agent has been started.- </p>+ {!onDone && (+ <p className="text-xs text-foreground-muted">+ Disconnecting removes credentials saved by Switch. You can also revoke authorization+ or uninstall the app in GitHub settings. No cloud agent has been started.+ </p>+ )}</>) : (<>@@ -267,11 +268,13 @@ export function ManagedGitHubStep({</div></>)}- {busy && (- <p className="flex items-center gap-2 text-sm">- <Spinner /> Checking GitHub…- </p>- )}+ <p+ role="status"+ aria-hidden={!busy}+ className={cn('flex items-center gap-2 text-sm', !busy && 'invisible')}+ >+ <Spinner /> Checking GitHub…+ </p>{warning && (<p role="status" className="rounded-md border p-3 text-sm text-foreground-muted">{warning}@@ -290,46 +293,28 @@ export function ManagedGitHubStep({</DialogContentArea><DialogFooter>{flowId ? (- <>- <Button- variant="outline"- disabled={busy}- onClick={() =>- void act(async () => {- await rpc.switchServers.cancelGitHubConnection(serverId, flowId);- setFlowId(null);- setFlow(null);- })- }- >- Cancel- </Button>- {flow?.status === 'ready' && (- <Button- disabled={busy}- onClick={() =>- void act(async () => {- const result = await rpc.switchServers.confirmGitHubConnection(- serverId,- flowId- );- setFlowId(null);- setFlow(null);- setWarning(result.warning ?? null);- await load();- })- }- >- Connect {flow.login}- </Button>- )}- </>+ <Button+ variant="outline"+ disabled={busy}+ onClick={() =>+ void act(async () => {+ await rpc.switchServers.cancelGitHubConnection(serverId, flowId);+ setFlowId(null);+ })+ }+ >+ Cancel+ </Button>+ ) : onDone && connected && !error ? (+ <Button onClick={onDone} disabled={busy}>+ Done+ </Button>) : (<><Button variant="outline" onClick={onBack} disabled={busy}>- Back+ {onDone ? 'Cancel' : 'Back'}</Button>- {connected && (+ {connected && !onDone && (<Buttonvariant="ghost"disabled={busy}@@ -367,7 +352,6 @@ export function ManagedGitHubStep({disabled={busy}onClick={() =>void act(async () => {- setFlow(null);setFlowId(await rpc.switchServers.startGitHubConnection(serverId));})}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsxindex c0f31e88f..4acb56cfc 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx@@ -1,4 +1,4 @@-import { Bot, ExternalLink, MoreVertical, Plug, Plus, RotateCcw, Trash2 } from 'lucide-react';+import { Bot, ExternalLink, MoreVertical, Plus, RotateCcw, Trash2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';@@ -21,7 +21,6 @@ import { AgentAvatar } from '@renderer/lib/components/agent-avatar';import { failureText } from '@renderer/lib/errors/describe-failure';import { resetAgentErrorText } from '@renderer/lib/errors/reset-agent-error';import { useToast } from '@renderer/lib/hooks/use-toast';-import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';@@ -55,7 +54,6 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {const serverId = useServerId();const server = switchServersStore.servers.find((s) => s.id === serverId);const showAddAgentModal = useShowModal('addAgentModal');- const showConnectionsModal = useShowModal('connectionsModal');// The sidebar reads the same two things, but this page must not be right only// when the sidebar happened to be open first.@@ -63,8 +61,6 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {void refreshSidebarRoomState(false);}, [serverId]);- // Connections are offered where the server has service connections on.- const serviceConnections = useFeatureFlags(serverId).service_connections;const machines = useCloudMachines(serverId);const managed = useManagedAgents(serverId);const agents = withoutManaged(agentsStore.agentsOnServer(serverId), managed.data);@@ -74,14 +70,6 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {width={880}title="Your Agents"description={`Agents on ${server?.name ?? 'this server'}. Add one, set how it is addressed, and start sessions.`}- action={- serviceConnections && (- <Button variant="outline" size="sm" onClick={() => showConnectionsModal({ serverId })}>- <Plug className="size-4" />- Connections- </Button>- )- }>{machines.data?.filter((machine) => machine.state !== 'deleted')diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-calls.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-calls.tsnew file mode 100644index 000000000..05dd9d396--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-calls.ts@@ -0,0 +1,42 @@+import { rpc } from '@renderer/lib/ipc';+import type {+ ServiceFlow,+ ServiceKeyConnected,+} from '@shared/core/switch-servers/service-connection';++/**+ * What the connect steps ask Switch, bound to where they act: the server's own+ * workspace for the add-server onboarding, or the workspace a Connectors page+ * shows, so a page for one workspace never connects or disconnects in another.+ */+export type ServiceCalls = {+ startSignIn: (service: string) => Promise<string>;+ getSignIn: (service: string, flowId: string) => Promise<ServiceFlow>;+ cancelSignIn: (service: string, flowId: string) => Promise<void>;+ connectWithKey: (service: string, fields: Record<string, string>) => Promise<ServiceKeyConnected>;+ disconnect: (service: string) => Promise<{ warning: string | null }>;+};++export function serverServiceCalls(serverId: string): ServiceCalls {+ return {+ startSignIn: (service) => rpc.switchServers.startServiceConnection(serverId, service),+ getSignIn: (service, flowId) => rpc.switchServers.getServiceFlow(serverId, service, flowId),+ cancelSignIn: (service, flowId) =>+ rpc.switchServers.cancelServiceConnection(serverId, service, flowId),+ connectWithKey: (service, fields) =>+ rpc.switchServers.connectServiceWithKey(serverId, service, fields),+ disconnect: (service) => rpc.switchServers.disconnectService(serverId, service),+ };+}++export function workspaceServiceCalls(workspaceId: string): ServiceCalls {+ return {+ startSignIn: (service) => rpc.workspaces.startServiceConnection({ workspaceId, service }),+ getSignIn: (service, flowId) => rpc.workspaces.getServiceFlow({ workspaceId, service, flowId }),+ cancelSignIn: (service, flowId) =>+ rpc.workspaces.cancelServiceConnection({ workspaceId, service, flowId }),+ connectWithKey: (service, fields) =>+ rpc.workspaces.connectServiceWithKey({ workspaceId, service, fields }),+ disconnect: (service) => rpc.workspaces.disconnectService({ workspaceId, service }),+ };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-connect-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-connect-step.tsxindex d64c3108e..97dbefcee 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-connect-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-connect-step.tsx@@ -1,7 +1,11 @@-import { CircleCheck, ExternalLink } from 'lucide-react';-import { useEffect, useState } from 'react';+import { ExternalLink } from 'lucide-react';+import { useEffect, useReducer, useRef } from 'react';+import {+ canCloseConnectFlow,+ connectFlowReducer,+ initialConnectFlow,+} from '@renderer/features/connectors/connect-flow';import { failureText } from '@renderer/lib/errors/describe-failure';-import { rpc } from '@renderer/lib/ipc';import { useCloseGuard } from '@renderer/lib/modal/use-close-guard';import { Button } from '@renderer/lib/ui/button';import {@@ -12,50 +16,65 @@ import {} from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';-import type { ServiceFlow } from '@shared/core/switch-servers/service-connection';+import type { ServiceCalls } from './service-calls';/*** Connecting a service through Switch's generic sign-in: the browser signs in- * at the vendor, this Console takes the result back, and the person confirms- * the account before Switch keeps it. GitHub has its own step.+ * at the vendor, this Console takes the result back, and Switch keeps the+ * account as soon as it has it. The dialog follows the sign-in and shows the+ * account connected, or why it was not. GitHub has its own step.*/export function ServiceConnectStep({- serverId,+ calls,connection,onBack,+ onConnected,}: {- serverId: string;+ calls: ServiceCalls;connection: ConnectionCatalogEntry;onBack: () => void;+ /** Moves on once the account is connected, with the warning Switch gave. */+ onConnected?: (warning: string | null) => void;}) {const service = connection.slug;- const [connected, setConnected] = useState(connection.status === 'connected');- const [flowId, setFlowId] = useState<string | null>(null);- const [flow, setFlow] = useState<ServiceFlow | null>(null);- const [busy, setBusy] = useState(false);- const [warning, setWarning] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);- useCloseGuard(busy || flowId !== null);+ const [state, dispatch] = useReducer(+ connectFlowReducer,+ connection.status === 'connected',+ initialConnectFlow+ );+ const { connected, flowId, flow, busy, warning, error } = state;+ const closable = canCloseConnectFlow(state);+ useCloseGuard(!closable);+ // Callers build their calls as they render; polling follows the flow, not them.+ const callsRef = useRef(calls);+ callsRef.current = calls;+ const onConnectedRef = useRef(onConnected);+ onConnectedRef.current = onConnected;useEffect(() => {if (!flowId) return;let alive = true;let timer: ReturnType<typeof setTimeout>;const poll = async () => {try {- const result = await rpc.switchServers.getServiceFlow(serverId, service, flowId);+ const result = await callsRef.current.getSignIn(service, flowId);if (!alive) return;- setFlow(result);- if (result.status === 'failed')- setError(- result.error ?? `Signing in to ${connection.name} failed. Cancel and try again.`- );- else if (result.status !== 'ready') timer = setTimeout(() => void poll(), 2000);- } catch (cause) {- if (alive) {- setFlowId(null);- setFlow(null);- setError(failureText(cause, `Could not check the ${connection.name} sign-in.`));+ if (result.status === 'connected') {+ onConnectedRef.current?.(result.warning);+ dispatch({ type: 'connected', warning: result.warning });+ return;}+ dispatch({+ type: 'polled',+ flow: result,+ failure: `Signing in to ${connection.name} failed. Cancel and try again.`,+ });+ if (result.status !== 'failed') timer = setTimeout(() => void poll(), 2000);+ } catch (cause) {+ if (alive)+ dispatch({+ type: 'poll_failed',+ error: failureText(cause, `Could not check the ${connection.name} sign-in.`),+ });}};void poll();@@ -63,44 +82,54 @@ export function ServiceConnectStep({alive = false;clearTimeout(timer);};- }, [serverId, service, flowId, connection.name]);- const act = async (action: () => Promise<void>) => {- setBusy(true);- setError(null);+ }, [service, flowId, connection.name]);+ const fallback = `Could not update the ${connection.name} connection.`;+ const start = async () => {+ dispatch({ type: 'act' });try {- await action();+ dispatch({+ type: 'started',+ flowId: await calls.startSignIn(service),+ });} catch (cause) {- setError(failureText(cause, `Could not update the ${connection.name} connection.`));- } finally {- setBusy(false);+ dispatch({ type: 'failed', error: failureText(cause, fallback) });+ }+ };+ const cancel = async (id: string) => {+ dispatch({ type: 'act' });+ try {+ await calls.cancelSignIn(service, id);+ dispatch({ type: 'cancelled' });+ } catch (cause) {+ dispatch({ type: 'cancel_failed', cause, error: failureText(cause, fallback) });+ }+ };+ const disconnect = async () => {+ dispatch({ type: 'act' });+ try {+ const result = await calls.disconnect(service);+ dispatch({ type: 'disconnected', warning: result.warning });+ } catch (cause) {+ dispatch({ type: 'failed', error: failureText(cause, fallback) });}};const needsReconnect =connection.status === 'needs_reauthorization' || connection.status === 'error';return (<>- <DialogHeader showCloseButton={!busy && !flowId}>+ <DialogHeader showCloseButton={closable}><DialogTitle>{connected && !flowId ? `${connection.name} connected` : `Connect ${connection.name}`}</DialogTitle></DialogHeader><DialogContentArea className="space-y-4 pt-0">{flowId ? (- flow?.status === 'ready' ? (- <>- <p className="flex items-center gap-2 text-sm">- <CircleCheck className="size-5 text-foreground-success" />- Signed in as <strong>{flow.account}</strong>- </p>- <p className="text-sm text-foreground-muted">- Confirm this is the {connection.name} account you want to connect to Switch.- </p>- </>- ) : (- <p className="flex items-center gap-2 text-sm">- <Spinner /> Finish signing in in your browser, then return here.- </p>- )+ <p className="flex items-center gap-2 text-sm">+ <Spinner />+ {flow?.status === 'checking'+ ? `Connecting ${connection.name}…`+ : 'Finish signing in in your browser, then return here.'}+ </p>) : (<><p className="text-sm text-foreground-muted">{connection.description}</p>@@ -138,71 +167,21 @@ export function ServiceConnectStep({</DialogContentArea><DialogFooter>{flowId ? (- <>- <Button- variant="outline"- disabled={busy}- onClick={() =>- void act(async () => {- await rpc.switchServers.cancelServiceConnection(serverId, service, flowId);- setFlowId(null);- setFlow(null);- })- }- >- Cancel- </Button>- {flow?.status === 'ready' && (- <Button- disabled={busy}- onClick={() =>- void act(async () => {- const result = await rpc.switchServers.confirmServiceConnection(- serverId,- service,- flowId- );- setFlowId(null);- setFlow(null);- setWarning(result.warning);- setConnected(true);- })- }- >- Connect {flow.account}- </Button>- )}- </>+ <Button variant="outline" disabled={busy} onClick={() => void cancel(flowId)}>+ Cancel+ </Button>) : (<><Button variant="outline" onClick={onBack} disabled={busy}>Back</Button>{connected && (- <Button- variant="ghost"- disabled={busy}- onClick={() =>- void act(async () => {- const result = await rpc.switchServers.disconnectService(serverId, service);- setWarning(result.warning);- setConnected(false);- })- }- >+ <Button variant="ghost" disabled={busy} onClick={() => void disconnect()}>Disconnect</Button>)}{(!connected || error) && (- <Button- disabled={busy || !connection.connectable}- onClick={() =>- void act(async () => {- setFlow(null);- setFlowId(await rpc.switchServers.startServiceConnection(serverId, service));- })- }- >+ <Button disabled={busy || !connection.connectable} onClick={() => void start()}>Connect {connection.name} <ExternalLink className="size-4" /></Button>)}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-key-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-key-step.tsxindex 2489a6208..52b2495af 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-key-step.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/service-key-step.tsx@@ -1,7 +1,6 @@import { CircleCheck, ExternalLink } from 'lucide-react';import { useState } from 'react';import { failureText } from '@renderer/lib/errors/describe-failure';-import { rpc } from '@renderer/lib/ipc';import { useCloseGuard } from '@renderer/lib/modal/use-close-guard';import { openExternalUrl } from '@renderer/lib/open-external';import { Button } from '@renderer/lib/ui/button';@@ -23,35 +22,45 @@ import type {ConnectionCatalogEntry,ServiceKeyForm,} from '@shared/core/switch-servers/connection-catalog';+import type { ServiceCalls } from './service-calls';/*** Connecting a service by pasting a key: a form of the fields the catalog* names, the keys typed into password inputs and anything else picked from its* choices. Switch checks the key with the vendor before keeping it, and never* sends it back, so a key typed here is cleared once it is submitted.+ *+ * Opened `replacing` a connected key, it is that one action: it opens on the+ * form, and once the new key is kept it is done. The server replaces the key+ * in place, so every agent that had the service keeps it.*/export function ServiceKeyStep({- serverId,+ calls,connection,form,+ replacing,onBack,+ onConnected,}: {- serverId: string;+ calls: ServiceCalls;connection: ConnectionCatalogEntry;form: ServiceKeyForm;+ replacing: boolean;onBack: () => void;+ /** Moves on once the key is connected, with the warning Switch gave. */+ onConnected?: (warning: string | null) => void;}) {const service = connection.slug;const name = connection.name;const [connected, setConnected] = useState(connection.status === 'connected');const [identity, setIdentity] = useState(connection.external_identity);- const [replacing, setReplacing] = useState(false);+ const [changingKey, setChangingKey] = useState(replacing);const [values, setValues] = useState<Record<string, string>>({});const [busy, setBusy] = useState(false);const [warning, setWarning] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);useCloseGuard(busy);- const editing = !connected || replacing;+ const editing = !connected || changingKey;const complete = form.fields.every((field) => (values[field.name] ?? '').trim() !== '');const clearSecrets = () =>setValues((current) =>@@ -70,11 +79,12 @@ export function ServiceKeyStep({);clearSecrets();try {- const result = await rpc.switchServers.connectServiceWithKey(serverId, service, fields);+ const result = await calls.connectWithKey(service, fields);setIdentity(result.external_identity);setWarning(result.warning);setConnected(true);- setReplacing(false);+ setChangingKey(false);+ onConnected?.(result.warning);} catch (cause) {setError(failureText(cause, `Could not connect ${name}.`));} finally {@@ -85,11 +95,11 @@ export function ServiceKeyStep({setBusy(true);setError(null);try {- const result = await rpc.switchServers.disconnectService(serverId, service);+ const result = await calls.disconnect(service);setWarning(result.warning);setConnected(false);setIdentity(null);- setReplacing(false);+ setChangingKey(false);} catch (cause) {setError(failureText(cause, `Could not disconnect ${name}.`));} finally {@@ -99,7 +109,13 @@ export function ServiceKeyStep({return (<><DialogHeader showCloseButton={!busy}>- <DialogTitle>{connected ? `${name} connected` : `Connect ${name}`}</DialogTitle>+ <DialogTitle>+ {replacing && changingKey+ ? `Replace the ${name} key`+ : connected+ ? `${name} connected`+ : `Connect ${name}`}+ </DialogTitle></DialogHeader><DialogContentArea className="space-y-4 pt-0"><p className="text-sm text-foreground-muted">{connection.description}</p>@@ -191,29 +207,49 @@ export function ServiceKeyStep({</p>)}</DialogContentArea>- <DialogFooter>- <Button variant="outline" onClick={onBack} disabled={busy}>- Back- </Button>- {connected && (- <Button variant="ghost" disabled={busy} onClick={() => void disconnect()}>- Disconnect- </Button>- )}- {connected && !replacing && (- <Button variant="outline" disabled={busy} onClick={() => setReplacing(true)}>- Replace key- </Button>- )}- {editing && (- <Button- disabled={busy || !complete || !connection.connectable}- onClick={() => void submit()}- >- Connect {name}+ {replacing ? (+ <DialogFooter>+ {changingKey ? (+ <>+ <Button variant="outline" onClick={onBack} disabled={busy}>+ Cancel+ </Button>+ <Button+ disabled={busy || !complete || !connection.connectable}+ onClick={() => void submit()}+ >+ Replace key+ </Button>+ </>+ ) : (+ <Button onClick={onBack}>Done</Button>+ )}+ </DialogFooter>+ ) : (+ <DialogFooter>+ <Button variant="outline" onClick={onBack} disabled={busy}>+ Back</Button>- )}- </DialogFooter>+ {connected && (+ <Button variant="ghost" disabled={busy} onClick={() => void disconnect()}>+ Disconnect+ </Button>+ )}+ {connected && !changingKey && (+ <Button variant="outline" disabled={busy} onClick={() => setChangingKey(true)}>+ Replace key+ </Button>+ )}+ {editing && (+ <Button+ disabled={busy || !complete || !connection.connectable}+ onClick={() => void submit()}+ >+ Connect {name}+ </Button>+ )}+ </DialogFooter>+ )}</>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.tsindex 561715894..0d7e17077 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts@@ -2,13 +2,21 @@ import { workspacesStore } from '@renderer/features/workspaces/workspaces-store'import { administersWorkspace } from '@shared/core/workspaces/workspaces';import { switchServersStore } from './switch-servers-store';+/**+ * Whether the signed-in account is the operator running `serverId`: what it+ * sets is the whole server's, not one workspace's.+ */+export function operatesServer(serverId: string): boolean {+ return switchServersStore.statusFor(serverId)?.user?.role === 'admin';+}+/*** Whether the signed-in account may manage the workspace a view about* `serverId` acts in: an owner or admin of that workspace, or the operator* running the server, whom the gateway lets administer every workspace.*/export function administersWorkspaceInScope(serverId: string): boolean {- if (switchServersStore.statusFor(serverId)?.user?.role === 'admin') return true;+ if (operatesServer(serverId)) return true;const workspace = workspacesStore.onServerInScope(serverId);return workspace !== null && administersWorkspace(workspace);}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/page-layout.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/page-layout.tsxindex 9c016bc9b..6a10ae22a 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/page-layout.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/page-layout.tsx@@ -20,29 +20,96 @@ export function PageSidebarMenu<T extends string>({return (<div className="sticky top-0 self-start py-10 [-webkit-app-region:drag]"><nav className="flex w-52 flex-col gap-0.5 [-webkit-app-region:no-drag]">- {items.map((item) => {- const isActive = item.id === activeId && !item.isExternal;- return (- <button- key={item.id}- type="button"- onClick={() => onSelect(item)}- className={cn(- 'flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-normal text-foreground-muted transition-colors hover:bg-background-1 hover:text-foreground',- isActive &&- 'bg-background-2 text-foreground hover:bg-background-2 hover:text-foreground'- )}- >- <span className="text-left">{item.label}</span>- {item.isExternal && <ExternalLink className="h-4 w-4" />}- </button>- );- })}+ {items.map((item) => (+ <PageSidebarButton+ key={item.id}+ item={item}+ active={item.id === activeId}+ onSelect={onSelect}+ />+ ))}</nav></div>);}+export type PageSidebarGroup<T extends string = string> = {+ /** What the group's items act on, such as "Workspace". */+ label: string;+ /** Which one, such as the workspace's name. */+ detail: string;+ items: ReadonlyArray<PageSidebarItem<T>>;+};++/**+ * `PageSidebarMenu` with its items under headings, for a page whose sections+ * reach different things: the heading says what each group acts on, so the+ * sections under it need not.+ */+export function PageSidebarGroups<T extends string>({+ groups,+ activeId,+ onSelect,+}: {+ groups: ReadonlyArray<PageSidebarGroup<T>>;+ activeId: T;+ onSelect: (item: PageSidebarItem<T>) => void;+}) {+ return (+ <div className="sticky top-0 self-start py-10 [-webkit-app-region:drag]">+ <nav className="flex w-52 flex-col gap-5 [-webkit-app-region:no-drag]">+ {groups.map((group) => (+ <div+ key={group.label}+ role="group"+ aria-label={group.label}+ className="flex flex-col gap-0.5"+ >+ <p className="truncate px-3 pb-1 text-xs text-foreground-muted" title={group.detail}>+ <span className="font-medium tracking-wide uppercase">{group.label}</span> ·{' '}+ {group.detail}+ </p>+ {group.items.map((item) => (+ <PageSidebarButton+ key={item.id}+ item={item}+ active={item.id === activeId}+ onSelect={onSelect}+ />+ ))}+ </div>+ ))}+ </nav>+ </div>+ );+}++function PageSidebarButton<T extends string>({+ item,+ active,+ onSelect,+}: {+ item: PageSidebarItem<T>;+ active: boolean;+ onSelect: (item: PageSidebarItem<T>) => void;+}) {+ const isActive = active && !item.isExternal;+ return (+ <button+ type="button"+ aria-current={isActive ? 'page' : undefined}+ onClick={() => onSelect(item)}+ className={cn(+ 'flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-normal text-foreground-muted transition-colors hover:bg-background-1 hover:text-foreground',+ isActive && 'bg-background-2 text-foreground hover:bg-background-2 hover:text-foreground'+ )}+ >+ <span className="text-left">{item.label}</span>+ {item.isExternal && <ExternalLink className="h-4 w-4" />}+ </button>+ );+}+export function PageContent({children,className,diff --git a/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/admin.test.tsnew file mode 100644index 000000000..7eb2d2c95--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';+import { adminGroups, shownAdminSection } from '@renderer/features/admin/admin-sections';+import { switchStanding, switchTiles } from '@renderer/features/admin/workspace-switches';+import type {+ ConnectionCatalogEntry,+ WorkspaceService,+} from '@shared/core/switch-servers/connection-catalog';++function service(overrides: Partial<WorkspaceService> = {}): WorkspaceService {+ return {+ slug: 'example',+ name: 'Example',+ enabled: true,+ updated_by_name: null,+ updated_at: null,+ connected_members: 0,+ granted_agents: 0,+ ...overrides,+ };+}++function entry(slug: string, category: string): ConnectionCatalogEntry {+ return {+ slug,+ name: slug,+ category,+ description: '',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'not_connected',+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: 3600,+ loopback_ports: null,+ key: null,+ external_identity: null,+ consent: null,+ workspace_enabled: true,+ };+}++describe('the Admin page’s sections', () => {+ it('shows the workspace switches to its admins, and the apps under Server to the operator alone', () => {+ expect(adminGroups({ administers: true, operator: false })).toEqual([+ { scope: 'workspace', sections: ['connectors'] },+ ]);+ expect(adminGroups({ administers: true, operator: true })).toEqual([+ { scope: 'workspace', sections: ['connectors'] },+ { scope: 'server', sections: ['apps'] },+ ]);+ expect(adminGroups({ administers: false, operator: false })).toEqual([]);+ });++ it('opens the section asked for when the person may use it, otherwise the first', () => {+ const operator = adminGroups({ administers: true, operator: true });+ const admin = adminGroups({ administers: true, operator: false });+ expect(shownAdminSection(operator, 'apps')).toBe('apps');+ expect(shownAdminSection(admin, 'apps')).toBe('connectors');+ expect(shownAdminSection(admin, undefined)).toBe('connectors');+ expect(shownAdminSection([], 'connectors')).toBeNull();+ });+});++describe('the workspace switches as tiles', () => {+ const services = [+ service({ slug: 'atlassian', name: 'Atlassian' }),+ service({ slug: 'linear', name: 'Linear', enabled: false }),+ service({ slug: 'figma', name: 'Figma' }),+ ];+ const catalog = [entry('atlassian', 'Project management'), entry('figma', 'Design')];++ it('keeps the server’s order whatever each switch says, with the catalog’s category', () => {+ expect(switchTiles(services, catalog, '')).toEqual([+ { service: services[0], category: 'Project management' },+ { service: services[1], category: null },+ { service: services[2], category: 'Design' },+ ]);+ });++ it('has no category before the catalog is read', () => {+ expect(switchTiles(services, undefined, '').map((tile) => tile.category)).toEqual([+ null,+ null,+ null,+ ]);+ });++ it('searches by name and by category, ignoring case', () => {+ expect(switchTiles(services, catalog, ' LIN ').map((tile) => tile.service.slug)).toEqual([+ 'linear',+ ]);+ expect(switchTiles(services, catalog, 'design').map((tile) => tile.service.slug)).toEqual([+ 'figma',+ ]);+ expect(switchTiles(services, catalog, 'nothing')).toEqual([]);+ });++ it('says who a switch reaches', () => {+ expect(switchStanding(service())).toBe('Nobody has connected it yet');+ expect(switchStanding(service({ connected_members: 1, granted_agents: 0 }))).toBe(+ '1 member connected · 0 agents use it'+ );+ expect(switchStanding(service({ connected_members: 3, granted_agents: 1 }))).toBe(+ '3 members connected · 1 agent uses it'+ );+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsxnew file mode 100644index 000000000..8647fe9fa--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx@@ -0,0 +1,506 @@+/**+ * The Admin page of the workspace in scope: its sections down the side,+ * under what they reach, and a workspace admin's switch for each service,+ * drawn as tiles. A switch asks before it reaches other people, shows what+ * the server says rather than what was asked, and keeps its place when it+ * flips. The server's operator also has the apps connectors sign in+ * through, under Server, each opening to its own profile. Someone who+ * administers nothing is told whom to ask.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { WorkspaceService } from '@shared/core/switch-servers/connection-catalog';+import type { ConnectorApp } from '@shared/core/switch-servers/connector-apps';++const workspaces = vi.hoisted(() => ({+ getWorkspaceServices: vi.fn(),+ setWorkspaceService: vi.fn(),+ getServiceConnections: vi.fn(),+}));+const featureFlags = vi.hoisted(() => ({+ get: vi.fn(async () => ({+ success: true,+ data: {+ serverId: 'server',+ flags: { service_connections: true },+ fetchedAt: 1,+ error: null,+ },+ })),+}));+const switchServers = vi.hoisted(() => ({+ getConnectorApps: vi.fn(),+ checkConnectorApp: vi.fn(),+ saveConnectorApp: vi.fn(),+ getConnectorAppImpact: vi.fn(),+}));+const admin = vi.hoisted(() => ({ administers: true, operator: false }));+/** The dialogs asked for, by id; each is answered by the test. */+const modals = vi.hoisted(+ () =>+ [] as {+ id: string;+ title: string;+ description: string;+ mode?: string;+ app?: { slug: string };+ onSuccess: () => void;+ }[]+);+const confirmations = {+ get length() {+ return modals.filter((modal) => modal.id === 'confirmActionModal').length;+ },+ at: (index: number) => modals.filter((modal) => modal.id === 'confirmActionModal')[index]!,+};++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { workspaces, featureFlags, switchServers },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { onServerInScope: () => ({ id: 'workspace', name: 'Acme' }) },+}));++vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: { servers: [{ id: 'server', name: 'Dev Server' }] },+}));++vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({+ administersWorkspaceInScope: () => admin.administers || admin.operator,+ operatesServer: () => admin.operator,+}));++/** Stands in for the app's navigation: a tile opens its profile by navigating. */+const navigation = vi.hoisted(() => {+ let params: Record<string, string | undefined> = { serverId: 'server' };+ const listeners = new Set<() => void>();+ return {+ params: () => params,+ navigate: (_view: string, next?: Record<string, string | undefined>) => {+ params = { serverId: 'server', ...next };+ for (const listener of listeners) listener();+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ reset: () => {+ params = { serverId: 'server' };+ },+ };+});++vi.mock('@renderer/lib/layout/navigation-provider', async () => {+ const { useSyncExternalStore } = await import('react');+ return {+ useNavigate: () => ({ navigate: navigation.navigate }),+ useParams: () => ({+ params: useSyncExternalStore(navigation.subscribe, navigation.params),+ setParams: () => {},+ }),+ };+});++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: (id: string) => (args: Omit<(typeof modals)[number], 'id'>) =>+ modals.push({ id, ...args }),+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++import { adminView } from '@renderer/features/admin/admin-view';+import { ConnectorAppSetupDialog } from '@renderer/features/admin/connector-app-dialogs';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++function service(overrides: Partial<WorkspaceService>): WorkspaceService {+ return {+ slug: 'example',+ name: 'Example',+ enabled: true,+ updated_by_name: null,+ updated_at: null,+ connected_members: 0,+ granted_agents: 0,+ ...overrides,+ };+}++const SERVICES = [+ service({ slug: 'atlassian', name: 'Atlassian', connected_members: 3, granted_agents: 2 }),+ service({ slug: 'figma', name: 'Figma' }),+];++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ navigation.reset();+ admin.administers = true;+ admin.operator = false;+ modals.length = 0;+ for (const mock of Object.values(workspaces)) mock.mockReset();+ for (const mock of Object.values(switchServers)) mock.mockReset();+ workspaces.getServiceConnections.mockResolvedValue([]);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const Panel = adminView.MainPanel;+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Panel />+ </QueryClientProvider>+ )+ );+ return container;+}++function tiles(page: HTMLElement): HTMLElement | null {+ return page.querySelector<HTMLElement>('[role="group"][aria-label="Workspace connectors"]');+}++function switchFor(page: HTMLElement, name: string): HTMLElement | null {+ return page.querySelector<HTMLElement>(`[aria-label="${name} for this workspace"]`);+}++it('lists its sections under what they reach, and each service as a tile with who it uses', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ const page = await render();++ await vi.waitFor(() => expect(tiles(page)).not.toBeNull());+ expect(workspaces.getWorkspaceServices).toHaveBeenCalledWith('workspace');+ expect(page.textContent).toContain('Choose which services people in Acme can connect');+ const workspace = page.querySelector('nav [role="group"][aria-label="Workspace"]')!;+ expect(workspace.textContent).toBe('Workspace · AcmeConnectors');+ expect(workspace.querySelector('[aria-current="page"]')!.textContent).toBe('Connectors');+ expect(page.querySelector('nav [role="group"][aria-label="Server"]')).toBeNull();+ expect(tiles(page)!.textContent).toContain('3 members connected · 2 agents use it');+ expect(tiles(page)!.textContent).toContain('Nobody has connected it yet');+});++it('asks before switching off a service people use, then shows what the server says', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ workspaces.setWorkspaceService.mockResolvedValue({+ slug: 'atlassian',+ enabled: false,+ warning: 'One session could not be reached yet.',+ });+ const page = await render();+ await vi.waitFor(() => expect(switchFor(page, 'Atlassian')).not.toBeNull());++ await act(async () => switchFor(page, 'Atlassian')!.click());+ expect(workspaces.setWorkspaceService).not.toHaveBeenCalled();+ expect(confirmations).toHaveLength(1);+ expect(confirmations.at(0).description).toBe(+ '3 members are connected and 2 agents use it. Their sessions lose it within a minute.'+ );++ workspaces.getWorkspaceServices.mockResolvedValue([+ { ...SERVICES[0], enabled: false, updated_by_name: 'Ada', updated_at: '2026-10-16T09:00:00Z' },+ SERVICES[1],+ ]);+ await act(async () => confirmations.at(0).onSuccess());++ expect(workspaces.setWorkspaceService).toHaveBeenCalledWith({+ workspaceId: 'workspace',+ service: 'atlassian',+ enabled: false,+ });+ await vi.waitFor(() =>+ expect(tiles(page)!.textContent).toContain('Switched off by Ada, Oct 16, 2026.')+ );+ expect(switchFor(page, 'Atlassian')!.getAttribute('aria-checked')).toBe('false');+ expect(page.querySelector('[role="status"]')?.textContent).toBe(+ 'One session could not be reached yet.'+ );+ // Still first: a tile keeps its place when it flips.+ expect(tiles(page)!.firstElementChild!.textContent!.trim()).toMatch(/^Atlassian/);+});++it('switches a service nobody uses without asking, and leaves it as it was on a failure', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ workspaces.setWorkspaceService.mockRejectedValue(new Error('Switch is down.'));+ const page = await render();+ await vi.waitFor(() => expect(switchFor(page, 'Figma')).not.toBeNull());++ await act(async () => switchFor(page, 'Figma')!.click());++ expect(confirmations).toHaveLength(0);+ await vi.waitFor(() => expect(page.querySelector('[role="alert"]')).not.toBeNull());+ expect(page.querySelector('[role="alert"]')!.textContent).toContain('Switch is down.');+ expect(switchFor(page, 'Figma')!.getAttribute('aria-checked')).toBe('true');+});++it('searches the tiles by name', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ const page = await render();+ await vi.waitFor(() => expect(tiles(page)).not.toBeNull());++ const search = page.querySelector<HTMLInputElement>('input[aria-label="Search services"]')!;+ await act(async () => {+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ set.call(search, 'fig');+ search.dispatchEvent(new Event('input', { bubbles: true }));+ });++ expect(switchFor(page, 'Figma')).not.toBeNull();+ expect(switchFor(page, 'Atlassian')).toBeNull();+});++it('says when the server has no workspace switches, rather than drawing none', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(null);+ const page = await render();++ await vi.waitFor(() =>+ expect(page.textContent).toContain("This server can't switch services on or off")+ );+});++it('tells someone who administers nothing whom to ask, asking the server nothing', async () => {+ admin.administers = false;+ const page = await render();++ await vi.waitFor(() =>+ expect(page.textContent).toContain('Ask a workspace admin to change these.')+ );+ expect(workspaces.getWorkspaceServices).not.toHaveBeenCalled();+});++function connectorApp(overrides: Partial<ConnectorApp>): ConnectorApp {+ return {+ slug: 'google-workspace',+ name: 'Google Workspace',+ kind: 'oauth_client',+ source: 'saved',+ configuration_variables: ['GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH'],+ deprecated: false,+ client_id: 'example-client-id',+ saved_client_id: 'example-client-id',+ fields: {},+ secrets: { client_secret: { set: true, last4: 'ab12' } },+ saved_ignored: false,+ unreadable: false,+ load_error: null,+ redirect_uri: 'https://switch.example.test/callback',+ setup_blocked: null,+ install_url: null,+ updated_by_name: 'Ada',+ updated_at: '2026-10-15T10:00:00Z',+ connected_members: 12,+ workspaces: 3,+ stale_connections: 0,+ ...overrides,+ };+}++const GITHUB_NOT_SET_UP = connectorApp({+ slug: 'github',+ name: 'GitHub',+ kind: 'github_app',+ source: 'none',+ client_id: null,+ saved_client_id: null,+ secrets: {},+ connected_members: 0,+ workspaces: 0,+});+const GOOGLE = connectorApp({});++function appTiles(page: HTMLElement): HTMLElement | null {+ return page.querySelector<HTMLElement>('[role="group"][aria-label="Connector apps"]');+}++function button(name: RegExp, within: ParentNode): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++it("gives the server's operator Connector apps under Server, the app needing set-up first", async () => {+ admin.operator = true;+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ switchServers.getConnectorApps.mockResolvedValue({+ public_url: 'https://switch.example.test',+ apps: [GOOGLE, GITHUB_NOT_SET_UP],+ });+ const page = await render();+ await vi.waitFor(() => expect(tiles(page)).not.toBeNull());++ const server = page.querySelector('nav [role="group"][aria-label="Server"]')!;+ expect(server.textContent).toBe('Server · Dev ServerConnector apps');+ await act(async () => button(/^Connector apps$/, server)!.click());+ expect(navigation.params()).toEqual({ serverId: 'server', section: 'apps' });+ await vi.waitFor(() => expect(appTiles(page)).not.toBeNull());+ expect(switchServers.getConnectorApps).toHaveBeenCalledWith('server');+ expect(page.textContent).toContain(+ 'Some connectors sign people in through an app you register with the vendor. Set each up once, and every workspace on Dev Server uses it.'+ );+ const [first, second] = [...appTiles(page)!.children];+ expect(first!.textContent).toContain('GitHub');+ expect(first!.textContent).toContain('Not set up');+ expect(second!.textContent).toContain('Used by 12 people in 3 workspaces');+ // A working app's tile carries no button: checking it is the profile's.+ expect(second!.querySelectorAll('button')).toHaveLength(1);++ await act(async () =>+ page.querySelector<HTMLElement>('button[aria-label="Set up GitHub"]')!.click()+ );+ expect(modals.at(-1)).toMatchObject({+ id: 'connectorAppSetupModal',+ mode: 'set_up',+ app: { slug: 'github' },+ });+});++it('keeps the apps from a workspace admin who does not run the server', async () => {+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);+ const page = await render();+ await vi.waitFor(() => expect(tiles(page)).not.toBeNull());++ expect(page.querySelector('nav [role="group"][aria-label="Server"]')).toBeNull();+ expect(switchServers.getConnectorApps).not.toHaveBeenCalled();+});++it("opens an app's profile from its tile, and a failed check stays on the tile after", async () => {+ admin.operator = true;+ switchServers.getConnectorApps.mockResolvedValue({+ public_url: 'https://switch.example.test',+ apps: [GOOGLE],+ });+ switchServers.checkConnectorApp.mockResolvedValue({+ ok: false,+ checks: [+ { name: 'client', ok: true, message: 'Google knows the client.', field: null },+ { name: 'secret', ok: false, message: 'Google refused the secret.', field: 'client_secret' },+ ],+ });+ navigation.navigate('admin', { section: 'apps' });+ const page = await render();+ await vi.waitFor(() => expect(appTiles(page)).not.toBeNull());++ await act(async () => button(/^Google Workspace/, appTiles(page)!)!.click());+ expect(navigation.params()).toEqual({+ serverId: 'server',+ section: 'apps',+ app: 'google-workspace',+ });+ await vi.waitFor(() => expect(page.querySelector('h1')?.textContent).toBe('Google Workspace'));+ const credentials = page.querySelector('section dl')!;+ expect([...credentials.querySelectorAll('dt')].map((dt) => dt.textContent)).toEqual([+ 'Client ID',+ 'Client secret',+ ]);+ expect(credentials.textContent).toContain('example-client-id');+ expect(credentials.textContent).toContain('•••• ab12');+ expect(page.querySelector('button[aria-label="Copy example-client-id"]')).not.toBeNull();++ await act(async () => button(/^Check it works$/, page)!.click());+ await vi.waitFor(() => expect(page.textContent).toContain('Google refused the secret.'));+ expect(page.querySelector('[aria-label="What the vendor said"]')!.textContent).toContain(+ 'Google knows the client.'+ );+ // The fix is now the obvious button.+ expect(button(/^Update secret$/, page)).toBeDefined();++ // The profile's way back, not the side menu's entry of the same name.+ const back = [...page.querySelectorAll('button')].find(+ (b) => b.textContent === 'Connector apps' && !b.closest('nav')+ )!;+ await act(async () => back.click());+ expect(navigation.params()).toEqual({ serverId: 'server', section: 'apps' });+ await vi.waitFor(() => expect(appTiles(page)).not.toBeNull());+ expect(appTiles(page)!.textContent).toContain('Needs attention');+ expect(appTiles(page)!.textContent).toContain('Google refused the secret.');+});++it('says what is missing before an app can be set up, and holds the button', async () => {+ admin.operator = true;+ switchServers.getConnectorApps.mockResolvedValue({ public_url: null, apps: [GITHUB_NOT_SET_UP] });+ navigation.navigate('admin', { section: 'apps' });+ const page = await render();++ await vi.waitFor(() => expect(page.textContent).toContain('Set GATEWAY_PUBLIC_URL first'));+ expect(+ page.querySelector<HTMLButtonElement>('button[aria-label="Set up GitHub"]')!.disabled+ ).toBe(true);+});++it('marks the value the vendor refused, and saves once it is right', async () => {+ const onSuccess = vi.fn();+ switchServers.saveConnectorApp+ .mockResolvedValueOnce({+ kind: 'refused',+ message: 'Google refused the secret.',+ field: 'client_secret',+ checks: [],+ })+ .mockResolvedValueOnce({ kind: 'saved', app: GOOGLE });+ switchServers.getConnectorApps.mockResolvedValue({ public_url: null, apps: [GOOGLE] });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Dialog open>+ <DialogContent>+ <ConnectorAppSetupDialog+ serverId="server"+ app={connectorApp({ source: 'none', client_id: null, saved_client_id: null })}+ publicUrl="https://switch.example.test"+ mode="set_up"+ onSuccess={onSuccess}+ onClose={() => {}}+ />+ </DialogContent>+ </Dialog>+ </QueryClientProvider>+ )+ );+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(dialog.textContent).toContain('Step 1 of 2');+ expect(dialog.textContent).toContain('Who will connect?');++ await act(async () => button(/^Next$/, dialog)!.click());+ const type = async (input: HTMLInputElement, value: string) =>+ act(async () => {+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ set.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await type(dialog.querySelector<HTMLInputElement>('#connector-app-client_id')!, ' my-client ');+ const secret = dialog.querySelector<HTMLInputElement>('#connector-app-client_secret')!;+ await type(secret, 'wrong');++ await act(async () => button(/^Check and save$/, dialog)!.click());+ await vi.waitFor(() =>+ expect(dialog.querySelector('[role="alert"]')?.textContent).toBe('Google refused the secret.')+ );+ expect(secret.getAttribute('aria-invalid')).toBe('true');+ expect(switchServers.saveConnectorApp).toHaveBeenCalledWith({+ serverId: 'server',+ service: 'google-workspace',+ input: { client_id: 'my-client', client_secret: 'wrong', replace: false },+ });+ expect(onSuccess).not.toHaveBeenCalled();++ await type(secret, 'right');+ expect(dialog.querySelector('[role="alert"]')).toBeNull();+ await act(async () => button(/^Check and save$/, dialog)!.click());+ await vi.waitFor(() => expect(onSuccess).toHaveBeenCalledWith('Google Workspace is ready.'));+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-service-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-service-modal.test.tsxnew file mode 100644index 000000000..ebf11374b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/connect-service-modal.test.tsx@@ -0,0 +1,193 @@+/**+ * Connecting from a Connectors profile, in the profile's workspace: the modal+ * opens the step the catalog entry calls for, a key form for a key service,+ * GitHub's own step for GitHub, and the generic sign-in otherwise. A service+ * whose agents are added from its page closes the dialog as soon as the server+ * has kept the sign-in, handing the warning on; a refusal keeps the dialog open+ * with the reason.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';++const switchServers = vi.hoisted(() => ({+ getGitHubConnection: vi.fn(),+}));+const workspaces = vi.hoisted(() => ({+ getConnectionAgents: vi.fn(),+ setServiceGrant: vi.fn(),+ startServiceConnection: vi.fn(),+ getServiceFlow: vi.fn(),+}));++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { switchServers, workspaces },+}));++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++import { ConnectServiceModal } from '@renderer/features/connectors/connect-service-modal';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++function entry(overrides: Partial<ConnectionCatalogEntry>): ConnectionCatalogEntry {+ return {+ slug: 'example',+ name: 'Example',+ category: 'Development',+ description: 'Example access',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'not_connected',+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: 3600,+ loopback_ports: null,+ key: null,+ external_identity: null,+ consent: null,+ workspace_enabled: true,+ ...overrides,+ };+}++const KEYED = entry({+ slug: 'datadog',+ name: 'Datadog',+ auth_type: 'api_key',+ key: {+ fields: [{ name: 'api_key', label: 'API key', secret: true, help: null, choices: null }],+ help_url: null,+ },+});++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ for (const mock of [...Object.values(switchServers), ...Object.values(workspaces)])+ mock.mockReset();+ workspaces.getConnectionAgents.mockResolvedValue([+ { agent_id: 'm1', name: 'M1', granted: false, addressing_open: false },+ { agent_id: 'm2', name: 'M2', granted: false, addressing_open: true },+ ]);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(+ connection: ConnectionCatalogEntry,+ onConnected: (warning: string | null) => void = () => {},+ onClose: () => void = () => {}+): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Dialog open>+ <DialogContent>+ <ConnectServiceModal+ serverId="server"+ workspaceId="workspace"+ connection={connection}+ startAt="connect"+ onConnected={onConnected}+ onSuccess={() => {}}+ onClose={onClose}+ />+ </DialogContent>+ </Dialog>+ </QueryClientProvider>+ )+ );+ return document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+}++function button(name: RegExp, within: ParentNode): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++it('opens a key service on its key form', async () => {+ const modal = await render(KEYED);++ expect(modal.querySelector('[aria-label="Datadog key"]')).not.toBeNull();+ expect(workspaces.startServiceConnection).not.toHaveBeenCalled();+ expect(switchServers.getGitHubConnection).not.toHaveBeenCalled();+});++it('opens GitHub on its own step', async () => {+ switchServers.getGitHubConnection.mockResolvedValue({+ status: 'not_connected',+ install_url: 'https://github.com/apps/example/installations/new',+ });+ const modal = await render(entry({ slug: 'github', name: 'GitHub', pass_through: false }));++ await vi.waitFor(() => expect(button(/^connect github\s*$/i, modal)).toBeDefined());+ expect(switchServers.getGitHubConnection).toHaveBeenCalledWith('server');+});++it('opens any other service on the sign-in', async () => {+ const modal = await render(entry({}));++ expect(button(/^connect example/i, modal)).toBeDefined();+ expect(modal.querySelector('[aria-label="Example key"]')).toBeNull();+ expect(switchServers.getGitHubConnection).not.toHaveBeenCalled();+});++/** Signs in through the browser; the flow then reads whatever `getServiceFlow` answers. */+async function signIn(modal: HTMLElement): Promise<void> {+ workspaces.startServiceConnection.mockResolvedValue('flow-1');+ await act(async () => button(/^connect example/i, modal)!.click());+}++it('closes as soon as the server has kept the sign-in, handing the warning on', async () => {+ workspaces.getServiceFlow.mockResolvedValue({+ status: 'connected',+ account: '[email protected]',+ error: null,+ warning: 'Access stays a while.',+ });+ const onConnected = vi.fn();+ const onClose = vi.fn();+ const modal = await render(entry({}), onConnected, onClose);+ await signIn(modal);++ await vi.waitFor(() => expect(onConnected).toHaveBeenCalledWith('Access stays a while.'));+ expect(onClose).toHaveBeenCalledOnce();+ expect(workspaces.setServiceGrant).not.toHaveBeenCalled();+});++it('stays open with the reason when the server refuses the sign-in', async () => {+ workspaces.getServiceFlow.mockResolvedValue({+ status: 'failed',+ account: null,+ error: 'Example is switched off for this workspace.',+ warning: null,+ });+ const onConnected = vi.fn();+ const onClose = vi.fn();+ const modal = await render(entry({}), onConnected, onClose);+ await signIn(modal);++ await vi.waitFor(() =>+ expect(modal.querySelector('[role="alert"]')?.textContent).toContain(+ 'Example is switched off for this workspace.'+ )+ );+ expect(onConnected).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ expect(modal.querySelector('[data-slot="dialog-close"]')).not.toBeNull();+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connections-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connections-modal.test.tsxdeleted file mode 100644index 896da9872..000000000--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/connections-modal.test.tsx+++ /dev/null@@ -1,528 +0,0 @@-/**- * Connections open from a server's Your Agents page at any time, not only from- * the setup wizard. The button is offered on a server with service- * connections, which any agent can be granted, or with cloud machines; the- * modal shows the server's catalog, says so when the catalog cannot be read- * (an older server has no catalog endpoint) rather than showing an empty one,- * and opens the GitHub step in place, with a way back to the grid.- */-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { act, useEffect, useState } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';-import { RpcError, serializeRpcError } from '@shared/lib/ipc/rpc-error';--const modalHost = vi.hoisted(() => ({- show: (_id: string, _args: unknown): void => {- throw new Error('No modal host is mounted.');- },-}));-const switchServers = vi.hoisted(() => ({- cloudMachines: vi.fn(),- getConnectionCatalog: vi.fn(),- getGitHubConnection: vi.fn(),- startServiceConnection: vi.fn(),- getServiceFlow: vi.fn(),- confirmServiceConnection: vi.fn(),- connectServiceWithKey: vi.fn(),- disconnectService: vi.fn(),-}));-const openExternalUrl = vi.hoisted(() => vi.fn());--const serverFlags = vi.hoisted(() => ({ service_connections: false }));-const featureFlags = vi.hoisted(() => ({- get: vi.fn(async () => ({ success: true, data: { flags: { ...serverFlags } } })),-}));--vi.mock('@renderer/lib/ipc', () => ({- events: { on: () => () => {} },- rpc: { switchServers, featureFlags },-}));--vi.mock('@renderer/features/locations/stores/agents-store', () => ({- agentsStore: { agentsOnServer: () => [] },-}));--vi.mock('@renderer/features/sidebar/sidebar-tree-data', () => ({- refreshSidebarRoomState: async () => {},- refreshSidebarRoomStateAfterOnboarding: async () => {},-}));--vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({- switchRoomsStore: { workspacesNotSignedIn: [], roomNameById: () => null },-}));--vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({- switchServersStore: { servers: [], statusFor: () => null, isConnected: () => false },-}));--vi.mock('@renderer/lib/layout/navigation-provider', () => ({- useNavigate: () => ({ navigate: () => {} }),- useParams: () => ({ params: { serverId: 'server' } }),-}));--vi.mock('@renderer/lib/modal/modal-provider', () => ({- useShowModal: (id: string) => (args: unknown) => modalHost.show(id, args),- useModalContext: () => ({ setCloseGuard: () => {} }),-}));--vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));--vi.mock('@renderer/lib/stores/use-remote-agents', () => ({- useAgentIconUrl: () => null,-}));--import { ConnectionsModal } from '@renderer/features/switch-servers/ConnectionsModal';-import { serverAgentsView } from '@renderer/features/switch-servers/server-agents-view';-import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';--/** Stands in for the modal renderer: shows the Connections modal once the page asks for it. */-function ModalHost() {- const [shown, setShown] = useState<{ id: string; args: { serverId: string } } | null>(null);- useEffect(() => {- modalHost.show = (id, args) => setShown({ id, args: args as { serverId: string } });- }, []);- if (!shown) return null;- expect(shown.id).toBe('connectionsModal');- return (- <Dialog open>- <DialogContent>- <ConnectionsModal- serverId={shown.args.serverId}- onClose={() => setShown(null)}- onSuccess={() => {}}- />- </DialogContent>- </Dialog>- );-}--function entry(- slug: string,- name: string,- enabled: boolean,- status: ConnectionCatalogEntry['status']-): ConnectionCatalogEntry {- return {- slug,- name,- category: 'Development',- description: `${name} access`,- enabled,- auth_type: 'oauth',- connectable: enabled,- status,- unavailable_reason: null,- pass_through: false,- token_lifetime: null,- loopback_ports: null,- key: null,- external_identity: null,- };-}--const CATALOG = [- entry('github', 'GitHub', true, 'not_connected'),- entry('linear', 'Linear', false, 'coming_soon'),-];--let container: HTMLDivElement | null = null;-let root: Root | null = null;--beforeEach(() => {- switchServers.cloudMachines.mockReset();- switchServers.getConnectionCatalog.mockReset();- switchServers.getGitHubConnection.mockReset();- serverFlags.service_connections = true;- switchServers.connectServiceWithKey.mockReset();- switchServers.disconnectService.mockReset();- openExternalUrl.mockReset().mockResolvedValue(true);-});--afterEach(async () => {- if (root) await act(async () => root!.unmount());- container?.remove();- container = null;- root = null;-});--async function render(): Promise<void> {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);- const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });- const Panel = serverAgentsView.MainPanel;- await act(async () =>- root!.render(- <QueryClientProvider client={client}>- <Panel />- <ModalHost />- </QueryClientProvider>- )- );-}--function button(name: RegExp, within: ParentNode = document): HTMLButtonElement | undefined {- return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));-}--function dialog(): HTMLElement | null {- return document.querySelector<HTMLElement>('[data-slot="dialog-content"]');-}--async function openConnections(): Promise<HTMLElement> {- await vi.waitFor(() => expect(button(/^connections$/i, container!)).toBeDefined());- await act(async () => button(/^connections$/i, container!)!.click());- await vi.waitFor(() => expect(dialog()).not.toBeNull());- return dialog()!;-}--it('offers no Connections for cloud machines alone, without service connections', async () => {- serverFlags.service_connections = false;- switchServers.cloudMachines.mockResolvedValue([]);- await render();-- await vi.waitFor(() => expect(featureFlags.get).toHaveBeenCalledWith('server'));- await act(async () => {});- expect(button(/^connections$/i, container!)).toBeUndefined();-});--it('offers Connections on a server with service connections and no cloud machine', async () => {- switchServers.cloudMachines.mockResolvedValue(null);- serverFlags.service_connections = true;- await render();-- await vi.waitFor(() => expect(button(/^connections$/i, container!)).toBeDefined());- expect(featureFlags.get).toHaveBeenCalledWith('server');-});--it('offers no Connections without service connections or cloud machines', async () => {- serverFlags.service_connections = false;- switchServers.cloudMachines.mockResolvedValue(null);- await render();-- await vi.waitFor(() => expect(switchServers.cloudMachines).toHaveBeenCalled());- await vi.waitFor(() => expect(featureFlags.get).toHaveBeenCalled());- await act(async () => {});- expect(button(/^connections$/i, container!)).toBeUndefined();-});--it('disables a service the server cannot connect, saying why', async () => {- serverFlags.service_connections = true;- switchServers.cloudMachines.mockResolvedValue(null);- switchServers.getConnectionCatalog.mockResolvedValue([- {- ...entry('github', 'GitHub', true, 'not_connected'),- connectable: false,- unavailable_reason: 'GitHub is not set up on this server.',- },- ]);- await render();- const modal = await openConnections();-- await vi.waitFor(() => expect(button(/GitHub/, modal)).toBeDefined());- expect(button(/GitHub/, modal)?.disabled).toBe(true);- expect(button(/GitHub/, modal)?.textContent).toMatch(/not set up on this server/);-});--it('shows the server’s connection grid', async () => {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockResolvedValue(CATALOG);- await render();- const modal = await openConnections();-- await vi.waitFor(() =>- expect(modal.querySelector('[role="group"][aria-label="Connections"]')).not.toBeNull()- );- expect(switchServers.getConnectionCatalog).toHaveBeenCalledWith('server');- expect(button(/GitHub/, modal)?.disabled).toBe(false);- expect(button(/Linear/, modal)?.disabled).toBe(true);- expect(button(/Linear/, modal)?.textContent).toMatch(/Coming soon/);-});--it('shows the real error when the catalog cannot be read', async () => {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockRejectedValue(- new RpcError(- serializeRpcError(- Object.assign(new Error('Switch gateway returned 404'), {- name: 'GatewayError',- kind: 'http',- status: 404,- detail: 'Not Found',- })- )- )- );- await render();- const modal = await openConnections();-- await vi.waitFor(() =>- expect(modal.querySelector('[role="alert"]')?.textContent).toBe(- 'Could not load connections. (HTTP 404: Not Found)'- )- );- expect(modal.querySelector('[role="group"][aria-label="Connections"]')).toBeNull();- expect(button(/^retry$/i, modal)).toBeDefined();-});--it('opens the GitHub step from the grid and returns to it', async () => {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockResolvedValue(CATALOG);- switchServers.getGitHubConnection.mockResolvedValue({- status: 'not_connected',- install_url: 'https://github.com/apps/example/installations/new',- });- await render();- const modal = await openConnections();- await vi.waitFor(() => expect(button(/GitHub/, modal)?.disabled).toBe(false));-- await act(async () => button(/GitHub/, modal)!.click());- await vi.waitFor(() => expect(button(/^connect github\s*$/i, dialog()!)).toBeDefined());- expect(switchServers.getGitHubConnection).toHaveBeenCalledWith('server');- expect(button(/set up later/i, dialog()!)).toBeUndefined();- expect(button(/continue to agent/i, dialog()!)).toBeUndefined();-- await act(async () => button(/^back$/i, dialog()!)!.click());- await vi.waitFor(() =>- expect(dialog()!.querySelector('[role="group"][aria-label="Connections"]')).not.toBeNull()- );- expect(switchServers.getConnectionCatalog).toHaveBeenCalledTimes(2);-});--it("says when an organization's single sign-on hides its installation", async () => {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockResolvedValue(CATALOG);- switchServers.getGitHubConnection.mockResolvedValue({- status: 'connected',- login: 'example-user',- install_url: 'https://github.com/apps/example/installations/new',- installations: [],- sso_hidden_organizations: [21955855],- });- await render();- const modal = await openConnections();- await vi.waitFor(() => expect(button(/GitHub/, modal)?.disabled).toBe(false));-- await act(async () => button(/GitHub/, modal)!.click());- await vi.waitFor(() =>- expect(dialog()!.querySelector('[role="alert"]')?.textContent).toMatch(- /single sign-on hides its installation/- )- );-});--it('connects any connectable service through the generic sign-in', async () => {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockResolvedValue([- ...CATALOG,- entry('example', 'Example', true, 'not_connected'),- ]);- switchServers.startServiceConnection.mockResolvedValue('flow-1');- switchServers.getServiceFlow.mockResolvedValue({- status: 'ready',- account: '[email protected]',- error: null,- });- switchServers.confirmServiceConnection.mockResolvedValue({ warning: null });- await render();- const modal = await openConnections();- await vi.waitFor(() => expect(button(/Example/, modal)?.disabled).toBe(false));-- await act(async () => button(/Example/, modal)!.click());- await vi.waitFor(() => expect(button(/^connect example/i, dialog()!)).toBeDefined());- expect(switchServers.getGitHubConnection).not.toHaveBeenCalled();- await act(async () => button(/^connect example/i, dialog()!)!.click());- expect(switchServers.startServiceConnection).toHaveBeenCalledWith('server', 'example');-- await vi.waitFor(() => expect(dialog()!.textContent).toMatch(/Signed in as ada@example\.test/));- await act(async () => button(/^connect ada@example\.test/i, dialog()!)!.click());- expect(switchServers.confirmServiceConnection).toHaveBeenCalledWith(- 'server',- 'example',- 'flow-1'- );- await vi.waitFor(() => expect(dialog()!.textContent).toMatch(/Example connected/));- expect(button(/^disconnect$/i, dialog()!)).toBeDefined();-});--const API_KEY = 'synthetic-datadog-api-key';-const APP_KEY = 'synthetic-datadog-application-key';--/** A service connected with a key, as the catalog describes Datadog's. */-function keyed(status: ConnectionCatalogEntry['status'] = 'not_connected'): ConnectionCatalogEntry {- return {- ...entry('datadog', 'Datadog', true, status),- category: 'Observability',- auth_type: 'api_key',- pass_through: true,- token_lifetime: 3600,- external_identity: status === 'connected' ? 'Datadog key · datadoghq.eu' : null,- key: {- fields: [- {- name: 'api_key',- label: 'API key',- secret: true,- help: 'Organization Settings, API Keys.',- choices: null,- },- {- name: 'application_key',- label: 'Application key',- secret: true,- help: 'Personal Settings, Application Keys.',- choices: null,- },- {- name: 'site',- label: 'Datadog site',- secret: false,- help: 'The address you open Datadog at.',- choices: ['datadoghq.com', 'datadoghq.eu'],- },- ],- help_url: 'https://docs.datadoghq.com/account_management/api-app-keys/',- },- };-}--async function openKeyStep(status: ConnectionCatalogEntry['status'] = 'not_connected') {- switchServers.cloudMachines.mockResolvedValue([]);- switchServers.getConnectionCatalog.mockResolvedValue([...CATALOG, keyed(status)]);- await render();- const modal = await openConnections();- await vi.waitFor(() => expect(button(/Datadog/, modal)?.disabled).toBe(false));- await act(async () => button(/Datadog/, modal)!.click());- await vi.waitFor(() =>- expect(dialog()!.textContent).toMatch(/Connect Datadog|Datadog connected/)- );- return dialog()!;-}--function input(within: ParentNode, label: string): HTMLInputElement {- const id = [...within.querySelectorAll('label')].find((l) => l.textContent === label)!.htmlFor;- return within.querySelector<HTMLInputElement>(`#${id}`)!;-}--async function type(target: HTMLInputElement, value: string) {- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;- await act(async () => {- setter.call(target, value);- target.dispatchEvent(new Event('input', { bubbles: true }));- });-}--async function pick(within: ParentNode, label: string, choice: string) {- await act(async () => within.querySelector<HTMLElement>(`[aria-label="${label}"]`)!.click());- await vi.waitFor(() =>- expect(document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0)- );- const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(- (candidate) => candidate.textContent?.trim() === choice- )!;- await act(async () => option.click());-}--async function fillKey(step: HTMLElement) {- await type(input(step, 'API key'), API_KEY);- await type(input(step, 'Application key'), APP_KEY);- await pick(step, 'Datadog site', 'datadoghq.eu');-}--it('opens a key service in a form built from its catalog entry, not the sign-in', async () => {- const step = await openKeyStep();-- expect(step.textContent).toMatch(/Connect Datadog/);- expect(input(step, 'API key').type).toBe('password');- expect(input(step, 'Application key').type).toBe('password');- expect(step.querySelector('[aria-label="Datadog site"]')).not.toBeNull();- expect(step.textContent).toContain('Organization Settings, API Keys.');- expect(step.textContent).toContain('The address you open Datadog at.');- expect(step.textContent).toContain(- "Switch checks the key with Datadog, stores it encrypted, and never shows it again. The agent can do whatever this key allows. Keys don't expire; disconnecting removes the key from Switch but can't revoke it at Datadog — revoke it there too."- );- expect(switchServers.startServiceConnection).not.toHaveBeenCalled();- await act(async () => button(/How to make a Datadog key/, step)!.click());- expect(openExternalUrl).toHaveBeenCalledWith(- 'https://docs.datadoghq.com/account_management/api-app-keys/',- expect.any(String)- );- expect(button(/^connect datadog$/i, step)?.disabled).toBe(true);-});--it('connects with the fields typed and picked, and shows whose key it is', async () => {- switchServers.connectServiceWithKey.mockResolvedValue({- warning: null,- external_identity: 'Datadog key · datadoghq.eu',- });- switchServers.disconnectService.mockResolvedValue({- warning: 'Switch has forgotten the Datadog key but cannot revoke it.',- });- const step = await openKeyStep();- await fillKey(step);-- await vi.waitFor(() => expect(button(/^connect datadog$/i, step)?.disabled).toBe(false));- await act(async () => button(/^connect datadog$/i, step)!.click());- expect(switchServers.connectServiceWithKey).toHaveBeenCalledWith('server', 'datadog', {- api_key: API_KEY,- application_key: APP_KEY,- site: 'datadoghq.eu',- });- await vi.waitFor(() => expect(dialog()!.textContent).toMatch(/Datadog connected/));- expect(dialog()!.textContent).toContain('Connected with Datadog key · datadoghq.eu');- expect(dialog()!.innerHTML).not.toContain(API_KEY);- expect(dialog()!.innerHTML).not.toContain(APP_KEY);-- await act(async () => button(/^replace key$/i, dialog()!)!.click());- expect(input(dialog()!, 'API key').value).toBe('');- expect(input(dialog()!, 'Application key').value).toBe('');-- await act(async () => button(/^disconnect$/i, dialog()!)!.click());- expect(switchServers.disconnectService).toHaveBeenCalledWith('server', 'datadog');- await vi.waitFor(() =>- expect(dialog()!.querySelector('[role="status"]')?.textContent).toBe(- 'Switch has forgotten the Datadog key but cannot revoke it.'- )- );- expect(dialog()!.textContent).toMatch(/Connect Datadog/);-});--it('shows Switch’s refusal of a key, and clears the keys typed', async () => {- switchServers.connectServiceWithKey.mockRejectedValue(- new RpcError(- serializeRpcError(- Object.assign(new Error('Switch gateway returned 422'), {- name: 'GatewayError',- kind: 'http',- status: 422,- detail: 'Datadog refused the key (HTTP 403). Check that it is right.',- })- )- )- );- const step = await openKeyStep();- await fillKey(step);- await act(async () => button(/^connect datadog$/i, step)!.click());-- await vi.waitFor(() =>- expect(dialog()!.querySelector('[role="alert"]')?.textContent).toContain(- 'Datadog refused the key (HTTP 403). Check that it is right.'- )- );- expect(input(dialog()!, 'API key').value).toBe('');- expect(input(dialog()!, 'Application key').value).toBe('');- expect(dialog()!.querySelector('[aria-label="Datadog site"]')?.textContent).toContain(- 'datadoghq.eu'- );- expect(dialog()!.textContent).toMatch(/Connect Datadog/);-});--it('shows a connected key service as connected, with whose key it is', async () => {- const step = await openKeyStep('connected');- expect(step.textContent).toMatch(/Datadog connected/);- expect(step.textContent).toContain('Connected with Datadog key · datadoghq.eu');- expect(button(/^disconnect$/i, step)).toBeDefined();- expect(step.querySelector('[aria-label="Datadog key"]')).toBeNull();-});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/connectors-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/connectors-page.test.tsxnew file mode 100644index 000000000..bce1a6be7--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/connectors-page.test.tsx@@ -0,0 +1,457 @@+/**+ * The Connectors page of the workspace in scope: its grid shows the+ * workspace's catalog, a service that cannot be used here says so, and a+ * catalog that cannot be read shows the real error with a way to retry+ * rather than an empty grid. A profile shows the truth after a disconnect,+ * made in the page's workspace: the page is re-read before the dialog+ * closes, and a re-read that fails says so on the profile.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, useEffect, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { RpcError, serializeRpcError } from '@shared/lib/ipc/rpc-error';++const workspaces = vi.hoisted(() => ({+ getServiceConnections: vi.fn(),+ getConnectionAgents: vi.fn(),+ disconnectService: vi.fn(),+ getGitHubConnection: vi.fn(),+ setServiceGrant: vi.fn(),+}));+const switchServers = vi.hoisted(() => ({+ openGitHubInstallation: vi.fn(),+}));+const modalHost = vi.hoisted(() => ({+ show: (_id: string, _args: unknown): void => {+ throw new Error('No modal host is mounted.');+ },+}));+const featureFlags = vi.hoisted(() => ({+ get: vi.fn(async () => ({+ success: true,+ data: {+ serverId: 'server',+ flags: { service_connections: true },+ fetchedAt: 1,+ error: null,+ },+ })),+}));++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { workspaces, featureFlags, switchServers },+}));++vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { idOnServerInScope: () => 'workspace' },+}));++const admin = vi.hoisted(() => ({ administers: false }));++vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({+ administersWorkspaceInScope: () => admin.administers,+}));++/** Stands in for the app's navigation: a card opens its profile by navigating. */+const navigation = vi.hoisted(() => {+ let params: Record<string, string | undefined> = { serverId: 'server' };+ let view = 'connectors';+ const listeners = new Set<() => void>();+ return {+ params: () => params,+ view: () => view,+ navigate: (to: string, next?: Record<string, string | undefined>) => {+ view = to;+ params = { serverId: 'server', ...next };+ for (const listener of listeners) listener();+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ reset: () => {+ view = 'connectors';+ params = { serverId: 'server' };+ },+ };+});++vi.mock('@renderer/lib/layout/navigation-provider', async () => {+ const { useSyncExternalStore } = await import('react');+ return {+ useNavigate: () => ({ navigate: navigation.navigate }),+ useParams: () => ({+ params: useSyncExternalStore(navigation.subscribe, navigation.params),+ setParams: () => {},+ }),+ };+});++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: (id: string) => (args: unknown) => modalHost.show(id, args),+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++import { connectorsView } from '@renderer/features/connectors/connectors-view';+import { DisconnectServiceDialog } from '@renderer/features/connectors/disconnect-dialog';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++type DisconnectArgs = {+ workspaceId: string;+ connection: ConnectionCatalogEntry;+ onSuccess?: (result: unknown) => void;+};++/** Stands in for the modal renderer: shows the disconnect dialog once the profile asks for it. */+function ModalHost() {+ const [shown, setShown] = useState<{ id: string; args: DisconnectArgs } | null>(null);+ useEffect(() => {+ modalHost.show = (id, args) => setShown({ id, args: args as DisconnectArgs });+ }, []);+ if (shown?.id !== 'disconnectServiceModal') return null;+ const { args } = shown;+ return (+ <Dialog open>+ <DialogContent>+ <DisconnectServiceDialog+ workspaceId={args.workspaceId}+ connection={args.connection}+ onSuccess={(result) => {+ setShown(null);+ args.onSuccess?.(result);+ }}+ onClose={() => setShown(null)}+ />+ </DialogContent>+ </Dialog>+ );+}++function entry(overrides: Partial<ConnectionCatalogEntry>): ConnectionCatalogEntry {+ return {+ slug: 'example',+ name: 'Example',+ category: 'Development',+ description: 'Example access',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'not_connected',+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: 3600,+ loopback_ports: null,+ key: null,+ external_identity: null,+ consent: null,+ workspace_enabled: true,+ ...overrides,+ };+}++const CATALOG = [+ entry({ slug: 'atlassian', name: 'Atlassian', status: 'connected', external_identity: 'ada' }),+ entry({ slug: 'example', name: 'Example' }),+ entry({ slug: 'linear', name: 'Linear', enabled: false, status: 'coming_soon' }),+ entry({+ slug: 'github',+ name: 'GitHub',+ connectable: false,+ unavailable_reason: 'GitHub is not set up on this server.',+ }),+];++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ navigation.reset();+ admin.administers = false;+ for (const mock of Object.values(workspaces)) mock.mockReset();+ switchServers.openGitHubInstallation.mockReset();+ workspaces.getConnectionAgents.mockResolvedValue([]);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const Panel = connectorsView.MainPanel;+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Panel />+ <ModalHost />+ </QueryClientProvider>+ )+ );+ return container;+}++function button(name: RegExp, within: ParentNode): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++function grid(page: HTMLElement): HTMLElement | null {+ return page.querySelector<HTMLElement>(+ '[role="group"][aria-label="Connectors"]:not([data-slot="toggle-group"])'+ );+}++it("shows the workspace's catalog, what the person has on Yours and everything on Discover", async () => {+ workspaces.getServiceConnections.mockResolvedValue(CATALOG);+ const page = await render();++ await vi.waitFor(() => expect(grid(page)).not.toBeNull());+ expect(workspaces.getServiceConnections).toHaveBeenCalledWith('workspace');+ expect(button(/^Atlassian/, grid(page)!)).toBeDefined();+ expect(button(/^Example/, grid(page)!)).toBeUndefined();+ expect(page.querySelector('[aria-label="Atlassian connected"]')).not.toBeNull();++ await act(async () => page.querySelector<HTMLElement>('button[aria-label="Discover"]')!.click());+ await vi.waitFor(() => expect(button(/^Example/, grid(page)!)).toBeDefined());+ expect(page.querySelector('button[aria-label="Connect Example"]')).not.toBeNull();+ expect(button(/^Linear/, grid(page)!)?.disabled).toBe(true);+ expect(button(/^Linear/, grid(page)!)?.textContent).toMatch(/Coming soon/);+});++it('marks a service the server cannot use with its reason, without offering to connect it', async () => {+ workspaces.getServiceConnections.mockResolvedValue(CATALOG);+ const page = await render();+ await vi.waitFor(() => expect(grid(page)).not.toBeNull());+ await act(async () => page.querySelector<HTMLElement>('button[aria-label="Discover"]')!.click());++ await vi.waitFor(() => expect(button(/^GitHub/, grid(page)!)).toBeDefined());+ expect(button(/^GitHub/, grid(page)!)!.textContent).toMatch(/Unavailable/);+ expect(button(/^GitHub/, grid(page)!)!.textContent).toContain(+ 'GitHub is not set up on this server.'+ );+ expect(page.querySelector('button[aria-label="Connect GitHub"]')).toBeNull();+});++it('shows the real error when the catalog cannot be read, with Retry', async () => {+ workspaces.getServiceConnections.mockRejectedValue(+ new RpcError(+ serializeRpcError(+ Object.assign(new Error('Switch gateway returned 404'), {+ name: 'GatewayError',+ kind: 'http',+ status: 404,+ detail: 'Not Found',+ })+ )+ )+ );+ const page = await render();++ await vi.waitFor(() =>+ expect(page.querySelector('[role="alert"]')?.textContent).toContain(+ 'Could not load the connectors. (HTTP 404: Not Found)'+ )+ );+ expect(grid(page)).toBeNull();++ workspaces.getServiceConnections.mockResolvedValue(CATALOG);+ await act(async () => button(/^retry$/i, page)!.click());+ await vi.waitFor(() => expect(grid(page)).not.toBeNull());+});++/** The catalog and agents as the server answers before and after Atlassian is disconnected. */+function serveDisconnect(): void {+ let connected = true;+ workspaces.getServiceConnections.mockImplementation(async () =>+ CATALOG.map((item) =>+ item.slug === 'atlassian' && !connected+ ? { ...item, status: 'not_connected', external_identity: null }+ : item+ )+ );+ workspaces.getConnectionAgents.mockImplementation(async () => [+ { agent_id: 'm1', name: 'M1', granted: connected, addressing_open: false },+ ]);+ workspaces.disconnectService.mockImplementation(async () => {+ connected = false;+ return { warning: null };+ });+}++async function openAtlassian(page: HTMLElement): Promise<void> {+ await vi.waitFor(() => expect(button(/^Atlassian/, grid(page)!)).toBeDefined());+ await act(async () => button(/^Atlassian/, grid(page)!)!.click());+ await vi.waitFor(() => expect(page.querySelector('h1')?.textContent).toBe('Atlassian'));+ await vi.waitFor(() =>+ expect(page.querySelector('[role="list"][aria-label="Agents"]')?.textContent).toContain('M1')+ );+}++async function disconnect(page: HTMLElement): Promise<void> {+ await act(async () => button(/^Disconnect$/, page)!.click());+ const dialog = () => document.querySelector<HTMLElement>('[data-slot="dialog-content"]');+ await vi.waitFor(() => expect(dialog()?.textContent).toContain('M1 loses Atlassian.'));+ await act(async () => button(/^Disconnect$/, dialog()!)!.click());+ await vi.waitFor(() => expect(dialog()).toBeNull());+}++it('offers Connect on the profile after a disconnect, made in the workspace shown', async () => {+ serveDisconnect();+ const page = await render();+ await openAtlassian(page);++ await disconnect(page);+ expect(workspaces.disconnectService).toHaveBeenCalledWith({+ workspaceId: 'workspace',+ service: 'atlassian',+ });+ expect(button(/^Connect to Switch$/, page)).toBeDefined();+ expect(button(/^Disconnect$/, page)).toBeUndefined();+ expect(page.textContent).not.toContain('Connected as ada');+ expect(page.textContent).toContain('None of your agents use Atlassian yet.');+ expect(page.querySelector('[role="list"][aria-label="Agents"]')).toBeNull();+});++it('says on the profile when re-reading the catalog fails, with Retry', async () => {+ serveDisconnect();+ const page = await render();+ await openAtlassian(page);+ const serve = workspaces.getServiceConnections.getMockImplementation()!;+ workspaces.getServiceConnections.mockRejectedValue(new Error('Switch is down.'));++ await disconnect(page);+ await vi.waitFor(() =>+ expect(page.querySelector('[role="alert"]')?.textContent).toContain(+ 'Could not load the connectors.'+ )+ );++ workspaces.getServiceConnections.mockImplementation(serve);+ await act(async () => button(/^retry$/i, page)!.click());+ await vi.waitFor(() => expect(button(/^Connect to Switch$/, page)).toBeDefined());+ expect(page.querySelector('[role="alert"]')).toBeNull();+});++it("shows GitHub's repositories on its profile, and adds an agent with them", async () => {+ workspaces.getServiceConnections.mockResolvedValue([+ entry({+ slug: 'github',+ name: 'GitHub',+ status: 'connected',+ external_identity: 'ada',+ pass_through: false,+ }),+ ]);+ workspaces.getGitHubConnection.mockResolvedValue({+ status: 'connected',+ login: 'ada',+ install_url: 'https://github.com/apps/example/installations/new',+ installations: [+ {+ id: 7,+ account: 'ada',+ repositories: [+ { id: 1, name: 'ada/one' },+ { id: 2, name: 'ada/two' },+ ],+ },+ ],+ });+ workspaces.getConnectionAgents.mockResolvedValue([+ { agent_id: 'm1', name: 'M1', granted: false, addressing_open: false },+ ]);+ workspaces.setServiceGrant.mockResolvedValue(null);+ const page = await render();++ await vi.waitFor(() => expect(button(/^GitHub/, grid(page)!)).toBeDefined());+ await act(async () => button(/^GitHub/, grid(page)!)!.click());+ await vi.waitFor(() => expect(page.querySelector('h1')?.textContent).toBe('GitHub'));+ const repositories = () => page.querySelector('section[aria-label="Repositories"]')!;+ await vi.waitFor(() => expect(repositories().textContent).toContain('2 repositories'));+ // The account card opens to its list; the names are not on the page before that.+ expect(repositories().textContent).not.toContain('ada/one');+ await act(async () =>+ repositories()+ .querySelector<HTMLButtonElement>('button[aria-label="Show the repositories under ada"]')!+ .click()+ );+ await vi.waitFor(() => expect(repositories().textContent).toContain('ada/one'));+ expect(button(/^Choose repositories/, page)).toBeUndefined();+ await act(async () => button(/^Change repositories/, repositories())!.click());+ expect(switchServers.openGitHubInstallation).toHaveBeenCalledWith('server');++ // Adding an agent: nothing is chosen yet, so no agent can be added.+ await act(async () => button(/^Add agent$/, page)!.click());+ await vi.waitFor(() => expect(page.textContent).toContain('No repositories chosen yet'));+ await vi.waitFor(() => expect(button(/M1/, page)).toBeDefined());+ expect(button(/M1/, page)!.disabled).toBe(true);++ // Add all, then drop one: the chips are the choice.+ await act(async () => button(/^Choose repositories$/, page)!.click());+ await vi.waitFor(() => expect(button(/^Add all$/, page)).toBeDefined());+ await act(async () => button(/^Add all$/, page)!.click());+ const chips = () => page.querySelector('[aria-label="Chosen repositories"]');+ await vi.waitFor(() => expect(chips()?.textContent).toContain('ada/two'));+ expect(page.textContent).toContain('2 of 2 chosen');+ await act(async () =>+ page.querySelector<HTMLButtonElement>('button[aria-label="Remove ada/one"]')!.click()+ );+ await vi.waitFor(() => expect(chips()?.textContent).not.toContain('ada/one'));+ await act(async () => button(/^Done$/, page)!.click());+ await vi.waitFor(() =>+ expect(page.textContent).toContain('Agents you add get read access to 1 repository.')+ );+ expect(button(/^Change$/, page)).toBeDefined();++ await vi.waitFor(() => expect(button(/M1/, page)!.disabled).toBe(false));+ await act(async () => button(/M1/, page)!.click());+ expect(workspaces.setServiceGrant).toHaveBeenCalledWith({+ workspaceId: 'workspace',+ agentId: 'm1',+ service: 'github',+ access: 'read',+ resources: { installation_id: 7, repository_ids: [2] },+ });+});++it('shows a connection the workspace has switched off as off, not as connected', async () => {+ workspaces.getServiceConnections.mockResolvedValue([+ entry({ slug: 'atlassian', name: 'Atlassian', status: 'connected', workspace_enabled: false }),+ ]);+ const page = await render();++ await vi.waitFor(() => expect(button(/^Atlassian/, grid(page)!)).toBeDefined());+ expect(page.querySelector('[aria-label="Atlassian connected"]')).toBeNull();+ expect(button(/^Atlassian/, grid(page)!)!.textContent).toContain('Off in this workspace');+ expect(button(/^Atlassian/, grid(page)!)!.textContent).toContain(+ 'A workspace admin has switched it off.'+ );+});++it('offers an admin the way to the workspace switches, and nobody else', async () => {+ workspaces.getServiceConnections.mockResolvedValue(CATALOG);+ let page = await render();+ await vi.waitFor(() => expect(grid(page)).not.toBeNull());+ expect(button(/Manage in Admin/, page)).toBeUndefined();+ expect(page.querySelector('button[aria-label="Workspace"]')).toBeNull();+ await act(async () => root!.unmount());+ root = null;+ container!.remove();++ admin.administers = true;+ page = await render();+ await vi.waitFor(() => expect(button(/Manage in Admin/, page)).toBeDefined());+ await act(async () => button(/Manage in Admin/, page)!.click());+ expect(navigation.view()).toBe('admin');+ expect(navigation.params()).toEqual({ serverId: 'server', section: 'connectors' });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsxindex b18f4b706..652e09326 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx@@ -3,7 +3,8 @@* header, instructions, General, the server's Advanced configuration for its* provider and its sessions. Every edit is pending until the page's save bar* saves them together, sending only what changed; a refusal is shown in the- * server's words.+ * server's words. Its tabbed titlebar keeps every tab in view beside a long+ * name.*/import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { act } from 'react';@@ -66,7 +67,12 @@ vi.mock(vi.mock('@renderer/lib/components/agent-icon-picker', () => ({ AgentIconPicker: () => null }));vi.mock('@renderer/lib/modal/modal-provider', () => ({ useShowModal: () => vi.fn() }));+import '@renderer/index.css';+import { agentTabs } from '@renderer/features/managed-agents/agent-tabs';import { ManagedAgentPage } from '@renderer/features/managed-agents/managed-agent-page';+import { TabbedAgentTitlebar } from '@renderer/features/managed-agents/tabbed-agent-titlebar';+import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';+import { WorkspaceLayoutContextProvider } from '@renderer/lib/layout/layout-provider';const AGENT: ManagedAgentView = {serverId: 'server-1',@@ -132,7 +138,7 @@ beforeEach(async () => {await act(async () => {root.render(<QueryClientProvider client={client}>- <ManagedAgentPage agent={AGENT} />+ <ManagedAgentPage agent={AGENT} serviceGrants /></QueryClientProvider>);});@@ -261,6 +267,7 @@ it('shows where the machine will make the agent’s directory when nothing names<QueryClientProvider client={client}><ManagedAgentPagekey="unplaced"+ serviceGrantsagent={{ ...AGENT, definition: { ...AGENT.definition, directory: null } }}/></QueryClientProvider>@@ -283,7 +290,7 @@ it('gives an agent on the Switch cloud machine the cloud agent’s service accesawait act(async () => {root.render(<QueryClientProvider client={client}>- <ManagedAgentPage key="cloud" agent={{ ...AGENT, machine }} />+ <ManagedAgentPage key="cloud" agent={{ ...AGENT, machine }} serviceGrants /></QueryClientProvider>);});@@ -293,3 +300,41 @@ it('gives an agent on the Switch cloud machine the cloud agent’s service acces));});++it('keeps Chats, Connections and Settings in view beside a long name, on every tab', async () => {+ const tabs = agentTabs(true, undefined);+ expect(tabs.map((tab) => tab.label)).toEqual(['Chats', 'Connections', 'Settings']);+ for (const shown of tabs) {+ const host = document.createElement('div');+ host.style.width = '900px';+ document.body.appendChild(host);+ const titleRoot = createRoot(host);+ await act(async () =>+ titleRoot.render(+ <WorkspaceLayoutContextProvider>+ <TabbedAgentTitlebar+ breadcrumb={+ <TitlebarBreadcrumb crumbs={[{ key: 'agent', label: 'm3-managed-reviewer' }]} />+ }+ tab={shown.value}+ tabs={tabs}+ onTab={() => {}}+ rightSlot={null}+ />+ </WorkspaceLayoutContextProvider>+ )+ );+ const control = host.querySelector<HTMLElement>('[aria-label="Agent view"]')!;+ const side = control.parentElement!.parentElement!.getBoundingClientRect();+ for (const { label } of tabs) {+ const item = control.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;+ const box = item.getBoundingClientRect();+ expect(box.width, `${label} on ${shown.label}`).toBeGreaterThan(0);+ expect(item.scrollWidth, `${label} on ${shown.label}`).toBeLessThanOrEqual(item.clientWidth);+ expect(box.right, `${label} on ${shown.label}`).toBeLessThanOrEqual(side.right + 0.5);+ }+ expect(host.textContent).toContain('m3-managed-reviewer');+ act(() => titleRoot.unmount());+ host.remove();+ }+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-github-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-github-step.test.tsxnew file mode 100644index 000000000..ccc3217fe--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-github-step.test.tsx@@ -0,0 +1,130 @@+/**+ * GitHub's own step, opened from the Connectors page: it offers to connect,+ * none of the setup wizard's ways onward, and a way back; and it says when an+ * organization's single sign-on hides the installation.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const switchServers = vi.hoisted(() => ({+ getGitHubConnection: vi.fn(),+}));++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { switchServers },+}));++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++import { ManagedGitHubStep } from '@renderer/features/switch-servers/managed-github-step';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ switchServers.getGitHubConnection.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(onBack: () => void, onDone?: () => void): Promise<void> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <Dialog open>+ <DialogContent>+ <ManagedGitHubStep serverId="server" onBack={onBack} onDone={onDone} />+ </DialogContent>+ </Dialog>+ )+ );+}++function button(name: RegExp, within: ParentNode = document): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++function dialog(): HTMLElement {+ return document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+}++it('offers to connect GitHub, and a way back', async () => {+ switchServers.getGitHubConnection.mockResolvedValue({+ status: 'not_connected',+ install_url: 'https://github.com/apps/example/installations/new',+ });+ const onBack = vi.fn();+ await render(onBack);++ await vi.waitFor(() => expect(button(/^connect github\s*$/i, dialog())).toBeDefined());+ expect(switchServers.getGitHubConnection).toHaveBeenCalledWith('server');+ expect(button(/set up later/i, dialog())).toBeUndefined();+ expect(button(/continue to agent/i, dialog())).toBeUndefined();++ await act(async () => button(/^back$/i, dialog())!.click());+ expect(onBack).toHaveBeenCalledOnce();+});++it("on a connector's page, a connected step offers Done and nothing else", async () => {+ switchServers.getGitHubConnection.mockResolvedValue({+ status: 'connected',+ login: 'example-user',+ install_url: 'https://github.com/apps/example/installations/new',+ installations: [{ id: 7, account: 'example-user', repositories: [{ id: 1, name: 'a/b' }] }],+ });+ const onDone = vi.fn();+ await render(() => {}, onDone);++ await vi.waitFor(() => expect(button(/^done$/i, dialog())).toBeDefined());+ expect(dialog().textContent).toContain('Connected as example-user');+ expect(dialog().textContent).toContain('a/b');+ expect(button(/^back$/i, dialog())).toBeUndefined();+ expect(button(/^disconnect$/i, dialog())).toBeUndefined();+ expect(dialog().textContent).not.toContain('Disconnecting removes credentials');++ await act(async () => button(/^done$/i, dialog())!.click());+ expect(onDone).toHaveBeenCalledOnce();+});++it("on a connector's page, Cancel stands in for Back before connecting", async () => {+ switchServers.getGitHubConnection.mockResolvedValue({+ status: 'not_connected',+ install_url: 'https://github.com/apps/example/installations/new',+ });+ const onBack = vi.fn();+ await render(onBack, () => {});++ await vi.waitFor(() => expect(button(/^connect github\s*$/i, dialog())).toBeDefined());+ expect(button(/^back$/i, dialog())).toBeUndefined();+ await act(async () => button(/^cancel$/i, dialog())!.click());+ expect(onBack).toHaveBeenCalledOnce();+});++it("says when an organization's single sign-on hides its installation", async () => {+ switchServers.getGitHubConnection.mockResolvedValue({+ status: 'connected',+ login: 'example-user',+ install_url: 'https://github.com/apps/example/installations/new',+ installations: [],+ sso_hidden_organizations: [21955855],+ });+ await render(() => {});++ await vi.waitFor(() =>+ expect(dialog().querySelector('[role="alert"]')?.textContent).toMatch(+ /single sign-on hides its installation/+ )+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/service-connect-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-connect-step.test.tsxnew file mode 100644index 000000000..b59742a16--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-connect-step.test.tsx@@ -0,0 +1,196 @@+/**+ * The generic sign-in step: it starts the sign-in at the vendor, waits for the+ * browser to finish, and shows the account connected once the server has kept+ * it, with no confirm in between. A refusal never strands the dialog: one the+ * server gives while connecting shows its reason and lets the dialog close,+ * and a cancel of a sign-in already gone is a cancel.+ */+import { type ReactNode, act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { RpcError, serializeRpcError } from '@shared/lib/ipc/rpc-error';++const switchServers = vi.hoisted(() => ({+ startServiceConnection: vi.fn(),+ getServiceFlow: vi.fn(),+ cancelServiceConnection: vi.fn(),+ disconnectService: vi.fn(),+}));++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { switchServers },+}));++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++import { serverServiceCalls } from '@renderer/features/switch-servers/service-calls';+import { ServiceConnectStep } from '@renderer/features/switch-servers/service-connect-step';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++const EXAMPLE: ConnectionCatalogEntry = {+ slug: 'example',+ name: 'Example',+ category: 'Development',+ description: 'Example access',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'not_connected',+ unavailable_reason: null,+ pass_through: false,+ token_lifetime: null,+ loopback_ports: null,+ key: null,+ external_identity: null,+ consent: null,+ workspace_enabled: null,+};++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ for (const mock of Object.values(switchServers)) mock.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(step: ReactNode): Promise<void> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <Dialog open>+ <DialogContent>{step}</DialogContent>+ </Dialog>+ )+ );+}++function button(name: RegExp, within: ParentNode = document): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++function dialog(): HTMLElement {+ return document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+}++function closable(): boolean {+ return dialog().querySelector('[data-slot="dialog-close"]') !== null;+}++function refusal(status: number, detail: string, retryable?: boolean): RpcError {+ return new RpcError(+ serializeRpcError(+ Object.assign(new Error(`Switch gateway returned ${status}`), {+ name: 'GatewayError',+ kind: 'http',+ status,+ detail,+ ...(retryable === undefined ? {} : { retryable }),+ })+ )+ );+}++function connectStep(onConnected: (warning: string | null) => void = () => {}) {+ return (+ <ServiceConnectStep+ calls={serverServiceCalls('server')}+ connection={EXAMPLE}+ onBack={() => {}}+ onConnected={onConnected}+ />+ );+}++/** Starts a sign-in; the flow then reads whatever `getServiceFlow` answers. */+async function signIn(): Promise<void> {+ switchServers.startServiceConnection.mockResolvedValue('flow-1');+ await vi.waitFor(() => expect(button(/^connect example/i, dialog())).toBeDefined());+ await act(async () => button(/^connect example/i, dialog())!.click());+ expect(switchServers.startServiceConnection).toHaveBeenCalledWith('server', 'example');+}++it('connects through the sign-in as soon as the server has kept the account', async () => {+ switchServers.getServiceFlow.mockResolvedValue({+ status: 'connected',+ account: '[email protected]',+ error: null,+ warning: 'Access stays a while.',+ });+ const onConnected = vi.fn();+ await render(connectStep(onConnected));+ await signIn();++ await vi.waitFor(() => expect(dialog().textContent).toMatch(/Example connected/));+ expect(onConnected).toHaveBeenCalledWith('Access stays a while.');+ expect(dialog().querySelector('[role="status"]')?.textContent).toBe('Access stays a while.');+ expect(button(/^disconnect$/i, dialog())).toBeDefined();+ expect(closable()).toBe(true);+});++it('waits on the browser, and cannot be closed meanwhile', async () => {+ switchServers.getServiceFlow.mockResolvedValue({+ status: 'pending',+ account: null,+ error: null,+ warning: null,+ });+ await render(connectStep());+ await signIn();++ await vi.waitFor(() => expect(dialog().textContent).toMatch(/Finish signing in in your browser/));+ expect(closable()).toBe(false);+ expect(button(/^cancel$/i, dialog())).toBeDefined();+});++it("shows the server's reason when it refuses the account, and lets the dialog close", async () => {+ switchServers.getServiceFlow.mockResolvedValue({+ status: 'failed',+ account: null,+ error:+ 'This Example account is already linked to another Switch user in this workspace. Remove that link first.',+ warning: null,+ });+ const onConnected = vi.fn();+ await render(connectStep(onConnected));+ await signIn();++ await vi.waitFor(() =>+ expect(dialog().querySelector('[role="alert"]')?.textContent).toContain(+ 'already linked to another Switch user'+ )+ );+ expect(onConnected).not.toHaveBeenCalled();+ expect(closable()).toBe(true);+ expect(button(/^cancel$/i, dialog())).toBeDefined();+});++it('counts a cancel of a sign-in the server already dropped as cancelled', async () => {+ switchServers.getServiceFlow.mockResolvedValue({+ status: 'pending',+ account: null,+ error: null,+ warning: null,+ });+ switchServers.cancelServiceConnection.mockRejectedValue(refusal(410, 'Sign-in not found.'));+ await render(connectStep());+ await signIn();++ await vi.waitFor(() => expect(button(/^cancel$/i, dialog())).toBeDefined());+ await act(async () => button(/^cancel$/i, dialog())!.click());+ await vi.waitFor(() => expect(button(/^connect example/i, dialog())).toBeDefined());+ expect(dialog().querySelector('[role="alert"]')).toBeNull();+ expect(closable()).toBe(true);+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/service-grants-section.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-grants-section.test.tsxindex 71aa4c301..7be83a622 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/service-grants-section.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-grants-section.test.tsx@@ -10,7 +10,8 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';-import { OWNER_ONLY_POLICY, type ServiceGrants } from '@shared/core/switch-servers/service-grants';+import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';+import type { ServiceGrants } from '@shared/core/switch-servers/service-grants';const agents = vi.hoisted(() => ({ getAgents: vi.fn() }));const workspaces = vi.hoisted(() => ({@@ -140,7 +141,7 @@ it('makes the agent owner-only from the warning', async () => {expect(workspaces.updateAddressingPolicy).toHaveBeenCalledWith({workspaceId: 'workspace',agentId: 'agent',- policy: OWNER_ONLY_POLICY,+ policy: ownerOnlyPolicy(),}));});@@ -153,7 +154,7 @@ it('says what removing a grant does, and does not, on your computer', async () =expect(button(el, 'Remove')!.title).toContain('may still use your own sign-in');await act(async () => button(el, 'Remove')!.click());await vi.waitFor(() =>- expect(el.textContent).toContain('Removing a grant stops Switch giving this access.')+ expect(el.textContent).toContain('Removing it stops Switch giving this access.'));expect(workspaces.removeServiceGrant).toHaveBeenCalledWith({workspaceId: 'workspace',@@ -169,23 +170,26 @@ it('grants GitHub on the repositories picked, for reading unless asked', async (});const el = await render();- await vi.waitFor(() => expect(el.querySelector('[aria-label="GitHub account"]')).not.toBeNull());- await act(async () => el.querySelector<HTMLElement>('[aria-label="GitHub account"]')!.click());- await vi.waitFor(() =>- expect(document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0)- );- const account = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(- (option) => option.textContent?.trim() === 'example-org'- );- await act(async () => account!.click());- await vi.waitFor(() => expect(el.textContent).toContain('docs'));-- const docs = [...el.querySelectorAll('label')].find((label) =>- label.textContent?.includes('docs')+ // One account: nothing to choose there. Nothing is chosen until a repository is.+ const search = () => el.querySelector<HTMLInputElement>('input[aria-label="Add repository"]');+ await vi.waitFor(() => expect(search()).not.toBeNull());+ expect(el.querySelector('[aria-label="GitHub account"]')).toBeNull();+ expect(el.textContent).toContain('Turn GitHub on for helper');+ expect(el.textContent).toContain('No repository chosen.');+ expect(button(el, 'Turn on')?.disabled).toBe(true);+ await act(async () => {+ const input = search()!;+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ setter.call(input, 'docs');+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await vi.waitFor(() => expect(el.textContent).toContain('example-org/docs'));+ const docs = [...el.querySelectorAll<HTMLButtonElement>('[role="option"]')].find((option) =>+ option.textContent?.includes('docs'));- await act(async () => docs!.querySelector<HTMLElement>('[role="checkbox"], button')!.click());- expect(button(el, 'Grant')?.disabled).toBe(false);- await act(async () => button(el, 'Grant')!.click());+ await act(async () => docs!.click());+ expect(button(el, 'Turn on')?.disabled).toBe(false);+ await act(async () => button(el, 'Turn on')!.click());await vi.waitFor(() =>expect(workspaces.setServiceGrant).toHaveBeenCalledWith({@@ -221,6 +225,20 @@ it('draws nothing, and asks nothing, where the server has service connections ofexpect(workspaces.getServiceGrants).not.toHaveBeenCalled();});+it('changes which repositories a GitHub grant reaches, in a form that never says "grant"', async () => {+ workspaces.getServiceGrants.mockResolvedValue(GRANTED);+ const el = await render();++ await vi.waitFor(() => expect(button(el, 'Change')).toBeDefined());+ await act(async () => button(el, 'Change')!.click());+ await vi.waitFor(() =>+ expect(el.textContent).toContain('Change which repositories helper reaches')+ );+ const form = button(el, 'Save')!.closest('.rounded-lg')!;+ expect(form.textContent).toContain('Change which repositories helper reaches');+ expect(form.textContent).not.toMatch(/\bgrant/i);+});+it('says so when the grants could not be loaded', async () => {workspaces.getServiceGrants.mockRejectedValue(new Error('Switch gateway returned 500'));const el = await render();@@ -280,6 +298,8 @@ function onOff(loopback_ports: null,key: null,external_identity: null,+ consent: null,+ workspace_enabled: null,...overrides,};}@@ -365,7 +385,7 @@ it('cannot turn on a service that is not connected, or not available, and says wawait vi.waitFor(() => expect(exampleSwitch(el)).not.toBeNull());expect(exampleSwitch(el)!.getAttribute('aria-disabled') ?? '').not.toBe('false');- expect(el.textContent).toContain("first connect it from the server's Connections");+ expect(el.textContent).toContain('first connect it from Connectors');expect(el.textContent).toContain('Switched off on this server.');await act(async () => exampleSwitch(el)!.click());await act(async () => el.querySelector<HTMLElement>('[aria-label="Other for helper"]')!.click());diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/service-key-step.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-key-step.test.tsxnew file mode 100644index 000000000..ef996680f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/service-key-step.test.tsx@@ -0,0 +1,295 @@+/**+ * Connecting a service with a key: a form built from the catalog entry, the+ * keys typed into password inputs and cleared once sent, the server's refusal+ * shown as it said it, and a connected key shown by whose it is. Opened to+ * replace a connected key, it opens on the form and ends on Done.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { RpcError, serializeRpcError } from '@shared/lib/ipc/rpc-error';++const switchServers = vi.hoisted(() => ({+ startServiceConnection: vi.fn(),+ connectServiceWithKey: vi.fn(),+ disconnectService: vi.fn(),+}));+const openExternalUrl = vi.hoisted(() => vi.fn());++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { switchServers },+}));++vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));++vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));++import { serverServiceCalls } from '@renderer/features/switch-servers/service-calls';+import { ServiceKeyStep } from '@renderer/features/switch-servers/service-key-step';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';++const API_KEY = 'synthetic-datadog-api-key';+const APP_KEY = 'synthetic-datadog-application-key';++/** A service connected with a key, as the catalog describes Datadog's. */+function keyed(status: ConnectionCatalogEntry['status']): ConnectionCatalogEntry {+ return {+ slug: 'datadog',+ name: 'Datadog',+ category: 'Observability',+ description: 'Datadog access',+ enabled: true,+ auth_type: 'api_key',+ connectable: true,+ status,+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: 3600,+ loopback_ports: null,+ external_identity: status === 'connected' ? 'Datadog key · datadoghq.eu' : null,+ consent: null,+ workspace_enabled: null,+ key: {+ fields: [+ {+ name: 'api_key',+ label: 'API key',+ secret: true,+ help: 'Organization Settings, API Keys.',+ choices: null,+ },+ {+ name: 'application_key',+ label: 'Application key',+ secret: true,+ help: 'Personal Settings, Application Keys.',+ choices: null,+ },+ {+ name: 'site',+ label: 'Datadog site',+ secret: false,+ help: 'The address you open Datadog at.',+ choices: ['datadoghq.com', 'datadoghq.eu'],+ },+ ],+ help_url: 'https://docs.datadoghq.com/account_management/api-app-keys/',+ },+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ for (const mock of Object.values(switchServers)) mock.mockReset();+ openExternalUrl.mockReset().mockResolvedValue(true);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(+ status: ConnectionCatalogEntry['status'] = 'not_connected',+ replacing = false,+ onBack: () => void = () => {}+): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const connection = keyed(status);+ await act(async () =>+ root!.render(+ <Dialog open>+ <DialogContent>+ <ServiceKeyStep+ calls={serverServiceCalls('server')}+ connection={connection}+ form={connection.key!}+ replacing={replacing}+ onBack={onBack}+ onConnected={() => {}}+ />+ </DialogContent>+ </Dialog>+ )+ );+ await vi.waitFor(() =>+ expect(dialog().textContent).toMatch(+ /Connect Datadog|Datadog connected|Replace the Datadog key/+ )+ );+ return dialog();+}++function button(name: RegExp, within: ParentNode = document): HTMLButtonElement | undefined {+ return [...within.querySelectorAll('button')].find((b) => name.test(b.textContent ?? ''));+}++function dialog(): HTMLElement {+ return document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+}++function input(within: ParentNode, label: string): HTMLInputElement {+ const id = [...within.querySelectorAll('label')].find((l) => l.textContent === label)!.htmlFor;+ return within.querySelector<HTMLInputElement>(`#${id}`)!;+}++async function type(target: HTMLInputElement, value: string) {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(target, value);+ target.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++async function pick(within: ParentNode, label: string, choice: string) {+ await act(async () => within.querySelector<HTMLElement>(`[aria-label="${label}"]`)!.click());+ await vi.waitFor(() =>+ expect(document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0)+ );+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (candidate) => candidate.textContent?.trim() === choice+ )!;+ await act(async () => option.click());+}++async function fillKey(step: HTMLElement) {+ await type(input(step, 'API key'), API_KEY);+ await type(input(step, 'Application key'), APP_KEY);+ await pick(step, 'Datadog site', 'datadoghq.eu');+}++it('is a form built from the catalog entry, not the sign-in', async () => {+ const step = await render();++ expect(step.textContent).toMatch(/Connect Datadog/);+ expect(input(step, 'API key').type).toBe('password');+ expect(input(step, 'Application key').type).toBe('password');+ expect(step.querySelector('[aria-label="Datadog site"]')).not.toBeNull();+ expect(step.textContent).toContain('Organization Settings, API Keys.');+ expect(step.textContent).toContain('The address you open Datadog at.');+ expect(step.textContent).toContain(+ "Switch checks the key with Datadog, stores it encrypted, and never shows it again. The agent can do whatever this key allows. Keys don't expire; disconnecting removes the key from Switch but can't revoke it at Datadog — revoke it there too."+ );+ expect(switchServers.startServiceConnection).not.toHaveBeenCalled();+ await act(async () => button(/How to make a Datadog key/, step)!.click());+ expect(openExternalUrl).toHaveBeenCalledWith(+ 'https://docs.datadoghq.com/account_management/api-app-keys/',+ expect.any(String)+ );+ expect(button(/^connect datadog$/i, step)?.disabled).toBe(true);+});++it('connects with the fields typed and picked, and shows whose key it is', async () => {+ switchServers.connectServiceWithKey.mockResolvedValue({+ warning: null,+ external_identity: 'Datadog key · datadoghq.eu',+ });+ switchServers.disconnectService.mockResolvedValue({+ warning: 'Switch has forgotten the Datadog key but cannot revoke it.',+ });+ const step = await render();+ await fillKey(step);++ await vi.waitFor(() => expect(button(/^connect datadog$/i, step)?.disabled).toBe(false));+ await act(async () => button(/^connect datadog$/i, step)!.click());+ expect(switchServers.connectServiceWithKey).toHaveBeenCalledWith('server', 'datadog', {+ api_key: API_KEY,+ application_key: APP_KEY,+ site: 'datadoghq.eu',+ });+ await vi.waitFor(() => expect(dialog().textContent).toMatch(/Datadog connected/));+ expect(dialog().textContent).toContain('Connected with Datadog key · datadoghq.eu');+ expect(dialog().innerHTML).not.toContain(API_KEY);+ expect(dialog().innerHTML).not.toContain(APP_KEY);++ await act(async () => button(/^replace key$/i, dialog())!.click());+ expect(input(dialog(), 'API key').value).toBe('');+ expect(input(dialog(), 'Application key').value).toBe('');++ await act(async () => button(/^disconnect$/i, dialog())!.click());+ expect(switchServers.disconnectService).toHaveBeenCalledWith('server', 'datadog');+ await vi.waitFor(() =>+ expect(dialog().querySelector('[role="status"]')?.textContent).toBe(+ 'Switch has forgotten the Datadog key but cannot revoke it.'+ )+ );+ expect(dialog().textContent).toMatch(/Connect Datadog/);+});++it('shows Switch’s refusal of a key, and clears the keys typed', async () => {+ switchServers.connectServiceWithKey.mockRejectedValue(+ new RpcError(+ serializeRpcError(+ Object.assign(new Error('Switch gateway returned 422'), {+ name: 'GatewayError',+ kind: 'http',+ status: 422,+ detail: 'Datadog refused the key (HTTP 403). Check that it is right.',+ })+ )+ )+ );+ const step = await render();+ await fillKey(step);+ await act(async () => button(/^connect datadog$/i, step)!.click());++ await vi.waitFor(() =>+ expect(dialog().querySelector('[role="alert"]')?.textContent).toContain(+ 'Datadog refused the key (HTTP 403). Check that it is right.'+ )+ );+ expect(input(dialog(), 'API key').value).toBe('');+ expect(input(dialog(), 'Application key').value).toBe('');+ expect(dialog().querySelector('[aria-label="Datadog site"]')?.textContent).toContain(+ 'datadoghq.eu'+ );+ expect(dialog().textContent).toMatch(/Connect Datadog/);+});++it('shows a connected key service as connected, with whose key it is', async () => {+ const step = await render('connected');+ expect(step.textContent).toMatch(/Datadog connected/);+ expect(step.textContent).toContain('Connected with Datadog key · datadoghq.eu');+ expect(button(/^disconnect$/i, step)).toBeDefined();+ expect(step.querySelector('[aria-label="Datadog key"]')).toBeNull();+});++it('opened to replace a key, opens on the form and ends on Done', async () => {+ switchServers.connectServiceWithKey.mockResolvedValue({+ warning: null,+ external_identity: 'Datadog key · datadoghq.com',+ });+ const onBack = vi.fn();+ const step = await render('connected', true, onBack);++ expect(step.textContent).toMatch(/Replace the Datadog key/);+ expect(step.querySelector('[aria-label="Datadog key"]')).not.toBeNull();+ expect(button(/^disconnect$/i, step)).toBeUndefined();+ await type(input(step, 'API key'), API_KEY);+ await type(input(step, 'Application key'), APP_KEY);+ await pick(step, 'Datadog site', 'datadoghq.com');+ await vi.waitFor(() => expect(button(/^replace key$/i, step)?.disabled).toBe(false));+ await act(async () => button(/^replace key$/i, step)!.click());++ expect(switchServers.connectServiceWithKey).toHaveBeenCalledWith('server', 'datadog', {+ api_key: API_KEY,+ application_key: APP_KEY,+ site: 'datadoghq.com',+ });+ await vi.waitFor(() => expect(dialog().textContent).toMatch(/Datadog connected/));+ expect(dialog().textContent).toContain('Connected with Datadog key · datadoghq.com');+ expect(dialog().innerHTML).not.toContain(API_KEY);+ expect(button(/^replace key$/i, dialog())).toBeUndefined();+ await act(async () => button(/^done$/i, dialog())!.click());+ expect(onBack).toHaveBeenCalledOnce();+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/connector-apps.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/connector-apps.test.tsnew file mode 100644index 000000000..def35ac95--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/connector-apps.test.ts@@ -0,0 +1,420 @@+import { describe, expect, it } from 'vitest';+import {+ actionLabel,+ appDetails,+ attention,+ audienceText,+ cardOrder,+ cardState,+ configuredSentence,+ menuActions,+ menuLabel,+ moveChecklist,+ peopleIn,+ primaryAction,+ removeWarning,+ secretSummary,+ sentBackTo,+ setupInstructions,+ stateLabel,+ switchWarning,+ tileAction,+ tileStanding,+} from '@renderer/features/admin/connector-apps';+import type { ConnectorApp } from '@shared/core/switch-servers/connector-apps';++/** A connector app as the server lists it, with placeholder values. */+function app(overrides: Partial<ConnectorApp> = {}): ConnectorApp {+ return {+ slug: 'google-workspace',+ name: 'Google Workspace',+ kind: 'oauth_client',+ source: 'saved',+ configuration_variables: ['GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH'],+ deprecated: false,+ client_id: 'example-client-id',+ saved_client_id: 'example-client-id',+ fields: {},+ secrets: { client_secret: { set: true, last4: 'ab12' } },+ saved_ignored: false,+ unreadable: false,+ load_error: null,+ redirect_uri:+ 'https://switch.example.test/gateway/service-connections/google-workspace/flows/callback',+ setup_blocked: null,+ install_url: null,+ updated_by_name: 'Ada',+ updated_at: '2026-10-15T10:00:00Z',+ connected_members: 12,+ workspaces: 3,+ stale_connections: 0,+ ...overrides,+ };+}++const PUBLIC_URL = 'https://switch.example.test';++const NONE = app({+ source: 'none',+ client_id: null,+ saved_client_id: null,+ secrets: { client_secret: { set: false, last4: null } },+ connected_members: 0,+ workspaces: 0,+});+const CONFIGURED = app({ source: 'configuration', saved_client_id: null });+const GITHUB = app({+ slug: 'github',+ name: 'GitHub',+ kind: 'github_app',+ configuration_variables: ['GITHUB_APP_CONFIG_PATH', 'GITHUB_APP_PRIVATE_KEY_PATH'],+ fields: { slug: 'example-app' },+ secrets: {+ client_secret: { set: true, last4: 'cd34' },+ private_key: { set: true, fingerprint: 'SHA256:example' },+ },+});++describe('card state', () => {+ it('is one of four', () => {+ expect(cardState(app(), null)).toBe('ready');+ expect(cardState(NONE, null)).toBe('not_set_up');+ expect(cardState(CONFIGURED, null)).toBe('configured');+ expect(cardState(app(), 'Google says no.')).toBe('attention');+ expect(+ ['ready', 'not_set_up', 'configured', 'attention'].map((s) => stateLabel(s as never))+ ).toEqual(['Ready', 'Not set up', 'Set on the server', 'Needs attention']);+ });++ it('names one cause and one fix for each kind of attention', () => {+ expect(attention(app(), "Google doesn't recognise this client.")).toEqual({+ cause: 'check_failed',+ sentence: "Google doesn't recognise this client.",+ action: 'update_secret',+ });+ expect(attention(app({ source: 'none', unreadable: true, load_error: 'x' }), null)).toEqual({+ cause: 'unreadable',+ sentence: "Switch can't read the saved secret any more.",+ action: 'enter_again',+ });+ expect(attention(app({ source: 'none', load_error: 'Not RSA.' }), null)?.cause).toBe(+ 'load_error'+ );+ expect(+ attention(+ app({ source: 'configuration', saved_ignored: true, saved_client_id: 'other' }),+ null+ )+ ).toEqual({+ cause: 'saved_ignored',+ sentence:+ 'Saved here, but GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH is still set, so Switch uses that. Remove it and restart Switch.',+ action: 'manage_here',+ });+ expect(attention(app({ stale_connections: 5 }), null)).toEqual({+ cause: 'stale',+ sentence: '5 people still need to reconnect.',+ action: null,+ });+ expect(attention(app({ stale_connections: 1 }), null)?.sentence).toBe(+ '1 person still needs to reconnect.'+ );+ expect(attention(app(), null)).toBeNull();+ });++ it('does not call a copied-in app waiting for its restart a problem', () => {+ const waiting = app({ source: 'configuration', saved_ignored: true });+ expect(attention(waiting, null)).toBeNull();+ expect(cardState(waiting, null)).toBe('configured');+ expect(primaryAction(waiting, null)).toBeNull();+ });+});++describe('set-up blocked by the server', () => {+ const BLOCKED =+ 'GitHub needs GATEWAY_PUBLIC_URL to be an https address, to send people back to Switch.';++ it("is the card's one sentence, with Set up as the fix", () => {+ const github = {+ ...GITHUB,+ source: 'none' as const,+ client_id: null,+ redirect_uri: null,+ setup_blocked: BLOCKED,+ };+ expect(attention(github, null)).toEqual({+ cause: 'setup_blocked',+ sentence: BLOCKED,+ action: 'set_up',+ });+ expect(primaryAction(github, null)).toBe('set_up');+ });++ it('leaves an app set on the server working', () => {+ const configured = { ...GITHUB, source: 'configuration' as const, setup_blocked: BLOCKED };+ expect(attention(configured, null)).toBeNull();+ expect(cardState(configured, null)).toBe('configured');+ });++ it('names where people are sent back to', () => {+ expect(sentBackTo('https://switch.example.test')).toBe(+ 'People are sent back to https://switch.example.test.'+ );+ });+});++describe('set on the server', () => {+ it('names the variable, and how to change it or move off it', () => {+ expect(configuredSentence(CONFIGURED)).toBe(+ 'From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here.'+ );+ expect(configuredSentence({ ...GITHUB, source: 'configuration', saved_client_id: null })).toBe(+ 'From GITHUB_APP_CONFIG_PATH and GITHUB_APP_PRIVATE_KEY_PATH. Change them there, or remove them to manage it here.'+ );+ });++ it('says a copy saved here under the same client is used once the variable goes', () => {+ const copied = app({ source: 'configuration', saved_ignored: true });+ expect(configuredSentence(copied)).toBe(+ 'From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here. A copy is saved here, same client. Remove the variable and restart Switch to use the copy.'+ );+ expect(configuredSentence(copied)).not.toMatch(/waiting for restart/);+ });++ it('leaves a copy of another client to the attention sentence', () => {+ const other = app({ source: 'configuration', saved_ignored: true, saved_client_id: 'other' });+ expect(configuredSentence(other)).toBe(+ 'From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here.'+ );+ expect(attention(other, null)?.cause).toBe('saved_ignored');+ });+});++describe('order', () => {+ it('puts what needs attention first, then not set up, then working', () => {+ const stale = app({ slug: 'a', name: 'A', stale_connections: 2 });+ const failing = app({ slug: 'b', name: 'B' });+ const ordered = cardOrder([app({ slug: 'z', name: 'Z' }), NONE, CONFIGURED, stale, failing], {+ b: 'No.',+ });+ expect(ordered.map((a) => a.name)).toEqual([+ 'A',+ 'B',+ 'Google Workspace',+ 'Google Workspace',+ 'Z',+ ]);+ expect(ordered[2]!.source).toBe('none');+ expect(ordered[3]!.source).toBe('configuration');+ });+});++describe('actions', () => {+ it('offers one obvious button per state', () => {+ expect(primaryAction(NONE, null)).toBe('set_up');+ expect(actionLabel(NONE, 'set_up')).toBe('Set up Google Workspace');+ expect(actionLabel(GITHUB, 'set_up')).toBe('Set up GitHub');+ expect(primaryAction(CONFIGURED, null)).toBe('manage_here');+ expect(primaryAction(app(), null)).toBe('check');+ expect(primaryAction(app(), 'No.')).toBe('update_secret');+ expect(primaryAction(app({ source: 'none', unreadable: true }), null)).toBe('enter_again');+ expect(primaryAction(app({ stale_connections: 3 }), null)).toBe('check');+ expect(primaryAction(app({ source: 'configuration', deprecated: true }), null)).toBeNull();+ });++ it('splits changes by what they do to the people connected', () => {+ expect(menuActions(app())).toEqual(['update_secret', 'switch_app', 'remove']);+ expect(menuActions(NONE)).toEqual([]);+ expect(menuActions(CONFIGURED)).toEqual([]);+ expect(menuActions(app({ source: 'none', unreadable: true }))).toEqual(['remove']);+ expect(menuLabel(app(), 'update_secret')).toBe('Update secret');+ expect(menuLabel(GITHUB, 'update_secret')).toBe('Update secret or private key');+ expect(menuLabel(app(), 'switch_app')).toBe('Use a different app');+ });+});++describe('wording', () => {+ it('counts people and workspaces', () => {+ expect(peopleIn({ connected_members: 12, workspaces: 3 })).toBe('12 people in 3 workspaces');+ expect(peopleIn({ connected_members: 1, workspaces: 1 })).toBe('1 person in 1 workspace');+ });++ it("warns before switching apps, GitHub's repositories included", () => {+ expect(switchWarning(app(), { connected_members: 12, workspaces: 3 })).toEqual([+ 'Everyone connected through the current app (12 people in 3 workspaces) will need to reconnect, and their agents lose Google Workspace until they do.',+ "If the old app's secret leaked, also delete it at Google: tokens already handed to agents stay valid for up to an hour.",+ ]);+ expect(switchWarning(GITHUB, { connected_members: 2, workspaces: 1 })).toContain(+ 'They will also need to choose their repositories again.'+ );+ });++ it('says who loses a removed app', () => {+ expect(removeWarning(app())).toBe(+ 'Nobody will be able to connect Google Workspace, and the 12 people connected now lose it. They can still disconnect.'+ );+ expect(removeWarning(NONE)).toBe('Nobody will be able to connect Google Workspace.');+ });++ it('shows how to recognise a secret, never the secret', () => {+ expect(secretSummary(app())).toBe('Secret ends in ab12');+ expect(secretSummary(GITHUB)).toBe('Secret ends in cd34 · Key SHA256:example');+ expect(secretSummary(NONE)).toBeNull();+ });++ it('changes only the instructions with who will connect', () => {+ const internal = setupInstructions(NONE, 'internal', PUBLIC_URL);+ const external = setupInstructions(NONE, 'external', PUBLIC_URL);+ expect(internal[2]!.text).toBe(audienceText('internal'));+ expect(external[2]!.text).toBe(audienceText('external'));+ expect(internal.filter((_, i) => i !== 2)).toEqual(external.filter((_, i) => i !== 2));+ expect(audienceText('external')).toMatch(/add the people who will try it as test users/);+ expect(audienceText('external')).toMatch(/reconnect every 7 days/);+ expect(audienceText('external')).toMatch(/security assessment renewed every year/);+ });++ it("walks Google's set-up page by page, each with its link", () => {+ const steps = setupInstructions(NONE, 'internal', PUBLIC_URL);+ expect(steps.map((s) => s.link?.href ?? null)).toEqual([+ 'https://console.cloud.google.com/projectcreate',+ 'https://console.cloud.google.com/auth/branding',+ 'https://console.cloud.google.com/auth/audience',+ 'https://console.cloud.google.com/auth/clients',+ null,+ 'https://console.cloud.google.com/apis/library',+ ]);+ expect(steps[1]!.text).toMatch(/app name .* support email/);+ expect(steps[4]!.copy).toBe(NONE.redirect_uri);+ expect(steps[5]!.text).toBe(+ 'Enable the Google Drive, Docs, Sheets, Slides and Calendar APIs for the project.'+ );+ });++ it("walks GitHub's form from top to bottom, with what to paste", () => {+ const steps = setupInstructions(GITHUB, 'internal', PUBLIC_URL);+ expect(steps[0]!.link).toEqual({+ label: 'Open GitHub',+ href: 'https://github.com/settings/apps/new',+ });+ expect(steps.slice(1).every((s) => s.link === null)).toBe(true);+ expect(steps.map((s) => s.copy).filter((c) => c !== null)).toEqual([+ PUBLIC_URL,+ GITHUB.redirect_uri,+ ]);+ const texts = steps.map((s) => s.text);+ expect(texts[1]).toMatch(/^Set the Homepage URL/);+ expect(texts[2]).toMatch(/^Set the Callback URL/);+ expect(texts[3]).toMatch(/Expire user authorization tokens turned on/);+ expect(texts[4]).toMatch(/^Under Webhook, untick Active/);+ expect(texts[5]).toMatch(/Contents and Pull requests to Read and write/);+ expect(texts[6]).toMatch(/Where can this GitHub App be installed, choose Any account/);+ expect(texts[7]).toMatch(/generate a client secret, then a private key/);+ });++ it("links only to the vendors' public pages", () => {+ const links = [+ ...setupInstructions(NONE, 'external', PUBLIC_URL),+ ...setupInstructions(GITHUB, 'internal', PUBLIC_URL),+ ].flatMap((s) => (s.link ? [s.link.href] : []));+ expect(+ links.every((href) => /^https:\/\/(console\.cloud\.google\.com|github\.com)\//.test(href))+ ).toBe(true);+ });+});++describe('moving off configuration', () => {+ it('ticks copying in once the saved app matches, and names the Helm value', () => {+ 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."+ );+ const after = moveChecklist(app({ source: 'configuration', saved_ignored: true }));+ expect(after.map((item) => item.done)).toEqual([true, false, false]);+ });+});++describe('a tile', () => {+ it('says what needs doing, or who the app serves', () => {+ expect(tileStanding(NONE, null)).toBe(+ "People can't connect Google Workspace until you add Switch's Google client."+ );+ expect(tileStanding(app(), 'Google refused the secret.')).toBe('Google refused the secret.');+ expect(tileStanding(app(), null)).toBe('Used by 12 people in 3 workspaces');+ expect(tileStanding(CONFIGURED, null)).toBe('Used by 12 people in 3 workspaces');+ });++ it('carries only the one thing that needs doing', () => {+ expect(tileAction(NONE, null)).toBe('set_up');+ expect(tileAction(app(), 'Google refused the secret.')).toBe('update_secret');+ expect(tileAction(app({ unreadable: true }), null)).toBe('enter_again');+ // Checking and moving off configuration are the profile's.+ expect(tileAction(app(), null)).toBeNull();+ expect(tileAction(CONFIGURED, null)).toBeNull();+ });+});++describe("an app's details", () => {+ const date = (iso: string) => `on ${iso}`;+ const shape = (sections: ReturnType<typeof appDetails>) =>+ sections.map((section) => [section.title, section.rows.map((r) => r.label)]);++ it('are in the same three sections for every app, each with what it has', () => {+ expect(shape(appDetails(app(), PUBLIC_URL, date))).toEqual([+ ['Credentials', ['Client ID', 'Client secret']],+ ['Setup', ['Source', 'Redirect URI', 'Last changed']],+ ['For people who connect', ['Sent back to']],+ ]);+ const installed = {+ ...GITHUB,+ install_url: 'https://github.com/apps/example-app/installations/new',+ };+ expect(shape(appDetails(installed, PUBLIC_URL, date))).toEqual([+ ['Credentials', ['Client ID', 'GitHub App', 'Client secret', 'Private key']],+ ['Setup', ['Source', 'Callback URL', 'Last changed']],+ ['For people who connect', ['Sent back to', 'Install page']],+ ]);+ });++ it('show identifiers to copy, a secret by its last characters, and never more', () => {+ const [credentials] = appDetails(GITHUB, PUBLIC_URL, date);+ const byLabel = Object.fromEntries(credentials!.rows.map((r) => [r.label, r]));+ expect(byLabel['Client ID']).toMatchObject({ code: true });+ expect(byLabel['Client secret']).toMatchObject({+ value: expect.stringMatching(/^•••• /),+ code: false,+ });+ expect(byLabel['Private key']).toMatchObject({ code: true });+ expect(byLabel['GitHub App']!.href).toBe('https://github.com/apps/example-app');+ });++ it('name a value an app added later from its key', () => {+ const later = app({+ fields: { tenant_domain: 'example.test' } as ConnectorApp['fields'],+ secrets: { signing_key: { set: true, last4: 'zz99' } },+ });+ expect(appDetails(later, null, date)[0]!.rows.map((r) => [r.label, r.value])).toEqual([+ ['Client ID', 'example-client-id'],+ ['Tenant domain', 'example.test'],+ ['Signing key', '•••• zz99'],+ ]);+ });++ it('say where an app comes from, who changed it, and who must reconnect', () => {+ const setup = (a: ConnectorApp) =>+ Object.fromEntries(appDetails(a, null, date)[1]!.rows.map((r) => [r.label, r.value]));+ expect(setup(app())).toMatchObject({+ Source: 'Saved in Switch',+ 'Last changed': 'Ada · on 2026-10-15T10:00:00Z',+ });+ expect(setup(CONFIGURED).Source).toBe(+ 'Server configuration (GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH)'+ );+ expect(setup(NONE)).toMatchObject({ Source: 'Not set up' });+ const people = appDetails(app({ stale_connections: 2 }), PUBLIC_URL, date).at(-1)!;+ expect(people.rows.map((r) => [r.label, r.value])).toEqual([+ ['Sent back to', PUBLIC_URL],+ ['Need to reconnect', '2 people'],+ ]);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.tsnew file mode 100644index 000000000..218771fd0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/connectors.test.ts@@ -0,0 +1,631 @@+import { describe, expect, it } from 'vitest';+import {+ type ConnectFlowState,+ canCloseConnectFlow,+ connectFlowReducer,+ initialConnectFlow,+} from '@renderer/features/connectors/connect-flow';+import { connectorCardState } from '@renderer/features/connectors/connector-card-state';+import {+ disconnectCopy,+ switchOffConfirmation,+ workspaceSwitchNote,+} from '@renderer/features/connectors/connector-copy';+import {+ cardQuickAction,+ connectedAsLine,+ connectorsInTab,+ connectorsPageAccess,+ keyAccessText,+ profileConnectAction,+ signInLabel,+ tokenLifetimeLabel,+ workspaceOffNotice,+} from '@renderer/features/connectors/connectors-catalog';+import {+ repositoriesActionLabel,+ repositoriesSummary,+} from '@renderer/features/connectors/github-access';+import {+ emptyGitHubGrant,+ githubChoiceSummary,+ githubGrantResources,+ withEveryRepository,+ withInstallation,+ withRepository,+ withoutRepository,+} from '@renderer/features/connectors/github-grant';+import {+ OPEN_AGENT_NOTE,+ addableAgents,+ agentsSummary,+ agentsUnlistedText,+ noAgentsText,+ offersAddAgent,+} from '@renderer/features/connectors/grant-agents';+import { workspaceNavViews } from '@renderer/features/sidebar/workspace-nav-views';+import {+ FLAGS_NOT_READ_YET,+ allFeatureFlagsOff,+ type ServerFeatureFlags,+} from '@shared/core/feature-flags/feature-flags';+import type { ConnectionCatalogEntry } from '@shared/core/switch-servers/connection-catalog';+import { RpcError, serializeRpcError } from '@shared/lib/ipc/rpc-error';++function entry(overrides: Partial<ConnectionCatalogEntry> = {}): ConnectionCatalogEntry {+ return {+ slug: 'example',+ name: 'Example',+ category: 'Project management',+ description: 'Example work items.',+ enabled: true,+ auth_type: 'oauth',+ connectable: true,+ status: 'not_connected',+ unavailable_reason: null,+ pass_through: true,+ token_lifetime: 3600,+ loopback_ports: null,+ key: null,+ external_identity: null,+ consent: null,+ workspace_enabled: true,+ ...overrides,+ };+}++describe('the state a connector card shows', () => {+ it('shows each state on its own', () => {+ expect(connectorCardState(entry({ status: 'coming_soon', enabled: false })).kind).toBe(+ 'coming_soon'+ );+ expect(+ connectorCardState(entry({ unavailable_reason: 'Maintenance', connectable: false }))+ ).toMatchObject({ kind: 'unavailable', detail: 'Maintenance' });+ expect(connectorCardState(entry({ workspace_enabled: false }))).toMatchObject({+ kind: 'workspace_off',+ label: 'Off in this workspace',+ detail: 'A workspace admin has switched it off.',+ });+ expect(connectorCardState(entry({ status: 'needs_reauthorization' }))).toMatchObject({+ kind: 'reconnect',+ label: 'Reconnect needed',+ detail: 'Switch can no longer use your Example connection. Connect again.',+ tone: 'problem',+ });+ expect(connectorCardState(entry({ status: 'error' }))).toMatchObject({+ kind: 'reconnect',+ label: 'Connection failed',+ });+ expect(connectorCardState(entry({ status: 'connected' })).kind).toBe('connected');+ expect(connectorCardState(entry()).kind).toBe('connect');+ });++ it('reads a server without the workspace switch as on', () => {+ expect(connectorCardState(entry({ workspace_enabled: null })).kind).toBe('connect');+ expect(connectorCardState(entry({ workspace_enabled: null, status: 'connected' })).kind).toBe(+ 'connected'+ );+ });++ it('picks the first that applies when several do', () => {+ const everything = entry({+ status: 'needs_reauthorization',+ unavailable_reason: 'Maintenance',+ workspace_enabled: false,+ });+ expect(connectorCardState({ ...everything, status: 'coming_soon' }).kind).toBe('coming_soon');+ // The server's reason wins over the workspace's switch.+ expect(connectorCardState(everything).kind).toBe('unavailable');+ // Off in the workspace wins over a sign-in that needs renewing.+ expect(connectorCardState({ ...everything, unavailable_reason: null }).kind).toBe(+ 'workspace_off'+ );+ expect(+ connectorCardState({ ...everything, unavailable_reason: null, status: 'connected' }).kind+ ).toBe('workspace_off');+ });+});++describe('the Yours and Discover tabs', () => {+ const catalog = [+ entry({ slug: 'atlassian', name: 'Atlassian', category: 'Project management' }),+ entry({+ slug: 'datadog',+ name: 'Datadog',+ category: 'Observability',+ description: 'Monitors, logs and incidents.',+ status: 'connected',+ }),+ entry({ slug: 'github', name: 'GitHub', category: 'Source control', status: 'error' }),+ entry({+ slug: 'jira-ish',+ name: 'Linear',+ category: 'Project management',+ status: 'needs_reauthorization',+ }),+ entry({ slug: 'notion', name: 'Notion', category: 'Docs', status: 'coming_soon' }),+ ];+ const names = (list: ConnectionCatalogEntry[]) => list.map((item) => item.name);++ it('puts every connection the person has on Yours, working or not', () => {+ expect(names(connectorsInTab(catalog, 'yours', ''))).toEqual(['Datadog', 'GitHub', 'Linear']);+ });++ it('puts the whole catalog on Discover, connected services and coming soon included', () => {+ expect(names(connectorsInTab(catalog, 'discover', ''))).toEqual([+ 'Atlassian',+ 'Datadog',+ 'GitHub',+ 'Linear',+ 'Notion',+ ]);+ });++ it('searches within the tab by name, category or description', () => {+ expect(names(connectorsInTab(catalog, 'discover', 'project'))).toEqual(['Atlassian', 'Linear']);+ expect(names(connectorsInTab(catalog, 'yours', 'project'))).toEqual(['Linear']);+ expect(names(connectorsInTab(catalog, 'yours', 'atlas'))).toEqual([]);+ expect(names(connectorsInTab(catalog, 'discover', ' NOTION '))).toEqual(['Notion']);+ expect(names(connectorsInTab(catalog, 'discover', 'incidents'))).toEqual(['Datadog']);+ });+});++describe("a card's own control", () => {+ const quick = (overrides: Partial<ConnectionCatalogEntry>) => {+ const item = entry(overrides);+ return cardQuickAction(item, connectorCardState(item));+ };++ it('connects where the profile would offer Connect', () => {+ expect(quick({})).toBe('connect');+ // Connectable where it cannot be granted: still offered, as on the profile.+ expect(quick({ unavailable_reason: 'Not fully set up.' })).toBe('connect');+ });++ it('marks a connection only when the card shows it connected, never offering to disconnect', () => {+ expect(quick({ status: 'connected' })).toBe('connected');+ expect(quick({ status: 'connected', workspace_enabled: null })).toBe('connected');+ });++ it('shows the state, not the mark, for a connection that cannot be used', () => {+ expect(quick({ status: 'connected', workspace_enabled: false })).toBeNull();+ expect(quick({ status: 'connected', unavailable_reason: 'Not set up on this server.' })).toBe(+ null+ );+ expect(quick({ status: 'connected', unavailable_reason: 'Gone.', connectable: false })).toBe(+ null+ );+ });++ it('offers nothing it would be refused, or that needs the profile', () => {+ expect(quick({ connectable: false })).toBeNull();+ expect(quick({ workspace_enabled: false })).toBeNull();+ expect(quick({ status: 'coming_soon' })).toBeNull();+ expect(quick({ status: 'needs_reauthorization' })).toBeNull();+ expect(quick({ status: 'error' })).toBeNull();+ });+});++describe('the profile', () => {+ it('says who the connection is as, and what was allowed', () => {+ expect(connectedAsLine(entry())).toBeNull();+ expect(+ connectedAsLine(entry({ status: 'connected', external_identity: 'ada', consent: 'write' }))+ ).toBe('Connected as ada · Read and write');+ expect(+ connectedAsLine(entry({ status: 'connected', external_identity: 'ada', consent: 'read' }))+ ).toBe('Connected as ada · Read');+ expect(connectedAsLine(entry({ status: 'needs_reauthorization', consent: null }))).toBe(+ 'Connected'+ );+ expect(+ connectedAsLine(+ entry({+ status: 'connected',+ auth_type: 'api_key',+ external_identity: 'Key · example.test',+ })+ )+ ).toBe('Connected with Key · example.test');+ });++ it('claims no access level for a key, and says what agents can do with one', () => {+ const key = entry({+ status: 'connected',+ auth_type: 'api_key',+ external_identity: 'Key · example.test',+ consent: 'write',+ });+ expect(connectedAsLine(key)).toBe('Connected with Key · example.test');+ expect(connectedAsLine({ ...key, external_identity: null })).toBe('Connected with your key');+ expect(keyAccessText(key)).toBe(+ "Whatever the key allows at Example. Switch can't read a key's scopes."+ );+ expect(keyAccessText(entry({ status: 'connected', consent: 'write' }))).toBeNull();+ });++ it('names the sign-in type and how long access lasts', () => {+ expect(signInLabel(entry())).toBe('Sign in at Example');+ expect(signInLabel(entry({ auth_type: 'api_key' }))).toBe('Key');+ expect(signInLabel(entry({ slug: 'github' }))).toBe('GitHub App');+ expect(tokenLifetimeLabel(entry({ token_lifetime: 3600 }))).toBe('1 hour');+ expect(tokenLifetimeLabel(entry({ token_lifetime: 28_800 }))).toBe('8 hours');+ expect(tokenLifetimeLabel(entry({ token_lifetime: 900 }))).toBe('15 minutes');+ expect(tokenLifetimeLabel(entry({ token_lifetime: 172_800 }))).toBe('2 days');+ expect(tokenLifetimeLabel(entry({ token_lifetime: null }))).toBe('Not stated');+ expect(tokenLifetimeLabel(entry({ auth_type: 'api_key' }))).toBe(+ "The key itself, which doesn't expire"+ );+ });++ it('offers connecting, signing in again, or replacing a key', () => {+ expect(profileConnectAction(entry())).toBe('connect');+ expect(profileConnectAction(entry({ status: 'needs_reauthorization' }))).toBe('reconnect');+ expect(profileConnectAction(entry({ status: 'error' }))).toBe('reconnect');+ expect(profileConnectAction(entry({ status: 'connected' }))).toBeNull();+ expect(profileConnectAction(entry({ slug: 'github', status: 'connected' }))).toBeNull();+ expect(profileConnectAction(entry({ status: 'connected', auth_type: 'api_key' }))).toBe(+ 'replace'+ );+ expect(profileConnectAction(entry({ status: 'not_connected', auth_type: 'api_key' }))).toBe(+ 'connect'+ );+ expect(profileConnectAction(entry({ status: 'coming_soon' }))).toBeNull();+ // Connectable where it cannot be granted: the server's reason does not hide Connect.+ expect(+ profileConnectAction(entry({ slug: 'github', unavailable_reason: 'Not fully set up.' }))+ ).toBe('connect');+ // Off in the workspace: the notice, not a button that would be refused.+ expect(profileConnectAction(entry({ workspace_enabled: false }))).toBeNull();+ expect(+ profileConnectAction(entry({ workspace_enabled: false, status: 'needs_reauthorization' }))+ ).toBeNull();+ });++ it('tells a member who can switch it on, and offers an admin the switch', () => {+ const off = entry({ workspace_enabled: false });+ expect(workspaceOffNotice(off, false)).toEqual({+ text: 'Not enabled in this workspace. Ask a workspace admin.',+ canEnable: false,+ });+ expect(workspaceOffNotice(off, true)).toEqual({+ text: 'Example is switched off for this workspace.',+ canEnable: true,+ });+ expect(workspaceOffNotice(entry(), true)).toBeNull();+ // No workspace layer on this server: nothing to say.+ expect(workspaceOffNotice(entry({ workspace_enabled: null }), false)).toBeNull();+ });+});++describe('the agents on a connector page', () => {+ const agents = [+ { agent_id: 'm2', name: 'M2', granted: false, addressing_open: true },+ { agent_id: 'm1', name: 'M1', granted: false, addressing_open: false },+ { agent_id: 'm3', name: 'M3', granted: true, addressing_open: true },+ ];++ it('can be added from the page for a service a grant switches on, and for GitHub', () => {+ expect(offersAddAgent(entry({ pass_through: true }))).toBe(true);+ expect(offersAddAgent(entry({ pass_through: false }))).toBe(false);+ expect(offersAddAgent(entry({ slug: 'github', pass_through: false }))).toBe(true);+ });++ it('starts a GitHub choice at the first account with nothing chosen, read only', () => {+ expect(emptyGitHubGrant(undefined)).toEqual({+ installationId: null,+ repositoryIds: [],+ access: 'read',+ });+ const github = {+ status: 'connected' as const,+ login: 'ada',+ install_url: 'https://example.test',+ installations: [+ {+ id: 7,+ account: 'ada',+ repositories: [+ { id: 1, name: 'ada/one' },+ { id: 2, name: 'ada/two' },+ ],+ },+ { id: 8, account: 'org', repositories: [{ id: 3, name: 'org/three' }] },+ ],+ };+ const empty = emptyGitHubGrant(github);+ expect(empty).toEqual({ installationId: 7, repositoryIds: [], access: 'read' });+ // Nothing to send until a repository is chosen.+ expect(githubGrantResources(empty)).toBeNull();+ expect(githubChoiceSummary(github, empty)).toBeNull();++ const one = withRepository(empty, 2);+ expect(withRepository(one, 2)).toBe(one);+ expect(githubGrantResources(one)).toEqual({ installation_id: 7, repository_ids: [2] });+ const all = withEveryRepository(github, one);+ expect(all.repositoryIds).toEqual([2, 1]);+ expect(withoutRepository(all, 2).repositoryIds).toEqual([1]);+ // Another account starts over: its repositories are different ones.+ expect(withInstallation(all, 8)).toEqual({+ installationId: 8,+ repositoryIds: [],+ access: 'read',+ });+ });++ it('says a GitHub choice in a sentence, naming the account only among several', () => {+ const one = {+ status: 'connected' as const,+ login: 'ada',+ install_url: 'https://example.test',+ installations: [+ {+ id: 7,+ account: 'ada',+ repositories: [+ { id: 1, name: 'ada/one' },+ { id: 2, name: 'ada/two' },+ ],+ },+ ],+ };+ const two = {+ ...one,+ installations: [...one.installations, { id: 8, account: 'org', repositories: [] }],+ };+ expect(+ githubChoiceSummary(one, { installationId: 7, repositoryIds: [1], access: 'read' })+ ).toBe('read access to 1 repository');+ expect(+ githubChoiceSummary(one, { installationId: 7, repositoryIds: [1, 2], access: 'write' })+ ).toBe('read and push access to 2 repositories');+ expect(+ githubChoiceSummary(two, { installationId: 7, repositoryIds: [1], access: 'read' })+ ).toBe('read access to 1 repository under ada');+ });++ it('counts repositories across accounts and offers choosing, then changing, them', () => {+ const none = {+ status: 'connected' as const,+ login: 'ada',+ install_url: 'https://example.test',+ installations: [{ id: 7, account: 'ada', repositories: [] }],+ };+ expect(repositoriesSummary(none)).toBe('0 repositories');+ expect(repositoriesActionLabel(none)).toBe('Choose repositories');+ const some = {+ ...none,+ installations: [+ { id: 7, account: 'ada', repositories: [{ id: 1, name: 'ada/one' }] },+ {+ id: 8,+ account: 'org',+ repositories: [+ { id: 2, name: 'org/two' },+ { id: 3, name: 'org/three' },+ ],+ },+ ],+ };+ expect(repositoriesSummary(some)).toBe('3 repositories across 2 accounts');+ expect(repositoriesActionLabel(some)).toBe('Change repositories');+ });++ it('counts the agents using it beside the heading', () => {+ expect(agentsSummary(0)).toBe('0 agents');+ expect(agentsSummary(1)).toBe('1 agent');+ expect(agentsSummary(3)).toBe('3 agents');+ });++ it('offers the agents without the service, narrowed by the search', () => {+ expect(addableAgents(agents, '').map((agent) => agent.agent_id)).toEqual(['m2', 'm1']);+ expect(addableAgents(agents, ' m1 ').map((agent) => agent.agent_id)).toEqual(['m1']);+ expect(addableAgents(agents, 'M3')).toEqual([]);+ expect(OPEN_AGENT_NOTE).toBe('Others can address it; it would act as you.');+ });++ it("sends the person to the agent's Connections tab where the server cannot list agents", () => {+ expect(agentsUnlistedText('Example')).toBe(+ "This server can't list your agents here. Turn Example on for an agent from the agent's Connections tab."+ );+ });++ it('says so when the person has no agents yet', () => {+ expect(noAgentsText('Example')).toBe(+ "You have no agents in this workspace yet. Once you add one, turn Example on for it from the agent's Connections tab."+ );+ });+});++/** A refusal as it reaches the renderer from the gateway. */+function refusal(status: number, retryable?: boolean): RpcError {+ return new RpcError(+ serializeRpcError(+ Object.assign(new Error(`Switch gateway returned ${status}`), {+ name: 'GatewayError',+ kind: 'http',+ status,+ detail: 'Refused.',+ ...(retryable === undefined ? {} : { retryable }),+ })+ )+ );+}++describe('the sign-in flow', () => {+ const waiting: ConnectFlowState = {+ ...initialConnectFlow(false),+ flowId: 'flow-1',+ flow: { status: 'pending', account: null, error: null, warning: null },+ };+ const run = (state: ConnectFlowState, ...events: Parameters<typeof connectFlowReducer>[1][]) =>+ events.reduce(connectFlowReducer, state);++ it('cannot be closed while waiting for the browser, or mid-call', () => {+ expect(canCloseConnectFlow(initialConnectFlow(false))).toBe(true);+ expect(canCloseConnectFlow(waiting)).toBe(false);+ expect(canCloseConnectFlow(run(initialConnectFlow(false), { type: 'act' }))).toBe(false);+ });++ it('counts a cancel answered 410 as cancelled, not as an error', () => {+ expect(+ run(waiting, { type: 'act' }, { type: 'cancel_failed', cause: refusal(410), error: 'Gone.' })+ ).toMatchObject({ flowId: null, flow: null, busy: false, error: null });+ expect(+ run(waiting, { type: 'act' }, { type: 'cancel_failed', cause: refusal(503), error: 'Down.' })+ ).toMatchObject({ flowId: 'flow-1', error: 'Down.' });+ });++ it("says why a sign-in failed, in the server's words where it has them, and lets the dialog close", () => {+ const failed = run(waiting, {+ type: 'polled',+ flow: { status: 'failed', account: null, error: null, warning: null },+ failure: 'Signing in failed.',+ });+ expect(failed.error).toBe('Signing in failed.');+ expect(failed.flowId).toBe('flow-1');+ expect(canCloseConnectFlow(failed)).toBe(true);+ const refused = run(waiting, {+ type: 'polled',+ flow: { status: 'failed', account: null, error: 'Already linked elsewhere.', warning: null },+ failure: 'Signing in failed.',+ });+ expect(refused.error).toBe('Already linked elsewhere.');+ });++ it('is connected, with the warning, once the server has kept the account', () => {+ const after = run(waiting, { type: 'connected', warning: 'Access stays a while.' });+ expect(after).toMatchObject({+ connected: true,+ flowId: null,+ flow: null,+ busy: false,+ error: null,+ warning: 'Access stays a while.',+ });+ expect(canCloseConnectFlow(after)).toBe(true);+ });+});++describe('the disconnect dialog', () => {+ it('leads with how many agents lose the service, then names them', () => {+ expect(disconnectCopy(entry({ name: 'Atlassian' }), ['m1-cc']).lines[0]).toBe(+ 'm1-cc loses Atlassian.'+ );+ expect(disconnectCopy(entry(), ['M1', 'M3']).lines[0]).toBe(+ '2 agents lose Example: M1 and M3. Disconnecting removes their access.'+ );+ expect(+ disconnectCopy(entry({ name: 'Atlassian' }), ['m1-cc', 'm3-oc', 'm4', 'test']).lines[0]+ ).toBe(+ '4 agents lose Atlassian: m1-cc, m3-oc, m4 and test. Disconnecting removes their access.'+ );+ });++ it('names at most four agents, and counts the rest', () => {+ expect(disconnectCopy(entry(), ['A', 'B', 'C', 'D', 'E']).lines[0]).toBe(+ '5 agents lose Example: A, B, C, D and 1 more. Disconnecting removes their access.'+ );+ expect(disconnectCopy(entry(), ['A', 'B', 'C', 'D', 'E', 'F', 'G']).lines[0]).toBe(+ '7 agents lose Example: A, B, C, D and 3 more. Disconnecting removes their access.'+ );+ });++ it('says nobody loses it when no agent uses it', () => {+ expect(disconnectCopy(entry(), []).lines[0]).toBe('None of your agents use Example.');+ expect(disconnectCopy(entry(), []).title).toBe('Disconnect Example?');+ });++ it('says every agent loses it where the server cannot say which', () => {+ expect(disconnectCopy(entry(), null).lines[0]).toBe(+ "Disconnecting removes every agent's access to Example."+ );+ });++ it('adds that the key cannot be revoked only for a key', () => {+ const note = "Switch can't revoke this key at Example; delete it there.";+ expect(disconnectCopy(entry({ auth_type: 'api_key' }), ['M1']).lines).toContain(note);+ expect(disconnectCopy(entry({ auth_type: 'oauth' }), ['M1']).lines).not.toContain(note);+ });+});++describe('an admin switching a service off', () => {+ const service = { name: 'Example', connected_members: 0, granted_agents: 0 };++ it('asks first when anyone is connected or any agent uses it, naming both counts', () => {+ expect(switchOffConfirmation({ ...service, connected_members: 3, granted_agents: 5 })).toEqual({+ title: 'Switch Example off for this workspace?',+ description:+ '3 members are connected and 5 agents use it. Their sessions lose it within a minute.',+ });+ expect(+ switchOffConfirmation({ ...service, connected_members: 1, granted_agents: 0 })?.description+ ).toBe('1 member is connected and 0 agents use it. Their sessions lose it within a minute.');+ expect(+ switchOffConfirmation({ ...service, connected_members: 0, granted_agents: 1 })?.description+ ).toBe('0 members are connected and 1 agent uses it. Their sessions lose it within a minute.');+ });++ it('does not ask when nobody is connected and no agent uses it', () => {+ expect(switchOffConfirmation(service)).toBeNull();+ });++ it('says who last switched it, or that nobody has', () => {+ const at = (iso: string) => `at ${iso}`;+ expect(+ workspaceSwitchNote({ enabled: true, updated_by_name: null, updated_at: null }, at)+ ).toBe('On by default.');+ expect(+ workspaceSwitchNote({ enabled: false, updated_by_name: 'Ada', updated_at: 'T' }, at)+ ).toBe('Switched off by Ada, at T.');+ });+});++describe('with the service_connections flag off', () => {+ const flags = (on: boolean): ServerFeatureFlags => ({+ serverId: 'server',+ flags: { ...allFeatureFlagsOff(), service_connections: on },+ fetchedAt: 1,+ error: null,+ });++ it('leaves Connectors and Admin out of the nav', () => {+ const shown = workspaceNavViews({+ managed: false,+ serviceConnections: false,+ administers: true,+ });+ expect(shown).not.toContain('connectors');+ expect(shown).not.toContain('admin');+ expect(+ workspaceNavViews({ managed: true, serviceConnections: true, administers: true })+ ).toEqual([+ 'server',+ 'serverAgents',+ 'serverRooms',+ 'connectors',+ 'templates',+ 'admin',+ 'managedServer',+ ]);+ });++ it('shows Admin only to whoever administers the workspace', () => {+ expect(+ workspaceNavViews({ managed: false, serviceConnections: true, administers: false })+ ).toEqual(['server', 'serverAgents', 'serverRooms', 'connectors', 'templates']);+ });++ it('has no page to show, rather than an empty one', () => {+ expect(connectorsPageAccess(flags(false))).toBe('absent');+ expect(connectorsPageAccess({ ...flags(false), fetchedAt: null, error: 'down' })).toBe(+ 'absent'+ );+ expect(connectorsPageAccess(null)).toBe('loading');+ expect(+ connectorsPageAccess({ ...flags(false), fetchedAt: null, error: FLAGS_NOT_READ_YET })+ ).toBe('loading');+ expect(connectorsPageAccess(flags(true))).toBe('shown');+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.tsindex 7c89eafca..2ca40ce29 100644--- a/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts+++ b/console/apps/switch-console-desktop/src/shared/core/feature-flags/feature-flags.ts@@ -25,6 +25,9 @@ export type FeatureFlags = Record<FeatureFlagKey, boolean>;/** One flag as the gateway serves it. */export type RemoteFeatureFlag = { key: string; enabled: boolean };+/** The `error` of a server whose flags have not been asked for yet, as opposed to failed. */+export const FLAGS_NOT_READ_YET = 'Not read yet';+/** What Console last learned about one server's flags. */export type ServerFeatureFlags = {serverId: string;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/connection-catalog.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/connection-catalog.tsindex e5a7bd9ef..724bc1154 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/connection-catalog.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/connection-catalog.ts@@ -45,6 +45,13 @@ export const connectionCatalogEntrySchema = z.object({key: serviceKeyFormSchema.nullable(),/** The connected account as people recognise it; null when not connected. */external_identity: z.string().nullable(),+ /** What the person allowed when they connected; null when not connected or not said. */+ consent: z.enum(['read', 'write']).nullable(),+ /**+ * Whether the workspace has the service switched on. Null from a server+ * with no workspace switch, which every page treats as on.+ */+ workspace_enabled: z.boolean().nullable(),});export type ConnectionCatalogEntry = z.infer<typeof connectionCatalogEntrySchema>;@@ -61,6 +68,8 @@ export const connectionCatalogSchema = z.object({loopback_ports: true,key: true,external_identity: true,+ consent: true,+ workspace_enabled: true,}).extend({ status: z.enum(['connected', 'not_connected', 'coming_soon']) })),@@ -85,7 +94,48 @@ export const serviceConnectionsSchema = z.object({loopback_ports: z.array(z.number().int()).nullable().default(null),key: serviceKeyFormSchema.nullable().default(null),external_identity: z.string().nullable().default(null),+ consent: z.enum(['read', 'write']).nullable().default(null),+ workspace_enabled: z.boolean().nullable().default(null),status: z.enum(['not_connected', 'active', 'needs_reauthorization', 'error']),})),});++/** `GET /service-connections/{service}/agents`: the person's own agents in the workspace. */+export const connectionAgentsSchema = z.array(+ z.object({+ agent_id: z.string(),+ name: z.string(),+ /** Whether the agent has a grant on the service. */+ granted: z.boolean(),+ /** Whether anyone but its owner can address it, and so use what it is granted. */+ addressing_open: z.boolean(),+ })+);+export type ConnectionAgent = z.infer<typeof connectionAgentsSchema>[number];++/** One catalog service as a workspace admin sees it: switched on or off, and who it reaches. */+export const workspaceServiceSchema = z.object({+ slug: z.string(),+ name: z.string(),+ enabled: z.boolean(),+ /** Who last switched it; null while nobody has touched its switch. */+ updated_by_name: z.string().nullable(),+ updated_at: z.string().nullable(),+ /** How many people in the workspace have connected it. */+ connected_members: z.number().int(),+ /** How many agents in the workspace are granted it. */+ granted_agents: z.number().int(),+});+export type WorkspaceService = z.infer<typeof workspaceServiceSchema>;++/** `GET /workspace/services`, for workspace admins. */+export const workspaceServicesSchema = z.object({ services: z.array(workspaceServiceSchema) });++/** `PUT /workspace/services/{service}`: `warning` when issued access could not all be revoked yet. */+export const workspaceServiceChangeSchema = z.object({+ slug: z.string(),+ enabled: z.boolean(),+ warning: z.string().nullable(),+});+export type WorkspaceServiceChange = z.infer<typeof workspaceServiceChangeSchema>;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/connector-apps.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/connector-apps.tsnew file mode 100644index 000000000..914474873--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/connector-apps.ts@@ -0,0 +1,115 @@+import { z } from 'zod';++/**+ * The apps the server's operator sets up for connectors to sign in through:+ * GitHub's App and the OAuth clients registered at a vendor (Google's). One+ * app serves every workspace on the server, so every route behind these is+ * the operator's alone. No answer carries a secret: a client secret shows its+ * last four characters, a private key its fingerprint.+ */++export const connectorAppFieldSchema = z.enum(['client_id', 'client_secret', 'private_key']);+export type ConnectorAppField = z.infer<typeof connectorAppFieldSchema>;++/** Whether a secret is set, and how the operator recognises it; never the secret. */+const connectorAppSecretSchema = z.object({+ set: z.boolean(),+ /** A client secret's last four characters. */+ last4: z.string().nullable().optional(),+ /** A private key's SHA-256 fingerprint, as GitHub lists it. */+ fingerprint: z.string().nullable().optional(),+});++/** The app one connector signs in through, and where it comes from. */+export const connectorAppSchema = z.object({+ slug: z.string(),+ name: z.string(),+ kind: z.enum(['github_app', 'oauth_client']),+ source: z.enum(['configuration', 'saved', 'none']),+ /** The variables that set it from configuration. */+ configuration_variables: z.array(z.string()),+ /** GitHub's HOSTED_GITHUB_CONFIG_PATH: no private key, so it can't be copied. */+ deprecated: z.boolean(),+ client_id: z.string().nullable(),+ /** The client saved here, when there is one. */+ saved_client_id: z.string().nullable(),+ fields: z.object({ slug: z.string().nullable().optional() }),+ secrets: z.record(z.string(), connectorAppSecretSchema),+ /** Saved here, but configuration is set, so Switch uses that. */+ saved_ignored: z.boolean(),+ /** Saved here under a key the server no longer has. */+ unreadable: z.boolean(),+ /** Why the app saved here can't be used. */+ load_error: z.string().nullable(),+ /** Where the vendor sends people back to Switch; null without a public URL it accepts. */+ redirect_uri: z.string().nullable(),+ /** Why it can't be set up here, before any vendor is asked. */+ setup_blocked: z.string().nullable(),+ install_url: z.string().nullable(),+ updated_by_name: z.string().nullable(),+ updated_at: z.string().nullable(),+ connected_members: z.number().int(),+ workspaces: z.number().int(),+ /** Connections made through an app this server no longer uses. */+ stale_connections: z.number().int(),+});+export type ConnectorApp = z.infer<typeof connectorAppSchema>;++/** `GET /connector-apps`. A service whose client Core registers itself is not the operator's to set up. */+export const connectorAppsSchema = z.object({+ public_url: z.string().nullable(),+ apps: z.array(connectorAppSchema),+});+export type ConnectorApps = z.infer<typeof connectorAppsSchema>;++export const connectorAppCheckSchema = z.object({+ name: z.string(),+ ok: z.boolean(),+ message: z.string(),+ field: connectorAppFieldSchema.nullable(),+});+export type ConnectorAppCheck = z.infer<typeof connectorAppCheckSchema>;++/** `POST /connector-apps/{service}/check`: the vendor asked about the app in use. */+export const connectorAppCheckResultSchema = z.object({+ ok: z.boolean(),+ checks: z.array(connectorAppCheckSchema),+});+export type ConnectorAppCheckResult = z.infer<typeof connectorAppCheckResultSchema>;++/** Who is connected through an app, or would have to reconnect if another replaced it. */+export const connectorAppImpactSchema = z.object({+ connected_members: z.number().int(),+ workspaces: z.number().int(),+});+export type ConnectorAppImpact = z.infer<typeof connectorAppImpactSchema>;++/** A 422 from a save the vendor refused: what it said, and the value to look at again. */+export const connectorAppRefusalSchema = z.object({+ detail: z.string(),+ field: connectorAppFieldSchema.nullable(),+ checks: z.array(connectorAppCheckSchema),+});++export type SaveConnectorAppInput = {+ client_id: string;+ /** Left out, the saved one is kept. */+ client_secret?: string;+ private_key?: string;+ /** Switching to another app on purpose: everyone connected must reconnect. */+ replace: boolean;+};++/**+ * A save's outcome. A refusal is an answer, not a failure: the vendor said+ * what is wrong and with which value, which the form shows beside it. Any+ * other failure is thrown.+ */+export type SaveConnectorAppResult =+ | { kind: 'saved'; app: ConnectorApp }+ | {+ kind: 'refused';+ message: string;+ field: ConnectorAppField | null;+ checks: ConnectorAppCheck[];+ };diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/github-connection.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/github-connection.tsindex 3c6c2d6cf..a97b6689a 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/github-connection.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/github-connection.ts@@ -23,7 +23,9 @@ export const gitHubConnectionSchema = z.discriminatedUnion('status', []);export type GitHubConnection = z.infer<typeof gitHubConnectionSchema>;export const gitHubFlowSchema = z.object({- status: z.enum(['pending', 'checking', 'ready', 'failed']),+ status: z.enum(['pending', 'checking', 'connected', 'failed']),login: z.string(),+ error: z.string().nullable(),+ warning: z.string().nullable(),});export type GitHubFlow = z.infer<typeof gitHubFlowSchema>;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-connection.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-connection.tsindex c733d69e7..df791ae30 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-connection.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-connection.ts@@ -14,12 +14,17 @@ export const serviceFlowStartSchema = z.object({});export type ServiceFlowStart = z.infer<typeof serviceFlowStartSchema>;-/** `GET /service-connections/{service}/flows/{id}`. */+/**+ * `GET /service-connections/{service}/flows/{id}`: `connected` once the server+ * has exchanged the code and kept the connection; `failed` with the reason.+ */export const serviceFlowSchema = z.object({- status: z.enum(['pending', 'checking', 'ready', 'failed']),+ status: z.enum(['pending', 'checking', 'connected', 'failed']),/** The connected account as people recognise it, once read. */account: z.string().nullable(),error: z.string().nullable(),+ /** What the server said as it connected, once each. */+ warning: z.string().nullable(),});export type ServiceFlow = z.infer<typeof serviceFlowSchema>;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-grants.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-grants.tsindex 749df594f..ea6b6c9e1 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-grants.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/service-grants.ts@@ -1,5 +1,4 @@import { z } from 'zod';-import type { AddressingPolicy } from './switch-servers';/** A grant giving an agent access to its owner's connection to a service. */export const serviceGrantSchema = z.object({@@ -21,20 +20,3 @@ export type ServiceGrants = z.infer<typeof serviceGrantsSchema>;/** What a grant change can leave behind: access already handed out, usable for a while. */export const serviceGrantWarningSchema = z.object({ warning: z.string().nullable() });--/**- * Owner-only addressing: the owner, and agents the owner runs. What the grant- * screens offer when anyone can address an agent with grants.- */-export const OWNER_ONLY_POLICY: AddressingPolicy = {- rules: [- {- rooms: '*',- room_groups: '*',- users: [],- agents: [],- owner: true,- owner_agents: true,- },- ],-};diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.tsindex fc4d6be47..197c01fd9 100644--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts@@ -18,6 +18,7 @@ export const VIEW_IDS = ['server','managedServer','serverAgents',+ 'connectors','serverRooms','remoteHosts','remoteHost',@@ -26,6 +27,7 @@ export const VIEW_IDS = ['templateDetail','templateUse','templateCapture',+ 'admin',] as const;export type ViewIdName = (typeof VIEW_IDS)[number];diff --git a/console/packages/agent-providers/src/acp/acp-adapter.test.ts b/console/packages/agent-providers/src/acp/acp-adapter.test.tsindex ce82e2e1d..d822d5668 100644--- a/console/packages/agent-providers/src/acp/acp-adapter.test.ts+++ b/console/packages/agent-providers/src/acp/acp-adapter.test.ts@@ -70,6 +70,7 @@ async function start(runtimeMode: 'approval-required',env: {},mcpServers: {},+ connectorMcpServers: [],...input,});return { adapter, events, session, server: servers.at(-1)! };@@ -190,6 +191,7 @@ it('auto-approves a tool the hooks place on any session-registered MCP server',};const { adapter, events, server } = await start(hooks, {mcpServers: { echo: { transport: 'stdio', command: 'node', args: ['echo.js'] } },+ connectorMcpServers: [],});await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });const options = [{ optionId: 'once', name: 'Allow once', kind: 'allow_once' }];@@ -345,3 +347,53 @@ it('fills a stdio MCP server environment from the session for its envVars', asyn},]);});++it.each([+ ['approval-required', 'switch', false],+ ['approval-required', 'other', false],+ ['approval-required', 'atlassian', true],+ ['approval-required', 'gws', true],+ ['auto-accept-edits', 'switch', false],+ ['auto-accept-edits', 'other', false],+ ['auto-accept-edits', 'atlassian', true],+ ['auto-accept-edits', 'gws', true],+ ['full-access', 'switch', false],+ ['full-access', 'atlassian', false],+ ['full-access', 'gws', false],+] as const)(+ "in %s a tool on %s asks: %s (Switch's own never does)",+ async (runtimeMode, toolServer, asks) => {+ const stdio = { transport: 'stdio' as const, command: 'node', args: ['server.js'] };+ const hooks: AcpProviderHooks = {+ ...dummy,+ mcpServerOf: (toolCall) => toolCall._meta?.server as string | undefined,+ };+ const { adapter, events, server } = await start(hooks, {+ runtimeMode,+ mcpServers: { switch: stdio, atlassian: stdio, gws: stdio, other: stdio },+ connectorMcpServers: ['atlassian', 'gws'],+ });+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });+ server.send({+ id: 80,+ method: 'session/request_permission',+ params: {+ sessionId: 'native',+ toolCall: { toolCallId: 'call-80', title: 'search', _meta: { server: toolServer } },+ options: [{ optionId: 'once', name: 'Allow', kind: 'allow_once' }],+ },+ });+ await flush();+ const opened = events.filter((e) => e.type === 'request.opened');+ if (!asks) {+ expect(opened).toEqual([]);+ expect(server.received.find((m) => m.id === 80)?.result).toEqual({+ outcome: { outcome: 'selected', optionId: 'once' },+ });+ return;+ }+ expect(opened).toHaveLength(1);+ expect(opened[0]).toMatchObject({ requestType: 'mcp_tool_approval', connector: toolServer });+ expect(server.received.some((m) => m.id === 80 && m.result)).toBe(false);+ }+);diff --git a/console/packages/agent-providers/src/acp/acp-adapter.ts b/console/packages/agent-providers/src/acp/acp-adapter.tsindex 430a62c40..c97e46d7c 100644--- a/console/packages/agent-providers/src/acp/acp-adapter.ts+++ b/console/packages/agent-providers/src/acp/acp-adapter.ts@@ -109,6 +109,8 @@ interface State {context: string;runtimeMode: ProviderSessionStartInput['runtimeMode'];mcpNames: Set<string>;+ /** The registered servers whose tools are allowed without asking: all but the connectors. */+ autoApprovedMcpNames: Set<string>;toolServers: Map<string, string>;prompt: AcpPromptCapabilities;configOptions: AcpConfigOption[];@@ -188,6 +190,9 @@ export class AcpAdapter implements ProviderAdapter {context: input.systemContext ?? '',runtimeMode: input.runtimeMode,mcpNames: new Set(Object.keys(input.mcpServers)),+ autoApprovedMcpNames: new Set(+ Object.keys(input.mcpServers).filter((name) => !input.connectorMcpServers.includes(name))+ ),toolServers: new Map(),prompt: {},configOptions: [],@@ -452,7 +457,7 @@ export class AcpAdapter implements ProviderAdapter {this.emit(state, { type: 'user-input.requested', turnId, requestId, questions });});},- requestDecision: async ({ requestType, title, detail, options }) => {+ requestDecision: async ({ requestType, title, detail, options, connector }) => {const turnId = active();if (!turnId) return ACP_CANCELLED;const requestId = randomUUID();@@ -469,6 +474,7 @@ export class AcpAdapter implements ProviderAdapter {title,...(detail === undefined ? {} : { detail }),options: options.map(({ decision, label }) => ({ decision, label })),+ ...(connector === undefined ? {} : { connector }),});});},@@ -493,7 +499,7 @@ export class AcpAdapter implements ProviderAdapter {const server = this.hooks.mcpServerOf?.(toolCall) ?? state.toolServers.get(toolCall.toolCallId);if (once &&- ((server !== undefined && state.mcpNames.has(server)) ||+ ((server !== undefined && state.autoApprovedMcpNames.has(server)) ||state.runtimeMode === 'full-access' ||(state.runtimeMode === 'auto-accept-edits' && toolCall.kind === 'edit')))@@ -522,15 +528,18 @@ export class AcpAdapter implements ProviderAdapter {});}options.push({ decision: 'cancel', label: 'Cancel', response: ACP_CANCELLED });+ const mcp = server !== undefined && state.mcpNames.has(server);return await context.requestDecision({- requestType:- toolCall.kind === 'execute'+ requestType: mcp+ ? 'mcp_tool_approval'+ : toolCall.kind === 'execute'? 'command_execution_approval': toolCall.kind === 'edit'? 'file_change_approval': 'tool_approval',title: toolCall.title ?? `${this.hooks.label} needs permission`,options,+ ...(mcp && !state.autoApprovedMcpNames.has(server) ? { connector: server } : {}),});}diff --git a/console/packages/agent-providers/src/acp/hooks.ts b/console/packages/agent-providers/src/acp/hooks.tsindex 3256334fc..b19706532 100644--- a/console/packages/agent-providers/src/acp/hooks.ts+++ b/console/packages/agent-providers/src/acp/hooks.ts@@ -69,6 +69,8 @@ export interface AcpSessionContext {title: string;detail?: string;options: Array<{ decision: ApprovalDecision; label: string; response: unknown }>;+ /** The connector server whose tool this asks to run, if it is one. */+ connector?: string;}): Promise<unknown>;/** Add a finished item to the running turn's transcript. */completeItem(item: ProviderItem): void;diff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex 9ab32ce43..ea49bb7f3 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -63,6 +63,12 @@ export interface ProviderSessionStartInput {env: Record<string, string>;/** MCP servers the session must expose to the agent, keyed by server name. */mcpServers: Record<string, McpServerSpec>;+ /**+ * Servers whose tools follow `runtimeMode` instead of being auto-approved:+ * the granted connectors' (`host/shared-config.ts`). Every other server in+ * {@link mcpServers}, Switch's own above all, is auto-approved in every mode.+ */+ connectorMcpServers: string[];/** Extra system-level context appended to whatever the vendor loads itself. */systemContext?: string;/**diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.tsindex a21279d1e..6c74c4e06 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts@@ -59,6 +59,7 @@ async function setup(resume = false, switchRegistered = true) {},}: {},+ connectorMcpServers: [],...(resume ? { resume: { nativeSessionId: 'acp:native' } } : {}),});const server = servers.at(-1)!;@@ -250,6 +251,7 @@ it('refuses legacy CLI conversation IDs before starting a process', async () =>runtimeMode: 'approval-required',env: {},mcpServers: {},+ connectorMcpServers: [],resume: { nativeSessionId: 'old-cli' },})).rejects.toThrow('previous Antigravity CLI');@@ -368,6 +370,7 @@ it('registers an HTTP MCP server with its headers when the agent declares HTTP',runtimeMode: 'approval-required',env: {},mcpServers: httpSwitch,+ connectorMcpServers: [],});expect(servers.at(-1)!.received.find((m) => m.method === 'session/new')?.params).toMatchObject({mcpServers: [@@ -391,6 +394,7 @@ it('refuses to start a session whose HTTP MCP servers the agent cannot reach', aruntimeMode: 'approval-required',env: {},mcpServers: httpSwitch,+ connectorMcpServers: [],})).rejects.toThrow('Antigravity does not declare MCP over HTTP');expect(servers.at(-1)!.received.some((m) => m.method === 'session/new')).toBe(false);@@ -406,6 +410,7 @@ it('auto-approves calls to any MCP server the session registered, not only SwitcruntimeMode: 'approval-required',env: {},mcpServers: { echo: { transport: 'stdio', command: 'node', args: ['echo.js'] } },+ connectorMcpServers: [],});const server = servers.at(-1)!;await adapter.sendTurn({ sessionId: 'echo', turnId: 't', text: 'echo' });diff --git a/console/packages/agent-providers/src/claude/claude-adapter.test.ts b/console/packages/agent-providers/src/claude/claude-adapter.test.tsindex de4010047..a08868b20 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.test.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.test.ts@@ -16,6 +16,7 @@ function startInput(overrides: Partial<ProviderSessionStartInput> = {}): ProvideruntimeMode: 'approval-required',env: { PATH: '/usr/bin', HOME: '/home/agent' },mcpServers: {},+ connectorMcpServers: [],...overrides,};}@@ -212,6 +213,7 @@ describe('ClaudeAdapter session lifecycle', () => {await adapter.startSession(startInput({mcpServers: { switch: { transport: 'stdio', command: 'node', args: ['server.mjs'] } },+ connectorMcpServers: [],}));expect(sdk.options().settings).toEqual({@@ -282,9 +284,9 @@ describe('ClaudeAdapter session lifecycle', () => {expect(warning.message).toContain('bundled with the Agent SDK');});- it('maps each runtime mode onto a permission mode', async () => {+ it('starts the SDK in the permission mode each runtime mode names', async () => {for (const [runtimeMode, permissionMode] of [- ['approval-required', undefined],+ ['approval-required', 'default'],['auto-accept-edits', 'acceptEdits'],['full-access', 'bypassPermissions'],] as const) {@@ -295,6 +297,14 @@ describe('ClaudeAdapter session lifecycle', () => {}});+ it('never leaves approval-required to the person’s own default mode', async () => {+ // Unset, the CLI reads `defaultMode` from the person's settings; `auto`+ // there settles connector calls before the callback can ask.+ const { sdk } = await startSession('approval-required');+ expect(sdk.options()).toHaveProperty('permissionMode', 'default');+ expect(sdk.options().allowDangerouslySkipPermissions).toBeUndefined();+ });+it('drops the SDK’s shadowed-callback warning and leaves other warnings alone', async () => {// The callback is registered under bypassPermissions on purpose — it is// what makes the CLI offer AskUserQuestion — so the SDK's warning about it@@ -949,8 +959,6 @@ describe('ClaudeAdapter approvals', () => {it('leaves native permission rules and hooks in control when bypass is off', async () => {const { sdk } = await startSession();- expect(sdk.options()).not.toHaveProperty('permissionMode');- expect(sdk.options()).toHaveProperty('resolvePermissionModeInCli', true);expect(sdk.options().settingSources).toBeUndefined();expect(sdk.options().hooks).toBeUndefined();expect(sdk.options().canUseTool).toBeTypeOf('function');@@ -1226,3 +1234,106 @@ describe('ClaudeAdapter background subagents', () => {await adapter.stopAll();});});++describe('ClaudeAdapter connector tools', () => {+ const MODES: RuntimeMode[] = ['approval-required', 'auto-accept-edits', 'full-access'];+ const stdio = { transport: 'stdio' as const, command: 'node', args: ['server.mjs'] };+ const toolOptions = (toolUseID: string, extra: Record<string, unknown> = {}) => ({+ signal: new AbortController().signal,+ toolUseID,+ requestId: `control-${toolUseID}`,+ ...extra,+ });++ async function startWithConnectors(runtimeMode: RuntimeMode) {+ const sdk = createFakeSdk();+ const adapter = new ClaudeAdapter({ query: sdk.query, claudeExecutablePath: '/bin/claude' });+ const recorder = new EventRecorder(adapter);+ await adapter.startSession(+ startInput({+ runtimeMode,+ mcpServers: {+ switch: stdio,+ atlassian: { transport: 'http', url: 'http://127.0.0.1:4100/mcp' },+ // A vendor CLI the host serves to the CLI as an MCP server.+ 'google-workspace': stdio,+ other: stdio,+ },+ connectorMcpServers: ['atlassian', 'google-workspace'],+ })+ );+ await adapter.sendTurn({ sessionId: SESSION, turnId: 'turn-1', text: 'go' });+ return { sdk, adapter, recorder };+ }++ it.each(MODES)("never asks about Switch's own room tools, in %s", async (mode) => {+ const { sdk, recorder } = await startWithConnectors(mode);+ const allowed = await sdk.canUseTool()('mcp__switch__post_message', {}, toolOptions('t1'));+ expect(allowed).toEqual({ behavior: 'allow' });+ expect(recorder.ofType('request.opened')).toEqual([]);+ });++ it.each(MODES)('allows a server that is not a connector without asking, in %s', async (mode) => {+ const { sdk, recorder } = await startWithConnectors(mode);+ const allowed = await sdk.canUseTool()('mcp__other__run', {}, toolOptions('t1'));+ expect(allowed).toEqual({ behavior: 'allow' });+ expect(recorder.ofType('request.opened')).toEqual([]);+ });++ it.each(+ MODES.flatMap((mode) =>+ ['atlassian', 'google-workspace'].map((server) => [mode, server] as const)+ )+ )('in %s a %s tool asks, except in full access', async (mode, server) => {+ const { sdk, adapter, recorder } = await startWithConnectors(mode);+ const decision = sdk.canUseTool()(+ `mcp__${server.replace(/[^A-Za-z0-9_-]/g, '_')}__search`,+ { query: 'open issues' },+ toolOptions('t1')+ );+ if (mode === 'full-access') {+ expect(await decision).toEqual({ behavior: 'allow' });+ expect(recorder.ofType('request.opened')).toEqual([]);+ return;+ }+ const opened = await recorder.waitFor('request.opened', () => true, 1_000);+ expect(opened.requestType).toBe('mcp_tool_approval');+ expect(opened.connector).toBe(server);+ expect(opened.title).toBe(`${server.replace(/[^A-Za-z0-9_-]/g, '_')} wants to run search`);+ expect(opened.detail).toBe('{"query":"open issues"}');+ await adapter.respondToRequest(SESSION, opened.requestId, 'accept');+ expect(await decision).toEqual({ behavior: 'allow' });+ });++ it('denies a declined connector call, telling the agent not to retry', async () => {+ const { sdk, adapter, recorder } = await startWithConnectors('approval-required');+ const decision = sdk.canUseTool()('mcp__atlassian__add_comment', {}, toolOptions('t1'));+ const opened = await recorder.waitFor('request.opened', () => true, 1_000);+ await adapter.respondToRequest(SESSION, opened.requestId, 'decline');+ expect(await decision).toEqual({+ behavior: 'deny',+ message: 'The user declined this request. Do not retry it another way.',+ });+ });++ it('keeps "allow for this session" to the session', async () => {+ const { sdk, adapter, recorder } = await startWithConnectors('auto-accept-edits');+ const rule = {+ type: 'addRules',+ rules: [{ toolName: 'mcp__atlassian__search' }],+ behavior: 'allow',+ destination: 'localSettings',+ };+ const decision = sdk.canUseTool()(+ 'mcp__atlassian__search',+ {},+ toolOptions('t1', { suggestions: [rule] })+ );+ const opened = await recorder.waitFor('request.opened', () => true, 1_000);+ await adapter.respondToRequest(SESSION, opened.requestId, 'acceptForSession');+ expect(await decision).toEqual({+ behavior: 'allow',+ updatedPermissions: [{ ...rule, destination: 'session' }],+ });+ });+});diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.tsindex 6d11c7303..da4165546 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts@@ -206,8 +206,14 @@ interface SessionState {drained: Promise<void>;compaction?: { resolve: () => void; reject: (error: Error) => void; boundary: boolean };runtimeMode: ProviderSessionStartInput['runtimeMode'];- /** `mcp__<server>__` prefixes for the servers the caller registered. */- registeredMcpPrefixes: string[];+ /**+ * `mcp__<server>__` prefixes for the registered servers whose tools are+ * allowed without asking: all but the connectors, whose tools follow+ * `runtimeMode`.+ */+ autoApprovedMcpPrefixes: string[];+ /** The connectors' prefixes, by server name, to say which one a request is for. */+ connectorMcpPrefixes: Map<string, string>;input: PromptQueue;turn: ActiveTurn | null;pendingApprovals: Map<string, PendingApproval>;@@ -353,6 +359,13 @@ export function mcpToolPrefixes(names: string[]): string[] {return names.map((name) => `mcp__${name.replace(/[^A-Za-z0-9_-]/g, '_')}__`);}+/** `{ connector }` when `toolName` is one of the session's connectors' tools. */+function connectorOf(session: SessionState, toolName: string): { connector?: string } {+ for (const [name, prefix] of session.connectorMcpPrefixes)+ if (toolName.startsWith(prefix)) return { connector: name };+ return {};+}+/** Rescoped so "allow for this session" never writes a rule to the user's settings. */function sessionScoped(suggestions: readonly PermissionUpdate[] | undefined): PermissionUpdate[] {return (suggestions ?? []).map((suggestion) => ({ ...suggestion, destination: 'session' }));@@ -444,12 +457,10 @@ export class ClaudeAdapter implements ProviderAdapter {filterShadowedWarningOnce();- // SDK 0.3.260 otherwise inserts --permission-mode default before spawning the CLI.- const options: Options & { resolvePermissionModeInCli: boolean } = {- resolvePermissionModeInCli: true,+ const options: Options = {cwd: input.cwd,env: input.env,- ...(permissionMode ? { permissionMode } : {}),+ permissionMode,strictMcpConfig: false,// The connector plugin Switch used to ship would add a second Switch// server with its own connection; kept off for installs that still have it.@@ -503,7 +514,12 @@ export class ClaudeAdapter implements ProviderAdapter {query: running,drained: Promise.resolve(),runtimeMode: input.runtimeMode,- registeredMcpPrefixes: mcpToolPrefixes(Object.keys(mcpServers)),+ autoApprovedMcpPrefixes: mcpToolPrefixes(+ Object.keys(mcpServers).filter((name) => !input.connectorMcpServers.includes(name))+ ),+ connectorMcpPrefixes: new Map(+ input.connectorMcpServers.map((name) => [name, mcpToolPrefixes([name])[0]!])+ ),input: prompt,turn: null,pendingApprovals: new Map(),@@ -1096,7 +1112,7 @@ export class ClaudeAdapter implements ProviderAdapter {});return { behavior: 'allow' };}- if (session.registeredMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {+ if (session.autoApprovedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {return { behavior: 'allow' };}return this.requestApproval(session, toolName, toolInput, options);@@ -1198,6 +1214,7 @@ export class ClaudeAdapter implements ProviderAdapter {requestType: requestTypeForTool(toolName),...approvalContent(toolName, toolInput, options.title, options.description),options: APPROVAL_OPTIONS,+ ...connectorOf(session, toolName),raw: { source: 'claude', payload: { toolName, toolInput } },});});diff --git a/console/packages/agent-providers/src/claude/claude-mapping.test.ts b/console/packages/agent-providers/src/claude/claude-mapping.test.tsnew file mode 100644index 000000000..16714cbcf--- /dev/null+++ b/console/packages/agent-providers/src/claude/claude-mapping.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';+import { approvalContent, mcpToolParts } from './claude-mapping';++describe('mcpToolParts', () => {+ it('splits a tool name into its server and tool', () => {+ expect(mcpToolParts('mcp__atlassian__addCommentToJiraIssue')).toEqual({+ server: 'atlassian',+ tool: 'addCommentToJiraIssue',+ });+ expect(mcpToolParts('mcp__google_workspace__docs_get')).toEqual({+ server: 'google_workspace',+ tool: 'docs_get',+ });+ });++ it('finds nothing in a name that is not an MCP tool', () => {+ expect(mcpToolParts('Bash')).toBeUndefined();+ expect(mcpToolParts('mcp__atlassian')).toBeUndefined();+ expect(mcpToolParts('mcp__atlassian__')).toBeUndefined();+ });+});++describe('approvalContent for an MCP tool', () => {+ it('names the server and tool and shows the input', () => {+ expect(+ approvalContent(+ 'mcp__atlassian__addCommentToJiraIssue',+ { issueIdOrKey: 'PROJ-1', commentBody: 'Shipped in 1.2.' },+ 'Claude wants to use addCommentToJiraIssue',+ undefined+ )+ ).toEqual({+ title: 'atlassian wants to run addCommentToJiraIssue',+ detail: '{"issueIdOrKey":"PROJ-1","commentBody":"Shipped in 1.2."}',+ });+ });++ it('leaves the detail out when there is no input', () => {+ expect(approvalContent('mcp__datadog__list_monitors', {}, undefined, undefined)).toEqual({+ title: 'datadog wants to run list_monitors',+ });+ });++ it('keeps a description the SDK sends, in the title', () => {+ expect(+ approvalContent('mcp__datadog__list_monitors', {}, undefined, 'Lists every monitor')+ ).toEqual({ title: 'datadog wants to run list_monitors — Lists every monitor' });+ });++ it('shows a long comment in full up to the limit, and says what it cut', () => {+ const readable = 'a'.repeat(900);+ const shown = approvalContent(+ 'mcp__atlassian__addComment',+ { body: readable },+ undefined,+ undefined+ );+ expect(shown.detail).toBe(JSON.stringify({ body: readable }));++ const long = 'b'.repeat(1200);+ const cut = approvalContent('mcp__atlassian__addComment', { body: long }, undefined, undefined);+ const json = JSON.stringify({ body: long });+ expect(cut.detail).toBe(+ `${json.slice(0, 1000)}… (${json.length - 1000} more characters not shown)`+ );+ });+});diff --git a/console/packages/agent-providers/src/claude/claude-mapping.ts b/console/packages/agent-providers/src/claude/claude-mapping.tsindex ea5ad10c2..1f2162ff9 100644--- a/console/packages/agent-providers/src/claude/claude-mapping.ts+++ b/console/packages/agent-providers/src/claude/claude-mapping.ts@@ -1,6 +1,11 @@-import type { McpServerConfig, SDKResultMessage } from '@anthropic-ai/claude-agent-sdk';+import type {+ McpServerConfig,+ PermissionMode,+ SDKResultMessage,+} from '@anthropic-ai/claude-agent-sdk';import type { McpServerSpec, RuntimeMode } from '../adapter';import type { ItemType, RequestType, TurnOutcome, UserInputQuestion } from '../events';+import { mcpApprovalContent } from '../mcp-approval';const COMMAND_TOOLS = new Set(['Bash', 'BashOutput', 'KillShell', 'KillBash']);const FILE_CHANGE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);@@ -9,11 +14,17 @@ const SUBAGENT_TOOLS = new Set(['Agent', 'Task']);const MCP_PREFIX = 'mcp__';+/**+ * Every mode names its permission mode, so the CLI never falls back to the+ * `defaultMode` in the person's own Claude Code settings: with `auto` there,+ * the CLI settles tool calls before `canUseTool` is asked, and connector tools+ * would run without the approval this mode promises.+ */export const PERMISSION_MODE_BY_RUNTIME_MODE = {- 'approval-required': undefined,+ 'approval-required': 'default','auto-accept-edits': 'acceptEdits','full-access': 'bypassPermissions',-} as const satisfies Record<RuntimeMode, string | undefined>;+} as const satisfies Record<RuntimeMode, PermissionMode>;export function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);@@ -33,6 +44,15 @@ export function isMcpTool(toolName: string): boolean {return toolName.startsWith(MCP_PREFIX);}+/** The server and tool in Claude's `mcp__<server>__<tool>` name. */+export function mcpToolParts(toolName: string): { server: string; tool: string } | undefined {+ if (!isMcpTool(toolName)) return undefined;+ const rest = toolName.slice(MCP_PREFIX.length);+ const split = rest.indexOf('__');+ if (split <= 0 || split + 2 >= rest.length) return undefined;+ return { server: rest.slice(0, split), tool: rest.slice(split + 2) };+}+export function itemTypeForTool(toolName: string): ItemType {if (COMMAND_TOOLS.has(toolName)) return 'command_execution';if (FILE_CHANGE_TOOLS.has(toolName)) return 'file_change';@@ -85,9 +105,15 @@ export function toolTitle(toolName: string, input: Record<string, unknown>): str** Both halves of the prose are kept when the host sends both: a title says what* the command is for and a description often says what it will cost, and- * someone deciding needs the second one most. Nothing is cut here — a consumer- * that cuts also records that it did, and answers for whether what survived is- * still enough to decide on. Cutting first hides that judgement from it.+ * someone deciding needs the second one most. Prose is not cut here — a+ * consumer that cuts also records that it did, and answers for whether what+ * survived is still enough to decide on. Cutting first hides that judgement+ * from it.+ *+ * An MCP tool is titled by its server and tool, and its input is the detail:+ * the input is what will run, the text of a comment included, and the SDK+ * rarely describes the call. Input can be any size, so it is the one thing cut+ * here, and the cut says so (`mcpApprovalContent`).*/export function approvalContent(toolName: string,@@ -106,6 +132,11 @@ export function approvalContent(};}}+ const mcp = mcpToolParts(toolName);+ if (mcp) {+ const content = mcpApprovalContent(mcp.server, mcp.tool, input);+ return description ? { ...content, title: `${content.title} — ${description}` } : content;+ }return {title: title ?? toolTitle(toolName, input),...(description ? { detail: description } : {}),diff --git a/console/packages/agent-providers/src/codex/codex-adapter.test.ts b/console/packages/agent-providers/src/codex/codex-adapter.test.tsindex 1b906dd9f..b17e0373e 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.test.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.test.ts@@ -37,7 +37,9 @@ function eventsOf<T extends ProviderRuntimeEventType>();}-async function start(runtimeMode: 'full-access' | 'approval-required' = 'full-access') {+async function start(+ runtimeMode: 'full-access' | 'approval-required' | 'auto-accept-edits' = 'full-access'+) {const adapter = createCodexAdapter();const events: ProviderRuntimeEvent[] = [];adapter.subscribe((event) => events.push(event));@@ -47,6 +49,7 @@ async function start(runtimeMode: 'full-access' | 'approval-required' = 'full-acruntimeMode,env: { PATH: '/usr/bin' },mcpServers: {},+ connectorMcpServers: [],});const server = servers.at(-1);if (!server) throw new Error('fake app-server was not spawned');@@ -101,6 +104,7 @@ describe('CodexAdapter', () => {runtimeMode: 'full-access',env: { PATH: '/usr/bin', CODEX_HOME: home },mcpServers: {},+ connectorMcpServers: [],resume: { nativeSessionId: THREAD },});const server = servers.at(-1)!;@@ -126,6 +130,7 @@ describe('CodexAdapter', () => {runtimeMode: 'approval-required',env: { PATH: '/usr/bin' },mcpServers: {},+ connectorMcpServers: [],resume: { nativeSessionId: 'missing' },});const server = servers.at(-1)!;@@ -146,6 +151,7 @@ describe('CodexAdapter', () => {runtimeMode: 'approval-required',env: { PATH: '/usr/bin' },mcpServers: {},+ connectorMcpServers: [],resume: { nativeSessionId: 'missing' },});const server = servers.at(-1)!;@@ -164,13 +170,30 @@ describe('CodexAdapter', () => {expect(adapter.hasSession('resume')).toBe(false);});- it('asks for approvals in approval-required mode', async () => {+ it('marks the working directory untrusted in approval-required mode, not a retired policy', async () => {const { server } = await start('approval-required');const threadStart = server.received.find((message) => message.method === 'thread/start');expect(threadStart?.params).not.toHaveProperty('sandbox');- expect(threadStart?.params).toMatchObject({- approvalPolicy: 'untrusted',- });+ expect(threadStart?.params).not.toHaveProperty('approvalPolicy');+ const args = (server as unknown as { spawnArgs: string[] }).spawnArgs;+ const override = args.indexOf('-c');+ expect(args.slice(override, override + 2)).toEqual([+ '-c',+ 'projects={"/work"={trust_level="untrusted"}}',+ ]);+ });++ it('sends on-request for auto-accept-edits and never for full access, with no project override', async () => {+ for (const [mode, approvalPolicy] of [+ ['auto-accept-edits', 'on-request'],+ ['full-access', 'never'],+ ] as const) {+ const { server } = await start(mode);+ const threadStart = server.received.find((message) => message.method === 'thread/start');+ expect(threadStart?.params).toMatchObject({ approvalPolicy });+ const args = (server as unknown as { spawnArgs: string[] }).spawnArgs;+ expect(args.some((arg) => arg.startsWith('projects='))).toBe(false);+ }});it('carries systemContext as developer instructions', async () => {@@ -181,6 +204,7 @@ describe('CodexAdapter', () => {runtimeMode: 'full-access',env: {},mcpServers: {},+ connectorMcpServers: [],systemContext: 'you are in a Switch room',});const server = servers.at(-1);@@ -197,6 +221,7 @@ describe('CodexAdapter', () => {runtimeMode: 'full-access',env: { PATH: '/usr/bin' },mcpServers: {},+ connectorMcpServers: [],model: { id: 'start-model', options: { effort: 'low' } },});const server = servers.at(-1)!;@@ -654,3 +679,148 @@ describe('CodexAdapter', () => {await expect(adapter.interruptTurn('nope')).rejects.toThrow(/unknown or stopped session/);});});++describe('CodexAdapter connector tools', () => {+ const META = {+ codex_approval_kind: 'mcp_tool_call',+ persist: ['session', 'always'],+ tool_description: 'Search issues.',+ tool_params: { jql: 'project = DEMO' },+ tool_params_display: [{ name: 'jql', value: 'project = DEMO', display_name: 'JQL' }],+ };++ async function startWithConnector(+ runtimeMode: 'full-access' | 'approval-required' | 'auto-accept-edits'+ ) {+ const adapter = createCodexAdapter();+ const events: ProviderRuntimeEvent[] = [];+ adapter.subscribe((event) => events.push(event));+ await adapter.startSession({+ sessionId: 'session-1',+ cwd: '/work',+ runtimeMode,+ env: { PATH: '/usr/bin' },+ mcpServers: {+ switch: { transport: 'http', url: 'http://127.0.0.1:4000/mcp' },+ atlassian: { transport: 'http', url: 'http://127.0.0.1:4100/mcp' },+ },+ connectorMcpServers: ['atlassian'],+ });+ const server = servers.at(-1)!;+ server.replyAlways('turn/start', () => ({ turn: { id: 'native-a', status: 'inProgress' } }));+ await adapter.sendTurn({ sessionId: 'session-1', turnId: 'caller-1', text: 'search' });+ server.notify('turn/started', turnNotification('native-a', 'inProgress'));+ return { adapter, events, server };+ }++ function elicit(server: FakeAppServer, id: number, meta: Record<string, unknown> | null) {+ server.send({+ id,+ method: 'mcpServer/elicitation/request',+ params: {+ threadId: THREAD,+ turnId: 'native-a',+ serverName: 'atlassian',+ mode: 'form',+ ...(meta ? { _meta: meta } : {}),+ message: 'Allow the atlassian MCP server to run tool "search"?',+ requestedSchema: { type: 'object', properties: {} },+ },+ });+ }++ async function answer(+ adapter: Awaited<ReturnType<typeof startWithConnector>>['adapter'],+ events: ProviderRuntimeEvent[],+ server: FakeAppServer,+ id: number,+ decision: 'accept' | 'acceptForSession' | 'decline'+ ) {+ await vi.waitFor(() => expect(eventsOf(events, 'request.opened')).toHaveLength(1));+ const opened = eventsOf(events, 'request.opened')[0]!;+ await adapter.respondToRequest('session-1', opened.requestId, decision);+ await vi.waitFor(() =>+ expect(server.received.some((message) => message.id === id && message.result)).toBe(true)+ );+ return server.received.find((message) => message.id === id)?.result;+ }++ it('opens a card naming the server and tool, with the arguments as the detail', async () => {+ const { events, server } = await startWithConnector('approval-required');+ elicit(server, 71, META);+ await vi.waitFor(() => expect(eventsOf(events, 'request.opened')).toHaveLength(1));+ const opened = eventsOf(events, 'request.opened')[0]!;+ expect(opened).toMatchObject({+ requestType: 'mcp_tool_approval',+ turnId: 'caller-1',+ title: 'atlassian wants to run search',+ detail: 'JQL: project = DEMO',+ connector: 'atlassian',+ });+ expect(opened.options.map((option) => option.decision)).toEqual([+ 'accept',+ 'acceptForSession',+ 'decline',+ 'cancel',+ ]);+ });++ it('answers accept for this one call', async () => {+ const { adapter, events, server } = await startWithConnector('approval-required');+ elicit(server, 72, META);+ expect(await answer(adapter, events, server, 72, 'accept')).toEqual({+ action: 'accept',+ content: {},+ _meta: null,+ });+ });++ it('keeps an accept for the session in _meta, where Codex reads it', async () => {+ const { adapter, events, server } = await startWithConnector('auto-accept-edits');+ elicit(server, 73, META);+ expect(await answer(adapter, events, server, 73, 'acceptForSession')).toEqual({+ action: 'accept',+ content: {},+ _meta: { persist: 'session' },+ });+ });++ it('answers decline so Codex fails the call without running it', async () => {+ const { adapter, events, server } = await startWithConnector('approval-required');+ elicit(server, 74, META);+ expect(await answer(adapter, events, server, 74, 'decline')).toMatchObject({+ action: 'decline',+ content: null,+ });+ });++ it("opens a server's own elicitation as the generic card", async () => {+ const { events, server } = await startWithConnector('approval-required');+ elicit(server, 75, null);+ await vi.waitFor(() => expect(eventsOf(events, 'request.opened')).toHaveLength(1));+ const opened = eventsOf(events, 'request.opened')[0]!;+ expect(opened.title).toBe('atlassian needs a decision');+ expect(opened.detail).toBe('Allow the atlassian MCP server to run tool "search"?');+ expect(opened.options.map((option) => option.decision)).toEqual([+ 'accept',+ 'decline',+ 'cancel',+ ]);+ });++ it.each([+ ['approval-required', false],+ ['auto-accept-edits', false],+ ['full-access', true],+ ] as const)(+ 'in %s Switch keeps the approve key and the connector keeps it: %s',+ async (mode, approved) => {+ await startWithConnector(mode);+ const args = (servers.at(-1) as unknown as { spawnArgs: string[] }).spawnArgs;+ expect(args).toContain('mcp_servers.switch.default_tools_approval_mode="approve"');+ expect(args.includes('mcp_servers.atlassian.default_tools_approval_mode="approve"')).toBe(+ approved+ );+ }+ );+});diff --git a/console/packages/agent-providers/src/codex/codex-adapter.ts b/console/packages/agent-providers/src/codex/codex-adapter.tsindex c3d762021..0100facf8 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.ts@@ -33,7 +33,7 @@ import {type ProviderLogger,} from '../transport/stdio-json-rpc';import { CumulativeUsage, mergeUsage, type UsageCounts } from '../usage';-import { featureArgs, mcpServerConfigArgs } from './config-args';+import { featureArgs, mcpServerConfigArgs, tomlString } from './config-args';import { mapCodexItem } from './item-mapping';import {CODEX_CLIENT_METHODS,@@ -51,6 +51,7 @@ import {type CodexInitializeParams,type CodexItemNotification,type CodexMcpElicitationParams,+ type CodexMcpToolCallMeta,type CodexPermissionsApprovalParams,type CodexThreadItem,type CodexThreadOpenResponse,@@ -122,20 +123,46 @@ interface CodexSessionState {unreportedUsage: TokenUsage[];/** The last model call's size against the window, cleared when a compaction makes it stale. */context?: { usedTokens: number; windowTokens: number | null };+ /** Servers whose tool calls Codex asks about, rather than approving them itself. */+ connectorMcpServers: Set<string>;}interface ThreadModeConfig {- approvalPolicy: CodexAskForApproval;+ /** Sent with the thread; null leaves the policy to the configuration the process was started with. */+ approvalPolicy: CodexAskForApproval | null;+ /** `-c` overrides for the `codex app-server` process. */+ configArgs: string[];}-function threadModeConfig(mode: RuntimeMode): ThreadModeConfig {+/**+ * How each runtime mode reaches Codex.+ *+ * Approval-required once sent `approvalPolicy: "untrusted"`, which asked+ * before every command outside Codex's small safe list. Codex retired that+ * value (0.162 refuses it in configuration, and its migration guide says to+ * remove it); the replacement it documents is marking the working directory+ * `trust_level = "untrusted"`, under which commands need approval unless an+ * execution-policy rule allows them. `on-request` is not that: it runs+ * anything the sandbox permits without asking. The mark goes on this+ * process's command line as an inline table, which replaces the user's own+ * `projects` entries for the process, so the `trusted` entry Console writes+ * for the directory does not override it. Verified against 0.162.1: a plain+ * `date` and an MCP tool call both ask, and a symlinked directory matches as+ * long as `cwd` is spelt the same way in both places. One consequence named+ * in Codex's guide: an untrusted project does not load its own `.codex/`+ * configuration.+ */+function threadModeConfig(mode: RuntimeMode, cwd: string): ThreadModeConfig {switch (mode) {case 'approval-required':- return { approvalPolicy: 'untrusted' };+ return {+ approvalPolicy: null,+ configArgs: ['-c', `projects={${tomlString(cwd)}={trust_level="untrusted"}}`],+ };case 'auto-accept-edits':- return { approvalPolicy: 'on-request' };+ return { approvalPolicy: 'on-request', configArgs: [] };case 'full-access':- return { approvalPolicy: 'never' };+ return { approvalPolicy: 'never', configArgs: [] };}}@@ -190,6 +217,27 @@ function turnOutcomeOf(status: CodexTurnNotification['turn']['status']): TurnOut}}+/**+ * The card for Codex asking to run an MCP tool: the server and tool in the+ * title, the arguments as the detail. Codex names the tool only in its+ * message, so a message worded otherwise leaves the tool out of the title.+ */+function mcpToolCallContent(+ serverName: string,+ message: string,+ meta: CodexMcpToolCallMeta+): { title: string; detail?: string } {+ const tool = /run tool "([^"]+)"/.exec(message)?.[1];+ const title = tool ? `${serverName} wants to run ${tool}` : `${serverName} wants to run a tool`;+ const detail = (meta.tool_params_display ?? [])+ .map(({ name, display_name, value }) => {+ const shown = typeof value === 'string' ? value : JSON.stringify(value);+ return `${display_name ?? name}: ${shown}`;+ })+ .join('\n');+ return detail ? { title, detail } : { title };+}+function approvalOptions(decisions: ApprovalDecision[]): ApprovalOption[] {const labels: Record<ApprovalDecision, string> = {accept: 'Approve',@@ -280,8 +328,9 @@ export class CodexAdapter implements ProviderAdapter {if (this.sessions.has(input.sessionId)) {throw new ProviderSessionError(PROVIDER, input.sessionId, 'session already started');}- const mcp = mcpServerConfigArgs(input.mcpServers);- const args = ['app-server', ...featureArgs(this.features), ...mcp.args];+ const mode = threadModeConfig(input.runtimeMode, input.cwd);+ const mcp = mcpServerConfigArgs(input.mcpServers, input.connectorMcpServers, input.runtimeMode);+ const args = ['app-server', ...featureArgs(this.features), ...mode.configArgs, ...mcp.args];const client = new StdioJsonRpcClient({command: this.binaryPath,args,@@ -307,6 +356,7 @@ export class CodexAdapter implements ProviderAdapter {exited: false,usage: new CumulativeUsage(),unreportedUsage: [],+ connectorMcpServers: new Set(input.connectorMcpServers),};this.sessions.set(input.sessionId, state);this.registerHandlers(state);@@ -325,11 +375,10 @@ export class CodexAdapter implements ProviderAdapter {if (!account.account && account.requiresOpenaiAuth)throw new Error('Sign in on the execution machine with codex login.');- const mode = threadModeConfig(input.runtimeMode);const sandbox = await configuredSandbox(input.env.CODEX_HOME);const config = {cwd: input.cwd,- approvalPolicy: mode.approvalPolicy,+ ...(mode.approvalPolicy ? { approvalPolicy: mode.approvalPolicy } : {}),...(sandbox ? { sandbox } : {}),approvalsReviewer: 'user' as const,...(input.model?.id ? { model: input.model.id } : {}),@@ -820,16 +869,29 @@ export class CodexAdapter implements ProviderAdapter {client.onServerRequest(CODEX_SERVER_REQUESTS.mcpElicitation, (params) => {const payload = params as CodexMcpElicitationParams;+ const toolCall =+ payload._meta?.codex_approval_kind === 'mcp_tool_call' ? payload._meta : null;+ // Codex keeps an approval for the thread only when the answer says so+ // in `_meta`; the same `persist` inside `content` does nothing.+ const forSession = toolCall?.persist?.includes('session') ?? false;return this.openApproval(state, {turnId: payload.turnId ?? state.activeNativeTurnId ?? '',requestType: 'mcp_tool_approval',- title: `${payload.serverName} needs a decision`,- detail: payload.message,- options: approvalOptions(['accept', 'decline', 'cancel']),+ ...(toolCall+ ? mcpToolCallContent(payload.serverName, payload.message, toolCall)+ : { title: `${payload.serverName} needs a decision`, detail: payload.message }),+ options: approvalOptions(+ forSession+ ? ['accept', 'acceptForSession', 'decline', 'cancel']+ : ['accept', 'decline', 'cancel']+ ),+ ...(state.connectorMcpServers.has(payload.serverName)+ ? { connector: payload.serverName }+ : {}),respond: (decision) => ({action: decision === 'decline' ? 'decline' : decision === 'cancel' ? 'cancel' : 'accept',content: decision === 'accept' || decision === 'acceptForSession' ? {} : null,- _meta: null,+ _meta: decision === 'acceptForSession' ? { persist: 'session' } : null,}),});});@@ -867,6 +929,7 @@ export class CodexAdapter implements ProviderAdapter {title: string;detail?: string;options: ApprovalOption[];+ connector?: string;respond: (decision: ApprovalDecision) => unknown;}): Promise<unknown> {@@ -882,6 +945,7 @@ export class CodexAdapter implements ProviderAdapter {title: spec.title,...(spec.detail ? { detail: spec.detail } : {}),options: spec.options,+ ...(spec.connector ? { connector: spec.connector } : {}),});});}diff --git a/console/packages/agent-providers/src/codex/config-args.test.ts b/console/packages/agent-providers/src/codex/config-args.test.tsindex 506292bd1..9ad8e6dda 100644--- a/console/packages/agent-providers/src/codex/config-args.test.ts+++ b/console/packages/agent-providers/src/codex/config-args.test.ts@@ -4,14 +4,18 @@ import { featureArgs, mcpServerConfigArgs } from './config-args';describe('mcpServerConfigArgs', () => {it('turns a stdio server into TOML config overrides', () => {expect(- mcpServerConfigArgs({- switch_echo: {- transport: 'stdio',- command: '/usr/bin/node',- args: ['/tmp/echo.mjs', '--flag'],- env: { SWITCH_API_TOKEN: 'shh' },+ mcpServerConfigArgs(+ {+ switch_echo: {+ transport: 'stdio',+ command: '/usr/bin/node',+ args: ['/tmp/echo.mjs', '--flag'],+ env: { SWITCH_API_TOKEN: 'shh' },+ },},- }).args+ [],+ 'approval-required'+ ).args).toEqual(['-c','mcp_servers.switch_echo.command="/usr/bin/node"',@@ -26,9 +30,13 @@ describe('mcpServerConfigArgs', () => {it('turns an http server into url and header overrides', () => {expect(- mcpServerConfigArgs({- switch: { transport: 'http', url: 'https://example.test/mcp', headers: { A: 'b' } },- })+ mcpServerConfigArgs(+ {+ switch: { transport: 'http', url: 'https://example.test/mcp', headers: { A: 'b' } },+ },+ [],+ 'approval-required'+ )).toEqual({args: ['-c',@@ -43,13 +51,17 @@ describe('mcpServerConfigArgs', () => {});it('hands a bearer token over by variable name, keeping it off the command line', () => {- const { args, env } = mcpServerConfigArgs({- switch: {- transport: 'http',- url: 'http://127.0.0.1:4567/mcp',- headers: { Authorization: 'Bearer secret-token', 'X-Other': 'x' },+ const { args, env } = mcpServerConfigArgs(+ {+ switch: {+ transport: 'http',+ url: 'http://127.0.0.1:4567/mcp',+ headers: { Authorization: 'Bearer secret-token', 'X-Other': 'x' },+ },},- });+ [],+ 'approval-required'+ );expect(args).toEqual(['-c','mcp_servers.switch.url="http://127.0.0.1:4567/mcp"',@@ -65,15 +77,23 @@ describe('mcpServerConfigArgs', () => {});it('omits empty env and headers', () => {- const { args } = mcpServerConfigArgs({- a: { transport: 'stdio', command: 'node', args: [], env: {} },- });+ const { args } = mcpServerConfigArgs(+ {+ a: { transport: 'stdio', command: 'node', args: [], env: {} },+ },+ [],+ 'approval-required'+ );expect(args.join(' ')).not.toContain('.env=');});it('refuses a name that cannot be a TOML bare key', () => {expect(() =>- mcpServerConfigArgs({ 'switch.echo': { transport: 'stdio', command: 'node', args: [] } })+ mcpServerConfigArgs(+ { 'switch.echo': { transport: 'stdio', command: 'node', args: [] } },+ [],+ 'approval-required'+ )).toThrow(/cannot be expressed as a Codex config key/);});});@@ -90,9 +110,57 @@ describe('featureArgs', () => {});it('forwards MCP credentials by name without putting values in argv', () => {- const { args } = mcpServerConfigArgs({- switch: { transport: 'stdio', command: 'node', args: [], envVars: ['SWITCH_API_TOKEN'] },- });+ const { args } = mcpServerConfigArgs(+ {+ switch: { transport: 'stdio', command: 'node', args: [], envVars: ['SWITCH_API_TOKEN'] },+ },+ [],+ 'approval-required'+ );expect(args).toContain('mcp_servers.switch.env_vars=["SWITCH_API_TOKEN"]');expect(args.some((arg) => arg.startsWith('mcp_servers.switch.env='))).toBe(false);});++describe('connector servers', () => {+ const servers = {+ switch: {+ transport: 'http' as const,+ url: 'http://127.0.0.1:4000/mcp',+ headers: { Authorization: 'Bearer switch-token' },+ },+ atlassian: {+ transport: 'http' as const,+ url: 'http://127.0.0.1:4100/mcp',+ headers: { Authorization: 'Bearer vendor-token' },+ },+ gws: { transport: 'stdio' as const, command: 'node', args: ['gws.mjs'] },+ };+ const approved = (args: string[], name: string) =>+ args.includes(`mcp_servers.${name}.default_tools_approval_mode="approve"`);++ it.each([+ ['approval-required', false],+ ['auto-accept-edits', false],+ ['full-access', true],+ ] as const)('in %s, connectors keep the approve key: %s', (mode, connectorApproved) => {+ const { args } = mcpServerConfigArgs(servers, ['atlassian', 'gws'], mode);+ expect(approved(args, 'switch')).toBe(true);+ expect(approved(args, 'atlassian')).toBe(connectorApproved);+ expect(approved(args, 'gws')).toBe(connectorApproved);+ });++ it('hands both kinds of bearer token over by variable name', () => {+ const { args, env } = mcpServerConfigArgs(servers, ['atlassian', 'gws'], 'approval-required');+ expect(args).toContain(+ 'mcp_servers.switch.bearer_token_env_var="SWITCH_MCP_SWITCH_BEARER_TOKEN"'+ );+ expect(args).toContain(+ 'mcp_servers.atlassian.bearer_token_env_var="SWITCH_MCP_ATLASSIAN_BEARER_TOKEN"'+ );+ expect(args.join(' ')).not.toMatch(/switch-token|vendor-token/);+ expect(env).toEqual({+ SWITCH_MCP_SWITCH_BEARER_TOKEN: 'switch-token',+ SWITCH_MCP_ATLASSIAN_BEARER_TOKEN: 'vendor-token',+ });+ });+});diff --git a/console/packages/agent-providers/src/codex/config-args.ts b/console/packages/agent-providers/src/codex/config-args.tsindex ec98e1fd5..c1da00976 100644--- a/console/packages/agent-providers/src/codex/config-args.ts+++ b/console/packages/agent-providers/src/codex/config-args.ts@@ -1,9 +1,9 @@-import type { McpServerSpec } from '../adapter';+import type { McpServerSpec, RuntimeMode } from '../adapter';/** TOML bare keys; anything else would have to be quoted inside a `-c` dotted path. */const BARE_KEY = /^[A-Za-z0-9_-]+$/;-function tomlString(value: string): string {+export function tomlString(value: string): string {return JSON.stringify(value);}@@ -22,8 +22,20 @@ function tomlStringTable(values: Record<string, string>): string {* `codex app-server` reads MCP servers from config, so a per-session* registration is a set of `-c mcp_servers.<name>.<key>=<toml>` overrides on* the process it is spawned with.+ *+ * Every server's tools are approved without asking (`default_tools_approval_mode+ * = "approve"`) except a connector's, which follow `runtimeMode`: Codex asks+ * through `mcpServer/elicitation/request` under the untrusted project mark and+ * `on-request`. In full access a connector keeps the key too, because under+ * `never` a tool call that needs approval is not allowed but failed ("MCP tool+ * call requires approval, but approval policy is never"), checked against+ * codex-cli 0.162.1.*/-export function mcpServerConfigArgs(servers: Record<string, McpServerSpec>): {+export function mcpServerConfigArgs(+ servers: Record<string, McpServerSpec>,+ connectors: readonly string[],+ runtimeMode: RuntimeMode+): {args: string[];env: Record<string, string>;} {@@ -63,7 +75,8 @@ export function mcpServerConfigArgs(servers: Record<string, McpServerSpec>): {}if (Object.keys(headers).length > 0) push('http_headers', tomlStringTable(headers));}- push('default_tools_approval_mode', tomlString('approve'));+ if (!connectors.includes(name) || runtimeMode === 'full-access')+ push('default_tools_approval_mode', tomlString('approve'));}return { args, env };}diff --git a/console/packages/agent-providers/src/codex/protocol.ts b/console/packages/agent-providers/src/codex/protocol.tsindex cf02d951f..782c83a97 100644--- a/console/packages/agent-providers/src/codex/protocol.ts+++ b/console/packages/agent-providers/src/codex/protocol.ts@@ -43,7 +43,11 @@ export const CODEX_SERVER_REQUESTS = {mcpElicitation: 'mcpServer/elicitation/request',} as const;-export type CodexAskForApproval = 'untrusted' | 'on-request' | 'never';+/**+ * `untrusted` is retired: codex-cli 0.162 refuses it in configuration, and the+ * documented replacement is a project `trust_level` (see `threadModeConfig`).+ */+export type CodexAskForApproval = 'on-request' | 'never';export type CodexSandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access';export type CodexApprovalsReviewer = 'user' | 'auto_review' | 'guardian_subagent';export type CodexTurnStatus = 'completed' | 'interrupted' | 'failed' | 'inProgress';@@ -282,9 +286,25 @@ export interface CodexToolRequestUserInputParams {}>;}+/**+ * What Codex adds to an elicitation it raises to approve an MCP tool call+ * (codex-cli 0.162.1). It names no tool: the tool is only in `message`+ * ("Allow the <server> MCP server to run tool \"<tool>\"?").+ */+export interface CodexMcpToolCallMeta {+ codex_approval_kind?: string;+ /** The scopes an accept may keep the approval for: `session`, `always`. */+ persist?: string[];+ tool_description?: string;+ tool_params?: Record<string, unknown>;+ tool_params_display?: Array<{ name: string; value: unknown; display_name?: string }>;+}+export interface CodexMcpElicitationParams {threadId: string;turnId: string | null;serverName: string;message: string;+ /** Present on a tool-call approval; a server's own elicitation carries none. */+ _meta?: CodexMcpToolCallMeta | null;}diff --git a/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts b/console/packages/agent-providers/src/cursor/cursor-adapter.test.tsindex 15a1ee936..4d499e0e2 100644--- a/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts+++ b/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts@@ -45,6 +45,7 @@ async function setup(resume = false, env: Record<string, string> = {}) {mcpServers: {switch: { transport: 'stdio', command: 'node', args: ['server.js'], env: { MODE: 'test' } },},+ connectorMcpServers: [],...(resume ? { resume: { nativeSessionId: 'native' } } : {}),});const server = servers.at(-1)!;@@ -339,6 +340,7 @@ it('registers an HTTP MCP server with its headers when the agent declares HTTP',runtimeMode: 'approval-required',env: {},mcpServers: httpSwitch,+ connectorMcpServers: [],});expect(servers.at(-1)!.received.find((m) => m.method === 'session/new')?.params).toMatchObject({mcpServers: [@@ -362,6 +364,7 @@ it('refuses to start a session whose HTTP MCP servers the agent cannot reach', aruntimeMode: 'approval-required',env: {},mcpServers: httpSwitch,+ connectorMcpServers: [],})).rejects.toThrow('Cursor CLI does not declare MCP over HTTP');expect(servers.at(-1)!.received.some((m) => m.method === 'session/new')).toBe(false);diff --git a/console/packages/agent-providers/src/events.ts b/console/packages/agent-providers/src/events.tsindex a5c0f591c..ef0a6fc93 100644--- a/console/packages/agent-providers/src/events.ts+++ b/console/packages/agent-providers/src/events.ts@@ -134,6 +134,11 @@ export type ProviderRuntimeEvent = EventBase &*/detail?: string;options: ApprovalOption[];+ /**+ * The connector server whose tool this asks to run, one of the+ * session's `connectorMcpServers`; absent for anything else.+ */+ connector?: string;}| { type: 'request.resolved'; requestId: string; decision: ApprovalDecision }| {diff --git a/console/packages/agent-providers/src/host/attachments.integration.test.ts b/console/packages/agent-providers/src/host/attachments.integration.test.tsindex c6f306719..bec0a9ae7 100644--- a/console/packages/agent-providers/src/host/attachments.integration.test.ts+++ b/console/packages/agent-providers/src/host/attachments.integration.test.ts@@ -91,6 +91,7 @@ itenv,runtimeMode: 'full-access',mcpServers: { echo: echoMcpServerSpec() },+ connectorMcpServers: [],...(provider === 'claude' ? { model: { id: 'claude-sonnet-5' } } : {}),...(provider === 'opencode' ? { model: { id: 'opencode/big-pickle' } } : {}),},diff --git a/console/packages/agent-providers/src/host/bench/daemon.ts b/console/packages/agent-providers/src/host/bench/daemon.tsindex b2843928b..8d87322bf 100644--- a/console/packages/agent-providers/src/host/bench/daemon.ts+++ b/console/packages/agent-providers/src/host/bench/daemon.ts@@ -136,6 +136,7 @@ async function main(): Promise<void> {port: process,authenticate: null,services: { grants: [], unavailable: null },+ servicesChange: null,entrypoint: process.argv[1]!,signal: stop.signal,});diff --git a/console/packages/agent-providers/src/host/service-notices.ts b/console/packages/agent-providers/src/host/service-notices.tsindex 7b7d9a11c..dfb93ba57 100644--- a/console/packages/agent-providers/src/host/service-notices.ts+++ b/console/packages/agent-providers/src/host/service-notices.ts@@ -57,3 +57,47 @@ export function serviceFallbackNotice(service: string, reason: string, fallback:? `${why}, so ${service === 'github' ? 'git and gh use' : 'it uses'} this machine's own ${name} sign-in instead, if it has one.`: `${why}.`;}++/**+ * Shown the first time a session asks to run a connector's tool. Connector+ * tools used to be allowed in every mode; they now follow the agent's mode.+ */+export const CONNECTOR_APPROVAL_NOTICE =+ 'Connector tools ask in this mode. Turn on Bypass permissions for this agent to allow them without asking.';++/** How a notice names a catalog service; the slug for one it does not know. */+export function serviceName(service: string): string {+ const names: Record<string, string> = {+ atlassian: 'Atlassian',+ datadog: 'Datadog',+ github: 'GitHub',+ 'google-workspace': 'Google Workspace',+ };+ return names[service] ?? service;+}++function listed(names: string[]): string {+ return names.length === 1+ ? names[0]!+ : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;+}++/**+ * What a session restarted for a change to its agent's grants is told: the+ * services that went and came. The host cannot tell a service switched off+ * for the workspace from a grant removed, so a removal names both.+ */+export function servicesChangedNotice(removed: string[], added: string[]): string | null {+ const sentences: string[] = [];+ if (removed.length > 0) {+ const one = removed.length === 1;+ sentences.push(+ `${listed(removed.map(serviceName))} ${one ? 'was' : 'were'} removed from this agent's tools: ${one ? 'it was' : 'each was'} switched off for the workspace, or its grant was removed.`+ );+ }+ if (added.length > 0)+ sentences.push(+ `${listed(added.map(serviceName))} ${added.length === 1 ? 'was' : 'were'} added to this agent's tools.`+ );+ return sentences.length > 0 ? sentences.join(' ') : null;+}diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex d0e96231e..ad253932b 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -6,6 +6,7 @@ import type { Command, Session, Snapshot } from '@switch-console/shared/session-import { afterEach, expect, it, vi } from 'vitest';import { ProviderConversationUnavailableError, type ProviderAdapter } from '../adapter';import type { ProviderRuntimeEvent } from '../events';+import { CONNECTOR_APPROVAL_NOTICE, ServiceNotices } from './service-notices';import { HostedSession, lastAssistantText, type RoomReply, unpostedReply } from './session-host';/**@@ -94,6 +95,7 @@ function setup(provider: Session['provider']) {runtimeMode: 'approval-required' as const,env: {},mcpServers: {},+ connectorMcpServers: [],},};return { adapter, config, emit };@@ -1612,3 +1614,59 @@ it('keeps tool input and output off the event stream, the journal and the snapsh},]);});++it("tells its owner when the provider asks to run a connector's tool, and only then", async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-host-test-'));+ roots.push(root);+ const fixture = setup('claude');+ const asked: string[] = [];+ const notices = new ServiceNotices();+ const host = await HostedSession.start(+ root,+ {+ ...fixture.config,+ connectorApproval: (connector) => {+ asked.push(connector);+ notices.raise(CONNECTOR_APPROVAL_NOTICE);+ },+ },+ fixture.adapter+ );+ hosts.push(host);+ notices.attach((message) => host.serviceFallback(message));+ const published: Array<{ type: string; message?: string; request?: { requestId: string } }> = [];+ host.onPublished((event) => published.push(event.body as (typeof published)[number]));+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));+ await host.command(message('turn'));+ const connectorRequest = (requestId: string) => ({+ type: 'request.opened' as const,+ turnId: 'turn',+ requestId,+ requestType: 'mcp_tool_approval' as const,+ title: `atlassian wants to run ${requestId}`,+ options: [{ decision: 'accept' as const, label: 'Allow once' }],+ connector: 'atlassian',+ });+ fixture.emit({+ type: 'request.opened',+ turnId: 'turn',+ requestId: 'bash',+ requestType: 'command_execution_approval',+ title: 'ls',+ options: [{ decision: 'accept', label: 'Allow once' }],+ });+ fixture.emit(connectorRequest('search'));+ fixture.emit(connectorRequest('add_comment'));+ await waitFor(() => expect(host.snapshot().requests).toHaveLength(3));+ await host.barrier();+ expect(asked).toEqual(['atlassian', 'atlassian']);++ const order = published.flatMap((body) =>+ body.type === 'notice' && body.message === CONNECTOR_APPROVAL_NOTICE+ ? ['notice']+ : body.type === 'request.opened' && body.request+ ? [body.request.requestId]+ : []+ );+ expect(order).toEqual(['bash', 'notice', 'search', 'add_comment']);+});diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex a50305dfa..0603ca197 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -75,6 +75,11 @@ export type HostSessionStart = {replyToRoom?: (reply: RoomReply) => Promise<void>;/** Service tokens to scrub from every event before it is recorded; none when absent. */redactions?: Redactions;+ /**+ * Told each time the provider asks to run a connector's tool, before the+ * request is published, so a notice it raises comes ahead of the card.+ */+ connectorApproval?: (connector: string) => void;};/** What the host posts for a turn a room message started that ended without the agent posting. */export type RoomReply = { roomId: string; threadId: string | null; body: string };@@ -1168,6 +1173,8 @@ export class HostedSession {},};this.questions.set(request.requestId, { request, options });+ if (event.type === 'request.opened' && event.connector !== undefined)+ this.config.connectorApproval?.(event.connector);await this.publish({ type: 'request.opened', request });}if (event.type === 'request.resolved' || event.type === 'user-input.resolved') {diff --git a/console/packages/agent-providers/src/host/session-services.test.ts b/console/packages/agent-providers/src/host/session-services.test.tsindex 294b7cbdc..de1e85a0e 100644--- a/console/packages/agent-providers/src/host/session-services.test.ts+++ b/console/packages/agent-providers/src/host/session-services.test.ts@@ -7,6 +7,7 @@ import {recordedServicesShape,recordSessionServices,servicesChanged,+ servicesChangeSince,servicesShape,} from './session-services';@@ -95,3 +96,61 @@ describe('whether a session’s grants changed', () => {expect(servicesChanged('[]', null)).toBe(false);});});++describe('what a restarted session is told about its services', () => {+ const services = (...names: string[]) => ({+ grants: names.map((name) => grant(name)),+ unavailable: null,+ });+ const shape = (...names: string[]) => servicesShape(services(...names));+ const REMOVED_DATADOG =+ "Datadog was removed from this agent's tools: it was switched off for the workspace, or its grant was removed.";++ it('names a service taken away, and both reasons it may have gone', () => {+ expect(servicesChangeSince(shape('atlassian', 'datadog'), services('atlassian'))).toBe(+ REMOVED_DATADOG+ );+ });++ it('names a service given back, and several at once', () => {+ expect(servicesChangeSince(shape('atlassian'), services('atlassian', 'datadog'))).toBe(+ "Datadog was added to this agent's tools."+ );+ expect(+ servicesChangeSince(shape('datadog', 'github', 'google-workspace'), services('atlassian'))+ ).toBe(+ "Datadog, GitHub and Google Workspace were removed from this agent's tools: each was switched off for the workspace, or its grant was removed. Atlassian was added to this agent's tools."+ );+ });++ it('says nothing when the same services stay, whatever changed in them', () => {+ expect(+ servicesChangeSince(shape('datadog'), {+ grants: [grant('datadog', { tools: ['search'] })],+ unavailable: null,+ })+ ).toBeNull();+ });++ it('says nothing for a new session, or when either side is unknown', () => {+ expect(servicesChangeSince(undefined, services('datadog'))).toBeNull();+ expect(servicesChangeSince(null, services('datadog'))).toBeNull();+ expect(+ servicesChangeSince(shape('datadog'), { grants: [], unavailable: 'Switch is unreachable' })+ ).toBeNull();+ });++ it('is said once for a change: the restart records the grants it started with', async () => {+ // What each start of a session's host does, in order: read the previous+ // host's record, then replace it with its own.+ const root = await mkdtemp(join(tmpdir(), 'session-services-'));+ const hostStarts = async (now: ReturnType<typeof services>) => {+ const change = servicesChangeSince(await recordedServicesShape(root), now);+ await recordSessionServices(root, now);+ return change;+ };+ expect(await hostStarts(services('atlassian', 'datadog'))).toBeNull();+ expect(await hostStarts(services('atlassian'))).toBe(REMOVED_DATADOG);+ expect(await hostStarts(services('atlassian'))).toBeNull();+ });+});diff --git a/console/packages/agent-providers/src/host/session-services.ts b/console/packages/agent-providers/src/host/session-services.tsindex 422b8caf8..f63ca687c 100644--- a/console/packages/agent-providers/src/host/session-services.ts+++ b/console/packages/agent-providers/src/host/session-services.ts@@ -2,6 +2,7 @@ import { readFile, rename, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { z } from 'zod';import type { ServiceGrant } from './service-access';+import { servicesChangedNotice } from './service-notices';import { type SessionServices, type SharedHostConfig, sessionServiceGrants } from './shared-config';/**@@ -81,6 +82,31 @@ export function servicesChanged(return recorded !== undefined && current !== null && recorded !== current;}+const shapeServicesSchema = z.array(z.object({ service: z.string() }));++/**+ * What a session is told about services that went or came since its host+ * last started: null for a host with no record (a new session, or one from+ * before the record), for grants that could not be read on either side, or+ * when the same services are granted (their tools changed, say).+ */+export function servicesChangeSince(+ recorded: string | null | undefined,+ services: SessionServices+): string | null {+ const current = servicesShape(services);+ if (recorded === undefined || recorded === null || !servicesChanged(recorded, current))+ return null;+ const parsed = shapeServicesSchema.safeParse(JSON.parse(recorded));+ if (!parsed.success) return null;+ const before = new Set(parsed.data.map((grant) => grant.service));+ const after = new Set(services.grants.map((grant) => grant.service));+ return servicesChangedNotice(+ [...before].filter((service) => !after.has(service)).sort(),+ [...after].filter((service) => !before.has(service)).sort()+ );+}+/** The shape of the agent's grants as they stand now, read as the watcher's template reaches Switch. */export async function currentServicesShape(template: SharedHostConfig): Promise<string | null> {return servicesShape(await sessionServiceGrants(template));diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.tsindex 992b2da47..2f5490f6e 100644--- a/console/packages/agent-providers/src/host/shared-config.test.ts+++ b/console/packages/agent-providers/src/host/shared-config.test.ts@@ -402,6 +402,43 @@ describe('the skills of the agent’s service grants', () => {}});+ it('name the granted vendors, MCP and CLI alike, as the connectors, never Switch', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));+ const served = (port: number) => ({+ transport: 'http' as const,+ url: `http://127.0.0.1:${port}/mcp`,+ });+ try {+ const prepared = await prepareSharedConfig(+ root,+ await configFor(root, 'claude'),+ runtime,+ NO_SERVICES,+ null,+ // A vendor MCP server and a vendor CLI, both served on loopback.+ { atlassian: served(4400), 'google-workspace': served(4401) }+ );+ expect(prepared.input.connectorMcpServers.sort()).toEqual(['atlassian', 'google-workspace']);+ expect(prepared.input.connectorMcpServers).not.toContain('switch');+ expect(Object.keys(prepared.input.mcpServers).sort()).toEqual([+ 'atlassian',+ 'google-workspace',+ 'switch',+ ]);+ const none = await prepareSharedConfig(+ root,+ await configFor(root, 'claude'),+ runtime,+ NO_SERVICES,+ null,+ {}+ );+ expect(none.input.connectorMcpServers).toEqual([]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+it('tell the session when they could not be loaded', async () => {const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));try {diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.tsindex 4f04b81c2..9fcab6598 100644--- a/console/packages/agent-providers/src/host/shared-config.ts+++ b/console/packages/agent-providers/src/host/shared-config.ts@@ -6,7 +6,7 @@ import { join } from 'node:path';import { promisify } from 'node:util';import { sessionSchema } from '@switch-console/shared/session-v1';import { z } from 'zod';-import type { HttpMcpServerSpec } from '../adapter';+import type { HttpMcpServerSpec, ProviderSessionStartInput } from '../adapter';import { prepareCodexSessionHome } from '../codex/home';import { agentHasOwnUser } from './host-permissions';import { type HostedCredential, hostedCredentialSchema } from './provider-login';@@ -117,7 +117,9 @@ export function servicesUnavailableNotice(reason: string): string {* granted GitHub gets Git's credential helper and the `gh` wrapper, which ask* the session's service endpoint for the token. `vendors` are the granted* vendors' MCP servers this host serves on loopback (`vendor-mcp.ts`), given- * to the CLI beside Switch's own under their own names.+ * to the CLI beside Switch's own under their own names, and named in+ * `connectorMcpServers`, so their tools follow the session's runtime mode+ * where Switch's own are always allowed.*/export async function prepareSharedConfig(root: string,@@ -209,7 +211,13 @@ export async function prepareSharedConfig(input.mcpServers.switch = runtime;if (!agentApiUrl || !token)throw new Error('Shared SDK host requires execution-host Switch credentials.');- return { agentApiUrl, token, input, notices };+ // Read from the grants as the session starts, never from the saved+ // configuration, so a resume follows the grants as they are then.+ const started: ProviderSessionStartInput = {+ ...input,+ connectorMcpServers: Object.keys(vendors),+ };+ return { agentApiUrl, token, input: started, notices };}/**diff --git a/console/packages/agent-providers/src/host/shared-daemon.ts b/console/packages/agent-providers/src/host/shared-daemon.tsindex b9c4e65f0..f2221da0e 100644--- a/console/packages/agent-providers/src/host/shared-daemon.ts+++ b/console/packages/agent-providers/src/host/shared-daemon.ts@@ -16,7 +16,11 @@ import { adapterFor } from './server';import { grantedSkills } from './service-access';import { runGitCredentialHelper, runGitHubCli } from './service-github';import { HOST_EXIT_GRACE_MS, SessionLinks } from './session-channel';-import { recordSessionServices } from './session-services';+import {+ recordedServicesShape,+ recordSessionServices,+ servicesChangeSince,+} from './session-services';import {readProviderLogin,readSharedCredentials,@@ -46,6 +50,7 @@ async function main(): Promise<void> {cwd: mode,runtimeMode: 'approval-required',mcpServers: {},+ connectorMcpServers: [],env: Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined@@ -208,6 +213,17 @@ async function main(): Promise<void> {process.on('disconnect', () => stop.abort());try {const services = await sessionServiceGrants(config);+ // Read before this host's own record replaces it: a host restarted+ // because a service was taken away or granted says which.+ const servicesChange = servicesChangeSince(+ await recordedServicesShape(resolve(root)).catch((error: unknown) => {+ console.warn(+ `Could not read which services this session's previous host started with, so a change to them is not announced: ${error instanceof Error ? error.message : String(error)}`+ );+ return undefined;+ }),+ services+ );// What the watcher compares the agent's grants against, to restart this// host when a service is granted or taken away (`servicesChanged`).await recordSessionServices(resolve(root), services);@@ -221,6 +237,7 @@ async function main(): Promise<void> {grantedSkills(services.grants)),services,+ servicesChange,entrypoint: process.argv[1]!,port: process,authenticate:diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex a153781fb..f383ba7db 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -280,6 +280,7 @@ async function start(runtimeMode: 'approval-required',env: {},mcpServers: {},+ connectorMcpServers: [],},...(opts.rooms ? { roomConnection: { connectionId: 'controller' } } : {}),parent: channel,diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex d22de3b74..37284abae 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -26,7 +26,11 @@ import {} from './room-prompt';import { type ServiceEndpointServer, startServiceEndpoint } from './service-endpoint';import { githubRepositoryVisible } from './service-github';-import { serviceFallbackNotice, ServiceNotices } from './service-notices';+import {+ CONNECTOR_APPROVAL_NOTICE,+ serviceFallbackNotice,+ ServiceNotices,+} from './service-notices';import {connectParent,type BusyReason,@@ -383,6 +387,7 @@ export async function runSharedHost(resumeOperationId: options.resumeOperationId,authenticate: options.authenticate,redactions: options.redactions,+ connectorApproval: () => options.serviceNotices.raise(CONNECTOR_APPROVAL_NOTICE),stageAttachments: (attachments) =>Promise.all(attachments.map((attachment) =>@@ -985,6 +990,11 @@ export async function hostSessionProcess(input: {authenticate: ((input: ProviderSessionStartInput) => Promise<void>) | null;/** The agent's service grants, as this session starts. */services: SessionServices;+ /**+ * What the session is told about services that went or came since its+ * previous host (`servicesChangeSince`); null for nothing.+ */+ servicesChange: string | null;/** This host's bundle, which the session's service helpers run from. */entrypoint: string;signal: AbortSignal;@@ -1058,6 +1068,15 @@ export async function hostSessionProcess(input: {{ ...vendors.specs, ...clis.specs });for (const notice of prepared.notices) serviceNotices.raise(notice);+ // The people watching see it as a notice; the agent reads it with the+ // context it resumes under, so it does not go looking for tools it no+ // longer has.+ if (input.servicesChange !== null) {+ serviceNotices.raise(input.servicesChange);+ prepared.input.systemContext = [prepared.input.systemContext, input.servicesChange]+ .filter(Boolean)+ .join('\n\n');+ }const authenticate = input.authenticate;await runSharedHost({diff --git a/console/packages/agent-providers/src/mcp-approval.ts b/console/packages/agent-providers/src/mcp-approval.tsnew file mode 100644index 000000000..790f7f7a8--- /dev/null+++ b/console/packages/agent-providers/src/mcp-approval.ts@@ -0,0 +1,29 @@+/** Long enough to read the text of a comment, which is often the thing being approved. */+const INPUT_DETAIL_LIMIT = 1000;++/**+ * The approval card for an MCP server's tool: the server and tool in the+ * title, as Codex words it, and the input as the detail, since the input is+ * what will run. No detail when the tool takes no input.+ */+export function mcpApprovalContent(+ server: string,+ tool: string,+ input: Record<string, unknown>+): { title: string; detail?: string } {+ const detail = toolInputDetail(input);+ return { title: `${server} wants to run ${tool}`, ...(detail ? { detail } : {}) };+}++/**+ * A tool's input as compact JSON; undefined when there is none. Past the limit+ * it is cut, and the cut says how much it left out, so nobody approves text+ * they believe they read in full.+ */+export function toolInputDetail(input: Record<string, unknown>): string | undefined {+ if (Object.keys(input).length === 0) return undefined;+ const json = JSON.stringify(input);+ if (json.length <= INPUT_DETAIL_LIMIT) return json;+ const omitted = json.length - INPUT_DETAIL_LIMIT;+ return `${json.slice(0, INPUT_DETAIL_LIMIT)}… (${omitted} more characters not shown)`;+}diff --git a/console/packages/agent-providers/src/opencode/config.ts b/console/packages/agent-providers/src/opencode/config.tsindex f9be1640f..b47270c49 100644--- a/console/packages/agent-providers/src/opencode/config.ts+++ b/console/packages/agent-providers/src/opencode/config.ts@@ -55,10 +55,12 @@ function editAction(mode: RuntimeMode): OpencodePermissionAction {/*** The permission keys covering the tools of the MCP servers the caller- * registered. OpenCode names an MCP permission `<server>_<tool>` and matches a- * permission key as a glob, so one entry per server covers its whole surface.+ * registered and auto-approves. OpenCode names an MCP permission+ * `<server>_<tool>` and matches a permission key as a glob, so one entry per+ * server covers its whole surface.*- * Only explicitly supplied servers receive these rules. Native user MCP+ * Only explicitly supplied servers receive these rules, and not a connector's,+ * whose tools fall under `'*' → ask` like any other tool. Native user MCP* registrations retain their own permissions. Switch's room protocol must be* available so the agent can ask the room for help.*/@@ -135,13 +137,15 @@ export function mcpConfigFor(return entries;}+/** `autoApproved` names the servers whose tools are allowed without asking. */export function buildConfigFile(mode: RuntimeMode,- servers: Record<string, McpServerSpec>+ servers: Record<string, McpServerSpec>,+ autoApproved: string[]): OpencodeConfigFile {return {$schema: 'https://opencode.ai/config.json',- permission: permissionConfigFor(mode, Object.keys(servers)),+ permission: permissionConfigFor(mode, autoApproved),mcp: mcpConfigFor(servers),};}diff --git a/console/packages/agent-providers/src/opencode/home.test.ts b/console/packages/agent-providers/src/opencode/home.test.tsindex d42deb786..22aa9d9bc 100644--- a/console/packages/agent-providers/src/opencode/home.test.ts+++ b/console/packages/agent-providers/src/opencode/home.test.ts@@ -19,9 +19,13 @@ it('preserves native JSONC configuration, skills, MCP, paths and credentials', aawait writeFile(join(source, 'opencode.jsonc'), original);await writeFile(join(root, 'auth-sentinel'), 'unchanged');prepared = await prepareOpencodeHome(- buildConfigFile('approval-required', {- switch: { transport: 'stdio', command: 'node', args: ['managed.mjs'] },- }),+ buildConfigFile(+ 'approval-required',+ {+ switch: { transport: 'stdio', command: 'node', args: ['managed.mjs'] },+ },+ ['switch']+ ),[{ name: 'managed', content: 'Managed skill' }],{ HOME: root });diff --git a/console/packages/agent-providers/src/opencode/opencode-adapter.test.ts b/console/packages/agent-providers/src/opencode/opencode-adapter.test.tsindex f2f57a18b..40ef3fbf3 100644--- a/console/packages/agent-providers/src/opencode/opencode-adapter.test.ts+++ b/console/packages/agent-providers/src/opencode/opencode-adapter.test.ts@@ -17,6 +17,7 @@ import {createOpencodeAdapter,fromPermissionReply,type OpencodeAdapter,+ mcpToolOf,permissionTitle,subagentName,toolItemType,@@ -34,6 +35,7 @@ function startInput(overrides: Partial<ProviderSessionStartInput> = {}): ProvideruntimeMode: 'full-access',env: { PATH: '/usr/bin', HOME: '/home/switch' },mcpServers: {},+ connectorMcpServers: [],model: { id: 'opencode/big-pickle' },...overrides,};@@ -774,3 +776,104 @@ it('sends the native model variant and clears it when returning to defaults', as).not.toHaveProperty('variant');await adapter.stopAll();});++describe('OpencodeAdapter connector tools', () => {+ const stdio = { transport: 'stdio' as const, command: 'node', args: ['server.mjs'] };+ const servers = { switch: stdio, atlassian: stdio, gws: stdio, other: stdio };+ const action = (rules: { permission: string; action: string }[], permission: string) =>+ rules.find((rule) => rule.permission === permission)?.action;++ it.each(['approval-required', 'auto-accept-edits'] as const)(+ "in %s a connector gets no allow rule and asks under '*', while Switch's own never asks",+ async (mode) => {+ const { session } = await setup(mode, {+ mcpServers: servers,+ connectorMcpServers: ['atlassian', 'gws'],+ });+ const { permission, config } = session.opened;+ expect(action(permission, '*')).toBe('ask');+ expect(action(permission, 'switch_*')).toBe('allow');+ expect(action(permission, 'other_*')).toBe('allow');+ expect(action(permission, 'atlassian_*')).toBeUndefined();+ expect(action(permission, 'gws_*')).toBeUndefined();+ expect(config.permission['switch_*']).toBe('allow');+ expect(config.permission['atlassian_*']).toBeUndefined();+ expect(config.permission['*']).toBe('ask');+ expect(Object.keys(config.mcp).sort()).toEqual(['atlassian', 'gws', 'other', 'switch']);+ }+ );++ it('allows everything in full access', async () => {+ const { session } = await setup('full-access', {+ mcpServers: servers,+ connectorMcpServers: ['atlassian', 'gws'],+ });+ expect(session.opened.permission.every((rule) => rule.action === 'allow')).toBe(true);+ });++ it("still types a connector's tools as MCP tool approvals", () => {+ expect(toRequestType('atlassian_search', ['switch', 'atlassian'])).toBe('mcp_tool_approval');+ });++ it('names the connector on the card it opens', async () => {+ const { adapter, session, recorder } = await setup('approval-required', {+ mcpServers: servers,+ connectorMcpServers: ['atlassian', 'gws'],+ });+ await adapter.sendTurn({ sessionId: 'switch-session', turnId: 't1', text: 'search' });+ session.push(sessionStatus(NATIVE, 'busy'));+ session.push(+ opencodeEvent('permission.asked', {+ id: 'per_1',+ sessionID: NATIVE,+ permission: 'atlassian_search',+ patterns: ['*'],+ metadata: {},+ always: ['*'],+ })+ );+ const opened = await recorder.waitFor('request.opened', () => true, 1_000);+ expect(opened).toMatchObject({ requestType: 'mcp_tool_approval', connector: 'atlassian' });+ });++ it('says which server wants to run which tool, with the input it will run', async () => {+ const { adapter, session, recorder } = await setup('approval-required', {+ mcpServers: servers,+ connectorMcpServers: ['atlassian', 'gws'],+ });+ await adapter.sendTurn({ sessionId: 'switch-session', turnId: 't1', text: 'comment' });+ session.push(sessionStatus(NATIVE, 'busy'));+ session.push(messageUpdated(NATIVE, 'msg1', 'assistant'));+ session.push(+ toolPart(NATIVE, 'msg1', 'c1', 'atlassian_addCommentToJiraIssue', {+ status: 'running',+ input: { issueIdOrKey: 'PROJ-1', commentBody: 'Shipped in 1.2.' },+ time: { start: 0 },+ })+ );+ session.push(+ opencodeEvent('permission.asked', {+ id: 'per_1',+ sessionID: NATIVE,+ permission: 'atlassian_addCommentToJiraIssue',+ patterns: ['*'],+ metadata: {},+ always: ['*'],+ tool: { messageID: 'msg1', callID: 'c1' },+ })+ );+ const opened = await recorder.waitFor('request.opened', () => true, 1_000);+ expect(opened).toMatchObject({+ title: 'atlassian wants to run addCommentToJiraIssue',+ detail: '{"issueIdOrKey":"PROJ-1","commentBody":"Shipped in 1.2."}',+ });+ });++ it('splits a tool name by the longest server it starts with', () => {+ expect(mcpToolOf('switch_echo_run', ['switch', 'switch_echo'])).toEqual({+ server: 'switch_echo',+ tool: 'run',+ });+ expect(mcpToolOf('bash', ['switch'])).toBeUndefined();+ });+});diff --git a/console/packages/agent-providers/src/opencode/opencode-adapter.ts b/console/packages/agent-providers/src/opencode/opencode-adapter.tsindex fed9816f5..654c3e3b9 100644--- a/console/packages/agent-providers/src/opencode/opencode-adapter.ts+++ b/console/packages/agent-providers/src/opencode/opencode-adapter.ts@@ -25,6 +25,7 @@ import type {UserInputAnswers,UserInputQuestion,} from '../events';+import { mcpApprovalContent } from '../mcp-approval';import { CumulativeUsage } from '../usage';import { buildConfigFile, parseModelId, permissionRulesFor } from './config';import type { OpencodeSkill } from './server';@@ -83,6 +84,8 @@ interface SessionRecord {systemContext?: string;variant?: string;mcpNames: string[];+ /** The registered servers whose tools ask, unless the mode allows everything. */+ connectorMcpServers: string[];transport: OpencodeSessionTransport;stopping: boolean;exited: boolean;@@ -166,12 +169,17 @@ export class OpencodeAdapter implements ProviderAdapter {createdAt: new Date().toISOString(),});+ // A connector's tools ask unless the mode allows everything; the rest of+ // the registered servers', Switch's own above all, never ask.+ const autoApproved = Object.keys(input.mcpServers).filter(+ (name) => !input.connectorMcpServers.includes(name)+ );const transport = await this.transport.open({sessionId: input.sessionId,cwd: input.cwd,env: input.env,- config: buildConfigFile(input.runtimeMode, input.mcpServers),- permission: permissionRulesFor(input.runtimeMode, Object.keys(input.mcpServers)),+ config: buildConfigFile(input.runtimeMode, input.mcpServers, autoApproved),+ permission: permissionRulesFor(input.runtimeMode, autoApproved),...(input.resume ? { resumeNativeSessionId: input.resume.nativeSessionId } : {}),...(model ? { model } : {}),});@@ -185,6 +193,7 @@ export class OpencodeAdapter implements ProviderAdapter {...(input.systemContext ? { systemContext: input.systemContext } : {}),...(input.model?.options?.variant ? { variant: input.model.options.variant } : {}),mcpNames: Object.keys(input.mcpServers),+ connectorMcpServers: [...input.connectorMcpServers],transport,stopping: false,exited: false,@@ -646,7 +655,7 @@ export class OpencodeAdapter implements ProviderAdapter {record: SessionRecord,event: Extract<OpencodeEvent, { type: 'permission.asked' }>): Promise<void> {- const { id, permission, patterns, metadata } = event.properties;+ const { id, permission, patterns, metadata, tool } = event.properties;if (record.activeTurnId === undefined) {await record.transport.replyPermission(id, 'reject');this.emit(record, {@@ -677,17 +686,23 @@ export class OpencodeAdapter implements ProviderAdapter {record.pendingApprovals.set(id, { turnId });const title = permissionTitle(permission, patterns);const command = metadata['command'];+ const mcpTool = mcpToolOf(permission, record.mcpNames);this.emit(record,{type: 'request.opened',requestId: id,requestType: toRequestType(permission, record.mcpNames),- title,- // Only when it says something the title does not: for a short `bash`- // the pattern *is* the command, and a card showing it twice reads as- // two different things to check.- ...(typeof command === 'string' && command !== title ? { detail: command } : {}),+ ...connectorOf(permission, record.connectorMcpServers),+ ...(mcpTool+ ? mcpApprovalContent(mcpTool.server, mcpTool.tool, this.toolInput(record, tool?.callID))+ : {+ title,+ // Only when it says something the title does not: for a short+ // `bash` the pattern *is* the command, and a card showing it+ // twice reads as two different things to check.+ ...(typeof command === 'string' && command !== title ? { detail: command } : {}),+ }),options: APPROVAL_OPTIONS,},turnId,@@ -695,6 +710,22 @@ export class OpencodeAdapter implements ProviderAdapter {);}+ /**+ * The input of the tool call a permission ask is for, from the tool part+ * OpenCode streamed before asking. Without it the card shows no input, so+ * that is logged rather than passed over.+ */+ private toolInput(record: SessionRecord, callId: string | undefined): Record<string, unknown> {+ const input = callId === undefined ? undefined : record.items.get(callId)?.payload?.['input'];+ if (typeof input === 'object' && input !== null && !Array.isArray(input))+ return input as Record<string, unknown>;+ this.logger.warn('opencode: no tool input for a permission ask; the card shows none', {+ sessionId: record.sessionId,+ callId,+ });+ return {};+ }+private async handleQuestionAsked(record: SessionRecord,event: Extract<OpencodeEvent, { type: 'question.asked' }>@@ -989,6 +1020,30 @@ export function permissionTitle(permission: string, patterns: string[]): stringreturn pattern === undefined || pattern === '' || pattern === '*' ? permission : pattern;}+/**+ * The server and tool in OpenCode's `<server>_<tool>` name, for a server this+ * session runs. The longest server name wins, so `switch_echo_run` is+ * `switch_echo`'s `run`, not `switch`'s `echo_run`.+ */+export function mcpToolOf(+ permission: string,+ mcpNames: string[]+): { server: string; tool: string } | undefined {+ const name = permission.toLowerCase();+ const server = mcpNames+ .filter((mcp) => name.startsWith(`${mcp.toLowerCase()}_`))+ .sort((a, b) => b.length - a.length)[0];+ if (server === undefined || permission.length <= server.length + 1) return undefined;+ return { server, tool: permission.slice(server.length + 1) };+}++/** `{ connector }` when `permission` is one of the connectors' tools. */+function connectorOf(permission: string, connectors: string[]): { connector?: string } {+ const name = permission.toLowerCase();+ const connector = connectors.find((mcp) => name.startsWith(`${mcp.toLowerCase()}_`));+ return connector === undefined ? {} : { connector };+}+export function toRequestType(permission: string, mcpNames: string[]): RequestType {const name = permission.toLowerCase();if (mcpNames.some((mcp) => name.startsWith(`${mcp.toLowerCase()}_`))) return 'mcp_tool_approval';diff --git a/console/packages/agent-providers/src/testing/conformance.ts b/console/packages/agent-providers/src/testing/conformance.tsindex 0d741e508..8ff2d718e 100644--- a/console/packages/agent-providers/src/testing/conformance.ts+++ b/console/packages/agent-providers/src/testing/conformance.ts@@ -110,6 +110,7 @@ export function describeConformance(name: string, options: ConformanceOptions):runtimeMode: 'full-access',env: baseEnv(options.env),mcpServers: {},+ connectorMcpServers: [],model: options.model,...overrides,};@@ -366,6 +367,7 @@ export function describeConformance(name: string, options: ConformanceOptions):const { adapter, recorder, sessionId, input } = await setup({runtimeMode: 'approval-required',mcpServers: options.mcpServers,+ connectorMcpServers: [],});await adapter.startSession(input);const names = Object.keys(options.mcpServers).join(', ');diff --git a/core/switch_core/addressing.py b/core/switch_core/addressing.pyindex fc3a2e1ac..f8cd0eefa 100644--- a/core/switch_core/addressing.py+++ b/core/switch_core/addressing.py@@ -197,24 +197,32 @@ class AddressingPolicy(BaseModel):for rule in self.rules)- def admits_others(- self, *, owner_identity_ids: set[str], owner_agent_ids: set[str]- ) -> bool:- """Whether anyone but the owner and the owner's own agents may address- the agent, and so have it act on what its owner granted it.-- An open policy does; so does any rule that admits every human or- agent (``"*"``, whatever its rooms), a human by an identity the owner- has not claimed, or another person's agent. `owner_identity_ids` are- the platform identities the owner has claimed; `owner_agent_ids` the- agents they own. A platform rule is not counted: the platform acting- for a person is judged as that person (`allows_on_behalf_of`).+ def admits_others(self, *, owner_identity_ids: set[str]) -> bool:+ """Whether anyone but the owner may address the agent, and so have it+ act on what its owner granted it.++ An open policy does; so does any rule that admits every human+ (``"*"``, whatever its rooms), a human by an identity the owner has+ not claimed, or any agent at all: ``owner_agents``, a named agent, or+ ``"*"``. The owner's own agents count as others because an agent+ sender is not the person. Whoever addressed that agent can have it+ pass the request on, and the grant is then used on their behalf, not+ the owner's: a confused-deputy path. `owner_identity_ids` are the+ platform identities the owner has claimed. A platform rule is not+ counted: the platform acting for a person is judged as that person+ (`allows_on_behalf_of`).++ This only reports the exposure; it does not refuse anything. An+ ``owner_agents`` rule still lets the owner's agents address the agent+ (`allows`), and closing that path needs the originating person carried+ on agent-to-agent messages."""if self.is_open():return Truereturn any(_admits_beyond(rule.users, owner_identity_ids)- or _admits_beyond(rule.agents, owner_agent_ids)+ or rule.owner_agents+ or rule.agents != []for rule in self.rules)diff --git a/core/switch_core/connections/adapters/__init__.py b/core/switch_core/connections/adapters/__init__.pyindex 7ed4a1988..2d92e86e4 100644--- a/core/switch_core/connections/adapters/__init__.py+++ b/core/switch_core/connections/adapters/__init__.py@@ -92,6 +92,12 @@ class ServiceAdapter(Protocol):# nothing can be granted.can_issue: bool+ def current_client_id(self) -> str | None:+ """The vendor client this adapter signs in through, where it knows it+ without asking anyone; None for a service with no client, or one not+ yet known. A connection signed in through another must reconnect."""+ ...+async def refresh(self, secret: ConnectionSecret) -> ConnectionSecret:"""The secret with a fresh access token, and a new refresh token wherethe vendor rotates them."""diff --git a/core/switch_core/connections/adapters/api_key.py b/core/switch_core/connections/adapters/api_key.pyindex 147b051a3..39b9696f2 100644--- a/core/switch_core/connections/adapters/api_key.py+++ b/core/switch_core/connections/adapters/api_key.py@@ -92,6 +92,9 @@ class ApiKeyAdapter:self._sign_in = sign_inself._http = http+ def current_client_id(self) -> str | None:+ return None+def checked_fields(self, submitted: dict[str, str]) -> dict[str, str]:"""The submitted fields, each as the entry allows, and nothing else."""expected = {field.name: field for field in self._sign_in.fields}diff --git a/core/switch_core/connections/adapters/github.py b/core/switch_core/connections/adapters/github.pyindex c7b237867..b298c3133 100644--- a/core/switch_core/connections/adapters/github.py+++ b/core/switch_core/connections/adapters/github.py@@ -59,10 +59,10 @@ def load_github_app(config: SwitchConfig) -> GitHubApp | None:if config.github_app_config_path is not None:if config.github_app_private_key_path is None:raise ValueError("GITHUB_APP_PRIVATE_KEY_PATH is not set.")- connections = GitHubConnections(config.github_app_config_path)+ connections = GitHubConnections.from_file(config.github_app_config_path)return GitHubApp(connections,- GitHubInstallationCredentials(+ GitHubInstallationCredentials.from_file(connections.client_id, config.github_app_private_key_path),)@@ -74,7 +74,9 @@ def load_github_app(config: SwitchConfig) -> GitHubApp | None:"GitHub can be connected but not granted to agents. Set ""GITHUB_APP_CONFIG_PATH and GITHUB_APP_PRIVATE_KEY_PATH instead.")- return GitHubApp(GitHubConnections(config.hosted_github_config_path), None)+ return GitHubApp(+ GitHubConnections.from_file(config.hosted_github_config_path), None+ )def _reach(resources: dict[str, Any]) -> tuple[int, list[int]]:@@ -113,6 +115,9 @@ class GitHubAdapter:self._signer = signerself.can_issue = signer is not None+ def current_client_id(self) -> str | None:+ return self._connections.client_id+async def refresh(self, secret: ConnectionSecret) -> ConnectionSecret:refresh_token = secret.values.get("refresh_token")refresh_expires_at = secret.values.get("refresh_expires_at")diff --git a/core/switch_core/connections/adapters/oauth.py b/core/switch_core/connections/adapters/oauth.pyindex aac7e9af2..00a2ca8c1 100644--- a/core/switch_core/connections/adapters/oauth.py+++ b/core/switch_core/connections/adapters/oauth.py@@ -66,6 +66,10 @@ class AuthorizationEndpoints:class ClientSource(Protocol):"""Where the adapter has its OAuth client from."""+ def known_client_id(self) -> str | None:+ """The client's id where it is already known, without asking anyone."""+ ...+async def credentials(self, endpoints: AuthorizationEndpoints) -> OAuthClientCredentials: ...@@ -77,6 +81,9 @@ class StaticClient:client: OAuthClientCredentials+ def known_client_id(self) -> str | None:+ return self.client.client_id+async def credentials(self, endpoints: AuthorizationEndpoints) -> OAuthClientCredentials:@@ -93,10 +100,17 @@ class Identity:@dataclass(frozen=True)class SignIn:- """What an authorization code was exchanged for."""+ """What an authorization code was exchanged for, and through which client."""secret: ConnectionSecretgranted_scopes: list[str]+ client_id: str+++@dataclass(frozen=True)+class TokenAnswer:+ body: dict[str, Any]+ client_id: strdef s256(verifier: str) -> str:@@ -309,7 +323,14 @@ class OAuthAdapter:)return None if match is None else _https(match.group(1), "resource metadata")- async def _token_request(self, form: dict[str, str]) -> dict[str, Any]:+ def current_client_id(self) -> str | None:+ return self._client.known_client_id()++ async def client_id(self) -> str:+ """The client a sign-in starting now goes through."""+ return (await self._client.credentials(await self.endpoints())).client_id++ async def _token_request(self, form: dict[str, str]) -> TokenAnswer:endpoints = await self.endpoints()client = await self._client.credentials(endpoints)data = {**form, "client_id": client.client_id}@@ -326,7 +347,7 @@ class OAuthAdapter:))if response.status_code == 200:- return self._json(response, "token response")+ return TokenAnswer(self._json(response, "token response"), client.client_id)try:error = response.json().get("error")except (ValueError, AttributeError):@@ -410,7 +431,7 @@ class OAuthAdapter:self, *, code: str, verifier: str, redirect_uri: str, scopes: list[str]) -> SignIn:"""The sign-in an authorization code stands for; Core keeps it."""- body = await self._token_request(+ answer = await self._token_request({"grant_type": "authorization_code","code": code,@@ -418,11 +439,12 @@ class OAuthAdapter:"redirect_uri": redirect_uri,})- values = self._credentials(body, {})+ values = self._credentials(answer.body, {})granted = values.get("scope")return SignIn(ConnectionSecret(values),granted.split() if isinstance(granted, str) else list(scopes),+ answer.client_id,)async def identify(self, access_token: str) -> Identity:@@ -465,10 +487,10 @@ class OAuthAdapter:raise ReauthorizationRequiredError(f"The {self._name} connection holds no refresh token.")- body = await self._token_request(+ answer = await self._token_request({"grant_type": "refresh_token", "refresh_token": refresh_token})- return ConnectionSecret(self._credentials(body, secret.values))+ return ConnectionSecret(self._credentials(answer.body, secret.values))async def check_grant(self, access_token: str, request: IssueRequestdiff --git a/core/switch_core/connections/app_checks.py b/core/switch_core/connections/app_checks.pynew file mode 100644index 000000000..a8c575c0d--- /dev/null+++ b/core/switch_core/connections/app_checks.py@@ -0,0 +1,288 @@+"""Asking a connector's vendor whether an app's values belong together.++Nothing is signed in and nothing is stored: each check sends the vendor a+request it must refuse, and reads which refusal it chose.++- **GitHub App**: `GET /app` with a JWT the private key signs, issued by the+ client id, proves the key and the client id are one App's, and answers its+ slug; a code exchange with a made-up code then tells a wrong client secret+ (`incorrect_client_credentials`) from a right one (`bad_verification_code`).+- **OAuth client**: a code exchange at the token endpoint with a made-up+ code, sent to Switch's own redirect URI. `invalid_grant` means the client+ id and secret are right; `invalid_client` that they are not; and+ `redirect_uri_mismatch` that the redirect URI is not registered.++What a check cannot prove (an App's permissions, a Google app's user type,+which APIs are switched on) is left to the vendor's own pages.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++import httpx++from switch_core.connections.adapters import ServiceAdapterError+from switch_core.connections.adapters.oauth import (+ OAuthAdapter,+ OAuthClientCredentials,+ StaticClient,+)+from switch_core.connections.app_credentials import AppSpec, AppValues+from switch_core.connections.loader import ConnectionDefinition+from switch_core.providers.github_installation import GitHubInstallationCredentials++GITHUB_APP_URL = "https://api.github.com/app"+GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token"+# Never a real code: the vendor is asked to refuse it.+PLACEHOLDER_CODE = "switch-connector-app-check"++Field = Literal["client_id", "client_secret", "private_key"]+++class VendorUnreachableError(Exception):+ """The vendor could not be asked; the message is for the operator."""+++@dataclass(frozen=True)+class Check:+ name: str+ ok: bool+ message: str+ # The value the operator should look at again when the check fails.+ field: Field | None+++@dataclass(frozen=True)+class CheckResult:+ checks: list[Check]+ # What the vendor said about the app that Switch keeps: a GitHub App's slug.+ settings: dict[str, str]++ @property+ def ok(self) -> bool:+ return all(check.ok for check in self.checks)++ def first_failure(self) -> Check | None:+ return next((check for check in self.checks if not check.ok), None)+++async def _send(+ http: httpx.AsyncClient, vendor: str, request: httpx.Request+) -> httpx.Response:+ try:+ response = await http.send(request, follow_redirects=False)+ except httpx.HTTPError:+ raise VendorUnreachableError(f"Couldn't reach {vendor}. Try again.") from None+ if response.status_code == 429 or response.status_code >= 500:+ raise VendorUnreachableError(+ f"{vendor} is unavailable (HTTP {response.status_code}). Try again."+ )+ return response+++def _body(response: httpx.Response) -> dict[str, Any]:+ try:+ body = response.json()+ except ValueError:+ return {}+ return body if isinstance(body, dict) else {}+++async def check_github_app(http: httpx.AsyncClient, values: AppValues) -> CheckResult:+ try:+ signer = GitHubInstallationCredentials(+ values.client_id, values.secrets["private_key"].encode()+ )+ except ValueError as unusable:+ return CheckResult(+ [Check("private_key", False, str(unusable), "private_key")], settings={}+ )+ assertion = signer.assertion()+ app = await _send(+ http,+ "GitHub",+ http.build_request(+ "GET",+ GITHUB_APP_URL,+ headers={+ "Authorization": f"Bearer {assertion}",+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ },+ ),+ )+ answer = _body(app)+ slug = answer.get("slug")+ if app.status_code != 200 or not isinstance(slug, str) or not slug:+ return CheckResult(+ [+ Check(+ "private_key",+ False,+ "GitHub doesn't accept this private key for this client ID. "+ "Copy the Client ID again, or generate a private key in the "+ "App's settings.",+ "private_key",+ )+ ],+ settings={},+ )+ if answer.get("client_id") != values.client_id:+ return CheckResult(+ [+ Check(+ "private_key",+ False,+ "This private key belongs to a GitHub App with another client "+ "ID. Copy the Client ID from that App's settings.",+ "client_id",+ )+ ],+ settings={},+ )+ checks = [+ Check(+ "private_key",+ True,+ f"GitHub accepts this private key for the App {slug}.",+ None,+ )+ ]+ exchanged = await _send(+ http,+ "GitHub",+ http.build_request(+ "POST",+ GITHUB_TOKEN_URL,+ data={+ "client_id": values.client_id,+ "client_secret": values.secrets["client_secret"],+ "code": PLACEHOLDER_CODE,+ },+ headers={"Accept": "application/json"},+ ),+ )+ error = _body(exchanged).get("error")+ if error == "bad_verification_code":+ checks.append(+ Check("client_secret", True, "GitHub accepts this client secret.", None)+ )+ elif error == "incorrect_client_credentials":+ checks.append(+ Check(+ "client_secret",+ False,+ "GitHub doesn't accept this client secret for this client ID. "+ "Generate a new one in the App's settings.",+ "client_secret",+ )+ )+ else:+ checks.append(+ Check(+ "client_secret",+ False,+ "GitHub gave an answer Switch doesn't recognise when checking the "+ f"client secret ({error or f'HTTP {exchanged.status_code}'}).",+ "client_secret",+ )+ )+ return CheckResult(checks, settings={"slug": slug})+++async def check_oauth_client(+ http: httpx.AsyncClient,+ definition: ConnectionDefinition,+ values: AppValues,+ redirect_uri: str,+) -> CheckResult:+ name = definition.name+ client = OAuthClientCredentials(values.client_id, values.secrets["client_secret"])+ try:+ endpoints = await OAuthAdapter(+ definition, StaticClient(client), http+ ).endpoints()+ except ServiceAdapterError as refused:+ raise VendorUnreachableError(str(refused)) from None+ response = await _send(+ http,+ name,+ http.build_request(+ "POST",+ endpoints.token,+ data={+ "grant_type": "authorization_code",+ "code": PLACEHOLDER_CODE,+ "redirect_uri": redirect_uri,+ "client_id": client.client_id,+ "client_secret": values.secrets["client_secret"],+ },+ headers={"Accept": "application/json"},+ ),+ )+ error = _body(response).get("error")+ if error == "invalid_grant":+ return CheckResult(+ [+ Check(+ "client",+ True,+ f"{name} accepts this client ID and secret.",+ None,+ )+ ],+ settings={},+ )+ if error == "redirect_uri_mismatch":+ return CheckResult(+ [+ Check(+ "client",+ False,+ f"{name} doesn't have Switch's redirect URI for this client. "+ f"Add {redirect_uri} to its authorized redirect URIs.",+ None,+ )+ ],+ settings={},+ )+ if error in ("invalid_client", "unauthorized_client"):+ return CheckResult(+ [+ Check(+ "client",+ False,+ f"{name} doesn't recognise this client ID and secret together. "+ "Copy both again from where you created the client.",+ "client_secret",+ )+ ],+ settings={},+ )+ return CheckResult(+ [+ Check(+ "client",+ False,+ f"{name} gave an answer Switch doesn't recognise "+ f"({error or f'HTTP {response.status_code}'}).",+ None,+ )+ ],+ settings={},+ )+++async def check_app(+ http: httpx.AsyncClient,+ spec: AppSpec,+ definition: ConnectionDefinition,+ values: AppValues,+ redirect_uri: str,+) -> CheckResult:+ """Ask the vendor about `values`. Raises `VendorUnreachableError`."""+ if spec.kind == "github_app":+ return await check_github_app(http, values)+ return await check_oauth_client(http, definition, values, redirect_uri)diff --git a/core/switch_core/connections/app_credentials.py b/core/switch_core/connections/app_credentials.pynew file mode 100644index 000000000..fa775b936--- /dev/null+++ b/core/switch_core/connections/app_credentials.py@@ -0,0 +1,479 @@+"""The apps connectors sign in through, and where each one comes from.++Some catalog entries need an app the server's operator registers at the+vendor before anyone can connect: GitHub's App (the `github` adapter), and+every OAuth client with `registration: static`. Each comes from one of two+places:++- **configuration**: the files named by `GITHUB_APP_CONFIG_PATH` and+ `GITHUB_APP_PRIVATE_KEY_PATH` (or, for one more release, the deprecated+ `HOSTED_GITHUB_CONFIG_PATH`), or by `<PREFIX>_CLIENT_CONFIG_PATH`;+- **saved**: a `service_app_credentials` row the operator saved from the+ dashboard.++Configuration wins: where it is set, Switch uses it exactly as it always+has, and a saved row is ignored with a warning at startup. A configuration+that is set but unusable stops the server; a saved row that cannot be used+leaves the service not set up, with the reason on the operator's page, so a+bad row cannot lock the operator out of the page that fixes it.++A GitHub App saved here is called back at `GATEWAY_PUBLIC_URL`, which must+then be https; a configured one keeps the `origin` its file names.++A change takes effect without a restart (`ConnectorApps.apply`): the+service's adapter is rebuilt and swapped into the broker, and for GitHub the+App on the gateway's state is swapped too; a sign-in under way is a row, so+it outlives the swap. The process that saved the change applies it at once+and announces it, and every other process applies it on hearing so+(`connections/app_signals.py`). Each process remembers which saved row it+resolved every app from, so one that missed the announcement finds the row+changed on its next re-check.+"""++from __future__ import annotations++import logging+from collections.abc import Mapping+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, Literal+from urllib.parse import urlsplit++import httpx+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from starlette.datastructures import State++from switch_core.config import SwitchConfig+from switch_core.connections.adapters.github import GitHubApp, load_github_app+from switch_core.connections.adapters.oauth import OAuthClientCredentials+from switch_core.connections.loader import Connection, ConnectionDefinition+from switch_core.connections.registry import (+ ClientRegistration,+ build_adapter,+ client_settings_variable,+ load_client_settings,+)+from switch_core.db.models import ServiceAppCredential+from switch_core.db.stores.service_app_credential_store import (+ ServiceAppCredentialStore,+)+from switch_core.keys import UndecryptableError+from switch_core.providers.github import GitHubConnections+from switch_core.providers.github_installation import GitHubInstallationCredentials++if TYPE_CHECKING:+ from datetime import datetime++ from switch_core.connections.app_signals import ConnectorAppSignals+ from switch_core.connections.broker import ServiceBroker++logger = logging.getLogger(__name__)++AppKind = Literal["github_app", "oauth_client"]+Source = Literal["configuration", "saved", "none"]++GITHUB_APP_VARIABLES = ("GITHUB_APP_CONFIG_PATH", "GITHUB_APP_PRIVATE_KEY_PATH")+HOSTED_GITHUB_VARIABLE = "HOSTED_GITHUB_CONFIG_PATH"++SECRET_NAMES: dict[AppKind, frozenset[str]] = {+ "github_app": frozenset({"client_secret", "private_key"}),+ "oauth_client": frozenset({"client_secret"}),+}++UNREADABLE = "Switch can't read the saved secret any more."++GITHUB_NEEDS_HTTPS = (+ "GitHub needs GATEWAY_PUBLIC_URL to be an https address, to send people "+ "back to Switch."+)+++def app_kind(definition: ConnectionDefinition) -> AppKind | None:+ """The kind of app the operator sets up for `definition`, if any."""+ if definition.adapter == "github":+ return "github_app"+ oauth = definition.auth.oauth+ if (+ definition.adapter == "oauth"+ and oauth is not None+ and oauth.registration == "static"+ ):+ return "oauth_client"+ return None+++def needs_operator_app(definition: ConnectionDefinition) -> bool:+ return app_kind(definition) is not None+++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. Ask whoever runs your Switch "+ "server to add it under Connectors in the Switch dashboard."+ )+++@dataclass(frozen=True)+class AppSpec:+ """A catalog entry that needs an app, and what configures it."""++ service: str+ name: str+ kind: AppKind+ variables: tuple[str, ...]++ @property+ def secret_names(self) -> frozenset[str]:+ return SECRET_NAMES[self.kind]+++def app_specs(catalog: Mapping[str, Connection]) -> dict[str, AppSpec]:+ specs = {}+ for slug, entry in catalog.items():+ definition = entry.definition+ kind = app_kind(definition)+ if not definition.enabled or kind is None:+ continue+ variables: tuple[str, ...]+ if kind == "github_app":+ variables = GITHUB_APP_VARIABLES+ else:+ assert definition.auth.oauth is not None+ assert definition.auth.oauth.client_settings is not None+ variables = (+ client_settings_variable(definition.auth.oauth.client_settings),+ )+ specs[slug] = AppSpec(slug, definition.name, kind, variables)+ if sum(spec.kind == "github_app" for spec in specs.values()) > 1:+ raise ValueError("The catalog names more than one GitHub App service.")+ return specs+++@dataclass(frozen=True)+class AppValues:+ """An app's values: its client id, non-secret settings and secrets."""++ client_id: str+ settings: dict[str, str]+ secrets: dict[str, str] = field(repr=False)+++@dataclass(frozen=True)+class EffectiveCredentials:+ """The app a service uses in this process, and where it came from.++ `configuration_variables` are the variables it was read from, when its+ source is configuration. `deprecated` marks GitHub's+ `HOSTED_GITHUB_CONFIG_PATH`, which names no signing key. `saved_ignored`:+ a row is saved but configuration is set, so the row is not used.+ `load_error` says why a saved row could not be used, and `unreadable`+ that no key opens it.+ """++ spec: AppSpec+ source: Source+ values: AppValues | None+ github_app: GitHubApp | None+ oauth_client: OAuthClientCredentials | None+ configuration_variables: tuple[str, ...]+ deprecated: bool+ saved_ignored: bool+ load_error: str | None+ unreadable: bool+++@dataclass(frozen=True)+class _Configured:+ values: AppValues+ github_app: GitHubApp | None+ oauth_client: OAuthClientCredentials | None+ variables: tuple[str, ...]+ deprecated: bool+++class AppLoadError(Exception):+ """A saved app that cannot be used; the message is for the operator."""+++def github_app_from_values(values: AppValues, public_url: str | None) -> GitHubApp:+ """A GitHub App from saved values, called back at `public_url`."""+ if public_url is None or urlsplit(public_url).scheme != "https":+ raise AppLoadError(GITHUB_NEEDS_HTTPS)+ try:+ connections = GitHubConnections(+ client_id=values.client_id,+ client_secret=values.secrets["client_secret"],+ slug=values.settings["slug"],+ origin=public_url,+ )+ signer = GitHubInstallationCredentials(+ values.client_id, values.secrets["private_key"].encode()+ )+ except KeyError as missing:+ raise AppLoadError(f"The saved GitHub App has no {missing.args[0]}.") from None+ except ValueError as error:+ raise AppLoadError(str(error)) from None+ return GitHubApp(connections, signer)+++def install_github_app(state: State, app: GitHubApp | None) -> None:+ """Put `app` on the gateway's state. A sign-in under way is a row in+ `sign_in_flows`, so it outlives the swap on its own; one that started+ under another client is refused as it completes."""+ state.github_app = app+ state.github_connections = None if app is None else app.connections+++def _changed_at(row: ServiceAppCredential | None) -> datetime | None:+ return None if row is None else row.updated_at+++class ConnectorApps:+ """Every connector's app, as this process uses it."""++ def __init__(+ self,+ *,+ catalog: dict[str, Connection],+ config: SwitchConfig,+ environ: Mapping[str, str],+ session_factory: async_sessionmaker[AsyncSession],+ store: ServiceAppCredentialStore,+ http: httpx.AsyncClient,+ registration: ClientRegistration,+ ) -> None:+ self.specs = app_specs(catalog)+ self._catalog = catalog+ self._config = config+ self._environ = environ+ self._session_factory = session_factory+ self._store = store+ self._http = http+ self._registration = registration+ self._configured: dict[str, _Configured | None] = {}+ self._effective: dict[str, EffectiveCredentials] = {}+ # When each service's saved row was last changed, as this process+ # resolved it; None where there was no row.+ self._resolved_at: dict[str, datetime | None] = {}+ self._signals: ConnectorAppSignals | None = None++ @property+ def store(self) -> ServiceAppCredentialStore:+ return self._store++ @property+ def public_url(self) -> str | None:+ return self._config.gateway_public_url++ @property+ def http(self) -> httpx.AsyncClient:+ """How this server reaches vendors, held to its outbound policy."""+ return self._http++ def definition(self, service: str) -> ConnectionDefinition:+ return self._catalog[service].definition++ async def load(self) -> None:+ """Resolve every app, at startup. Configuration that is set but+ cannot be used raises, as it always has."""+ self._configured = {+ service: self._configuration(spec) for service, spec in self.specs.items()+ }+ async with self._session_factory() as session:+ rows = await self._store.list_all(session)+ for service, spec in self.specs.items():+ effective = self._resolve(spec, rows.get(service))+ if effective.saved_ignored:+ logger.warning(+ "%s has an app saved from the dashboard, but %s is set, so "+ "Switch uses that and ignores the saved app.",+ spec.name,+ " and ".join(effective.configuration_variables),+ )+ self._effective[service] = effective+ self._resolved_at[service] = _changed_at(rows.get(service))++ async def reload(self, service: str) -> EffectiveCredentials:+ """Resolve one service's app again, after its row changed."""+ spec = self.specs[service]+ async with self._session_factory() as session:+ row = await self._store.get(session, service)+ effective = self._resolve(spec, row)+ self._effective[service] = effective+ self._resolved_at[service] = _changed_at(row)+ return effective++ def use_signals(self, signals: ConnectorAppSignals) -> None:+ """Announce each change made here, so every other process applies+ it too (`app_signals.py`)."""+ self._signals = signals++ def announce(self, service: str) -> None:+ """Tell every other process that `service`'s saved app changed, once+ the change has committed and been applied here."""+ if self._signals is not None:+ self._signals.changed(service)++ async def changed_since_resolved(self) -> list[str]:+ """The services whose saved row changed, appeared or went since this+ process last resolved them: what a missed announcement leaves behind.+ A read, never a write."""+ async with self._session_factory() as session:+ rows = await self._store.list_all(session)+ return [+ service+ for service in self.specs+ if _changed_at(rows.get(service)) != self._resolved_at.get(service)+ ]++ async def apply(+ self, service: str, *, broker: ServiceBroker, state: State+ ) -> EffectiveCredentials:+ """Resolve `service`'s app again and put it to work at once."""+ effective = await self.reload(service)+ broker.replace_adapter(+ service,+ build_adapter(+ service,+ self._catalog[service].definition,+ github_app=effective.github_app,+ oauth_client=effective.oauth_client,+ http=self._http,+ registration=self._registration,+ ),+ )+ if effective.spec.kind == "github_app":+ install_github_app(state, effective.github_app)+ return effective++ def effective(self, service: str) -> EffectiveCredentials:+ effective = self._effective.get(service)+ if effective is None:+ raise KeyError(f"{service} has no connector app, or apps are not loaded.")+ return effective++ def github_app(self) -> GitHubApp | None:+ for service, spec in self.specs.items():+ if spec.kind == "github_app":+ return self.effective(service).github_app+ return None++ def oauth_clients(self) -> dict[str, OAuthClientCredentials]:+ return {+ service: client+ for service in self.specs+ if (client := self.effective(service).oauth_client) is not None+ }++ def _configuration(self, spec: AppSpec) -> _Configured | None:+ if spec.kind == "oauth_client":+ oauth = self._catalog[spec.service].definition.auth.oauth+ assert oauth is not None and oauth.client_settings is not None+ settings = load_client_settings(oauth.client_settings, self._environ)+ if settings is None:+ return None+ client = OAuthClientCredentials(settings.client_id, settings.client_secret)+ return _Configured(+ values=AppValues(+ settings.client_id, {}, {"client_secret": settings.client_secret}+ ),+ github_app=None,+ oauth_client=client,+ variables=spec.variables,+ deprecated=False,+ )+ app = load_github_app(self._config)+ if app is None:+ return None+ secrets = {"client_secret": app.connections.client_secret}+ key_path = self._config.github_app_private_key_path+ deprecated = app.signer is None+ if key_path is not None:+ secrets["private_key"] = Path(key_path).read_text("utf-8")+ return _Configured(+ values=AppValues(+ app.connections.client_id, {"slug": app.connections.slug}, secrets+ ),+ github_app=app,+ oauth_client=None,+ variables=(HOSTED_GITHUB_VARIABLE,) if deprecated else spec.variables,+ deprecated=deprecated,+ )++ def _resolve(+ self, spec: AppSpec, row: ServiceAppCredential | None+ ) -> EffectiveCredentials:+ configured = self._configured.get(spec.service)+ if configured is not None:+ return EffectiveCredentials(+ spec=spec,+ source="configuration",+ values=configured.values,+ github_app=configured.github_app,+ oauth_client=configured.oauth_client,+ configuration_variables=configured.variables,+ deprecated=configured.deprecated,+ saved_ignored=row is not None,+ load_error=None,+ unreadable=False,+ )+ if row is None:+ return self._none(spec, load_error=None, unreadable=False)+ try:+ secrets = self._store.secrets(row)+ except UndecryptableError:+ logger.error(+ "The app saved for %s cannot be decrypted with any current key; "+ "%s is not set up until it is saved again.",+ spec.name,+ spec.name,+ )+ return self._none(spec, load_error=UNREADABLE, unreadable=True)+ values = AppValues(row.client_id, dict(row.settings), secrets)+ try:+ if spec.kind == "github_app":+ github_app = github_app_from_values(values, self.public_url)+ oauth_client = None+ else:+ if "client_secret" not in secrets:+ raise AppLoadError("The saved client has no client secret.")+ github_app = None+ oauth_client = OAuthClientCredentials(+ row.client_id, secrets["client_secret"]+ )+ except AppLoadError as error:+ logger.error(+ "The app saved for %s cannot be used, so it is not set up: %s",+ spec.name,+ error,+ )+ return self._none(spec, load_error=str(error), unreadable=False)+ return EffectiveCredentials(+ spec=spec,+ source="saved",+ values=values,+ github_app=github_app,+ oauth_client=oauth_client,+ configuration_variables=(),+ deprecated=False,+ saved_ignored=False,+ load_error=None,+ unreadable=False,+ )++ def _none(+ self, spec: AppSpec, *, load_error: str | None, unreadable: bool+ ) -> EffectiveCredentials:+ return EffectiveCredentials(+ spec=spec,+ source="none",+ values=None,+ github_app=None,+ oauth_client=None,+ configuration_variables=(),+ deprecated=False,+ saved_ignored=False,+ load_error=load_error,+ unreadable=unreadable,+ )diff --git a/core/switch_core/connections/app_signals.py b/core/switch_core/connections/app_signals.pynew file mode 100644index 000000000..d527fcc53--- /dev/null+++ b/core/switch_core/connections/app_signals.py@@ -0,0 +1,69 @@+"""A connector app saved or removed in one process, put to work in every one.++Every switch-core process resolves each connector's app at boot and holds+what it resolved: the broker's adapter, and for GitHub the App on the+gateway's state (`app_credentials.py`). The operator's save or removal is+handled by one process, which applies it at once; every other process kept+the app it had until a restart, so a sign-in or a token served elsewhere+went through the old app.++So the process that made the change announces `connector_app.changed` for+the service once it has committed, and every other process applies it on+hearing so (`ConnectorApps.apply`), which reads the row again rather than+trusting the signal. A process skips its own signals: it applied the change+before announcing it. An apply that fails is kept and tried again, and every+process re-checks on reconnecting and every `RECHECK_SECONDS` which rows+changed since it resolved them, so a missed signal costs a delay rather than+a process using an old app until it restarts.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from starlette.datastructures import State++ from switch_core.connections.app_credentials import ConnectorApps+ from switch_core.connections.broker import ServiceBroker+ from switch_core.signals import SignalBus++CONNECTOR_APP_CHANGED_SIGNAL = "connector_app.changed"+++class ConnectorAppSignals:+ def __init__(+ self,+ *,+ apps: ConnectorApps,+ broker: ServiceBroker,+ state: State,+ bus: SignalBus,+ ) -> None:+ self._apps = apps+ self._broker = broker+ self._state = state+ self._bus = bus+ self._owed = bus.pending_work("connector apps", self._apply)+ bus.handle(CONNECTOR_APP_CHANGED_SIGNAL, self._on_changed)+ bus.on_resync(self.recheck)+ bus.on_recheck(self.recheck)+ apps.use_signals(self)++ def changed(self, service: str) -> None:+ self._bus.publish(CONNECTOR_APP_CHANGED_SIGNAL, service=service)++ async def recheck(self) -> None:+ """Apply again every app whose saved row changed since this process+ resolved it."""+ for service in await self._apps.changed_since_resolved():+ self._owed.add(service)++ def _on_changed(self, signal: dict[str, Any]) -> None:+ service = signal["service"]+ # A service this build has no app for, from a newer process mid-roll.+ if service in self._apps.specs:+ self._owed.add(service)++ async def _apply(self, service: str) -> None:+ await self._apps.apply(service, broker=self._broker, state=self._state)diff --git a/core/switch_core/connections/broker.py b/core/switch_core/connections/broker.pyindex 504eb6a61..045f8cd60 100644--- a/core/switch_core/connections/broker.py+++ b/core/switch_core/connections/broker.py@@ -51,6 +51,7 @@ from switch_core.connections.adapters import ()from switch_core.connections.adapters.api_key import ApiKeyAdapterfrom switch_core.connections.adapters.oauth import OAuthAdapter+from switch_core.connections.app_credentials import needs_operator_app, not_set_upfrom switch_core.connections.loader import (TOKEN_PLACEHOLDER,AccessLevel,@@ -75,6 +76,7 @@ from switch_core.db.stores.service_connection_store import (ServiceConnectionBusy,ServiceConnectionStore,)+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.keys import Keyringfrom switch_core.observability.catalogue import SERVICE_TOKEN_REQUESTSfrom switch_core.observability.metrics import metrics@@ -124,6 +126,9 @@ REVOCATION_CLAIM = timedelta(seconds=90)VENDOR_CALL_SECONDS = 8ACCESS_WARNING = "Some access already given out may remain for up to 1 hour."SWITCHED_OFF = "Switched off on this server."+# Why a connection needs reconnecting: the operator replaced the app it+# signed in through.+CLIENT_REPLACED = "client_replaced"class ServiceError(Exception):@@ -323,6 +328,8 @@ class ServiceBroker:disabled: dict[str, str],store: ServiceConnectionStore,token_retention: timedelta,+ workspace_services: WorkspaceServiceStore,+ workspace_gate: bool,) -> None:unknown = sorted(set(adapters) - set(catalog))if unknown:@@ -342,6 +349,10 @@ class ServiceBroker:}self._store = storeself._token_retention = token_retention+ self._workspace_services = workspace_services+ # Whether a workspace admin's switch applies: on with the+ # `service_connections` flag, so with it off GitHub works as before.+ self._workspace_gate = workspace_gate# The access token being fetched for each connection, by (tenant,# owner, service), for callers that ask while it is.self._fetching: dict[tuple[str, str, str], asyncio.Task[AccessToken]] = {}@@ -381,6 +392,31 @@ class ServiceBroker:if reason is not None:raise ServiceError(403, FORBIDDEN, reason, retryable=False)+ async def require_workspace_enabled(+ self, session: AsyncSession, service: str+ ) -> None:+ """Refuse `service` where a workspace admin switched it off. The+ server's own switch (`DISABLED_SERVICES`) is checked first, so its+ reason is the one people see when both apply."""+ name = self._entry(service).definition.name+ if not self._workspace_gate:+ return+ self._require_switched_on(service)+ if not await self._workspace_services.is_enabled(session, service):+ raise ServiceError(+ 403,+ FORBIDDEN,+ f"{name} is not enabled in this workspace. Ask a workspace admin; "+ "they switch it on under Connectors in Switch Console.",+ retryable=False,+ )++ async def workspace_disabled(self, session: AsyncSession) -> set[str]:+ """The services a workspace admin switched off; none with the gate off."""+ if not self._workspace_gate:+ return set()+ return await self._workspace_services.disabled_services(session)+def _adapter(self, service: str) -> ServiceAdapter:"""The adapter that issues for `service`, or the refusal saying why not."""adapter = self._refresher(service)@@ -431,6 +467,7 @@ class ServiceBroker:) -> GrantDecision:entry = self._entry(service)self._require_switched_on(service)+ await self.require_workspace_enabled(session, service)name = entry.definition.nametenant_id = require_tenant_id()agent = await session.scalar(@@ -879,6 +916,18 @@ class ServiceBroker:"Connections.",retryable=False,)+ if self.client_replaced(connection):+ await self._store.mark_needs_reauthorization(+ session, owner_id, service, CLIENT_REPLACED+ )+ await session.commit()+ raise self._revoked(+ service,+ ReauthorizationRequiredError(+ f"{name} was connected through an app this server no "+ "longer uses."+ ),+ )secret = self._secret(connection)token = secret.access_tokenfresh = secret.expires_at > time.time() + before.total_seconds()@@ -968,8 +1017,14 @@ class ServiceBroker:issuing holds it to."""_require_owners_controller(principal, agent.owner_id)+ # A service the workspace switched off is left out, as if never+ # granted: the host restarts a running session without it. The grant+ # is kept, so switching it back on returns it.+ switched_off = await self.workspace_disabled(session)grants = []for grant in await self._store.list_grants(session, agent.id):+ if grant.service in switched_off:+ continueentry = self._catalog.get(grant.service)skill = None if entry is None else entry.skill_files.get("SKILL.md")mcp = None if entry is None else entry.definition.mcp@@ -1023,6 +1078,39 @@ class ServiceBroker:and service not in self._disabled)+ def server_setup_needed(self, service: str) -> bool:+ """Whether `service` waits on the operator setting up its app here."""+ entry = self._catalog.get(service)+ return (+ entry is not None+ and entry.definition.enabled+ and needs_operator_app(entry.definition)+ and service not in self._adapters+ )++ def client_replaced(self, connection: ServiceConnection) -> bool:+ """Whether `connection` signed in through a client its service no+ longer uses, so it must reconnect. Unknown either side is no."""+ if connection.oauth_client_id is None:+ return False+ adapter = self._adapters.get(connection.service)+ current = None if adapter is None else adapter.current_client_id()+ return current is not None and current != connection.oauth_client_id++ def replace_adapter(self, service: str, adapter: ServiceAdapter | None) -> None:+ """Use `adapter` for `service` from the next call on, or none.++ One assignment on the event loop, so a reader sees the old adapter or+ the new one, never a mix. A call already under way finishes on the+ adapter it started with.+ """+ if service not in self._catalog:+ raise ValueError(f"No service named {service!r} in the catalog.")+ if adapter is None:+ self._adapters.pop(service, None)+ else:+ self._adapters[service] = adapter+def availability(self, service: str) -> str | None:"""Why `service` cannot be granted on this server, or None if it can."""entry = self._catalog.get(service)@@ -1033,9 +1121,8 @@ class ServiceBroker:return reasonadapter = self._adapters.get(service)if adapter is None:- oauth = entry.definition.auth.oauth- if oauth is not None and oauth.setup_note is not None:- return f"Not set up on this server. {oauth.setup_note}"+ if needs_operator_app(entry.definition):+ return not_set_up(entry.definition.name)return f"{entry.definition.name} is not set up on this server."if not adapter.can_issue:return (@@ -1073,6 +1160,7 @@ class ServiceBroker:unavailable = self.availability(service)if unavailable is not None:raise ServiceError(422, VALIDATION_ERROR, unavailable, retryable=False)+ await self.require_workspace_enabled(session, service)entry = self._entry(service)name = entry.definition.nameadapter = self._adapter(service)@@ -1332,9 +1420,13 @@ class ServiceBroker:account_id: str,external_identity: str,secret: ConnectionSecret,+ oauth_client_id: str | None,) -> str | None:"""Link the person's account, or re-link it in place.+ `oauth_client_id` is the vendor client the sign-in went through, None+ for a key.+Re-linking keeps the grants (a different account then fails them with`grant_account_changed`) and revokes what was issued on the oldsign-in, and the old sign-in itself when it is not the new one.@@ -1342,6 +1434,23 @@ class ServiceBroker:"""name = self._entry(service).definition.nameself._require_switched_on(service)+ try:+ await self.require_workspace_enabled(session, service)+ except ServiceError as refusal:+ # The vendor has already issued this sign-in: one Switch will not+ # keep is revoked, rather than left live with nobody holding it.+ previous = await self._store.get_connection(session, user_id, service)+ kept = previous is not None and (+ self._secret(previous).access_token == secret.access_token+ )+ await session.rollback()+ note = None if kept else await self._revoke_unkept(service, secret)+ raise ServiceError(+ refusal.status_code,+ refusal.code,+ refusal.message if note is None else f"{refusal.message} {note}",+ retryable=False,+ ) from Nonetry:await self._store.lock_connection(session, user_id, service)except ServiceConnectionBusy as error:@@ -1362,6 +1471,7 @@ class ServiceBroker:account_id=account_id,external_identity=external_identity,encrypted_secret=self._keyring.encrypt(json.dumps(secret.values)),+ oauth_client_id=oauth_client_id,)await record_audit_event(session,@@ -1400,6 +1510,37 @@ class ServiceBroker:warnings.append(ACCESS_WARNING)return " ".join(warnings) or None+ async def _revoke_unkept(+ self, service: str, secret: ConnectionSecret+ ) -> str | None:+ """Revoke a new sign-in that was not kept; a sentence for the person+ when it could not be. A key is the person's own, and theirs to keep."""+ definition = self._entry(service).definition+ if definition.adapter == "api_key":+ return None+ name = definition.name+ adapter = self._adapters.get(service)+ try:+ if adapter is None:+ raise ServiceUnavailableError(+ f"{name} is not available on this server."+ )+ async with asyncio.timeout(VENDOR_CALL_SECONDS):+ await adapter.revoke_connection(secret)+ except ConnectionNotRevocable:+ return None+ except Exception as error:+ logger.error(+ "%s unkept sign-in revocation failed: error_type=%s",+ service,+ type(error).__name__,+ )+ return (+ f"Switch could not revoke the sign-in {name} just issued. Remove "+ f"Switch from your {name} account's connected apps."+ )+ return None+async def check_key(self, service: str, fields: dict[str, str]) -> CheckedKey:"""A pasted key for `service`, once its vendor accepts it: whose it is,and the secret a connection keeps. Connect it with `connect`, at@@ -1600,11 +1741,17 @@ class ServiceBroker:entry = self._catalog.get(service)name = service if entry is None else entry.definition.nameadapter = self._adapters.get(service)+ if adapter is None:+ logger.warning(+ "%s sign-in not revoked: the service is not set up on this server",+ service,+ )+ warnings.append(+ f"{name} is not set up on this server, so Switch could not "+ f"revoke the sign-in. Revoke it at {name}."+ )+ continuetry:- if adapter is None:- raise ServiceUnavailableError(- f"{name} is not available on this server."- )async with asyncio.timeout(VENDOR_CALL_SECONDS):await adapter.revoke_connection(secret)except ConnectionNotRevocable as error:diff --git a/core/switch_core/connections/catalog/google-workspace/connection.yaml b/core/switch_core/connections/catalog/google-workspace/connection.yamlindex 19ac16950..636d4c379 100644--- a/core/switch_core/connections/catalog/google-workspace/connection.yaml+++ b/core/switch_core/connections/catalog/google-workspace/connection.yaml@@ -9,8 +9,9 @@ auth:# Google's refresh tokens survive their use.refresh: reusableoauth:- # Each server's operator registers an internal Google app (a Web client)- # and names its settings in GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH.+ # Each server's operator registers a Google app (a Web client) and saves+ # it under Connectors in the dashboard, or names its settings in+ # GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH.registration: staticclient_settings: GOOGLE_WORKSPACEredirect: [core]@@ -23,8 +24,6 @@ auth:# personal one, or another organization's) does not pick it unasked.prompt: consent select_accountauthorization_params: { access_type: offline }- # Shown after "Not set up on this server." where the settings are unset.- setup_note: Its operator registers an internal Google app; see the docs.identity:url: https://openidconnect.googleapis.com/v1/userinfoaccount_id: subdiff --git a/core/switch_core/connections/flows.py b/core/switch_core/connections/flows.pyindex b3426fee5..7e7deffa2 100644--- a/core/switch_core/connections/flows.py+++ b/core/switch_core/connections/flows.py@@ -7,14 +7,15 @@ token. The browser comes back one of two ways, as the catalog allows and thisserver can offer:- **loopback**: the vendor redirects straight to Console's listener.-- **core**: the vendor redirects to Core's callback, which asks the person to- continue (showing whose Switch account the sign-in will join), then relays- the code to Console's listener. A cookie set when the browser left through- Core ties the return to that browser.+- **core**: the vendor redirects to Core's callback, which sends the browser+ straight on to Console's listener with the code. A cookie set when the+ browser left through Core ties the return to that browser.-Either way Console posts the code back with its completion secret, Core-exchanges it and reads the account, and Console confirms; only then is the-connection written, through `ServiceBroker.connect`.+Either way Console posts the code back with its completion secret, and Core+exchanges it, reads the account and writes the connection through+`ServiceBroker.connect` in that one step. The flow then reads connected, or+failed with the reason, holding no token, until it expires or Console drops+it.Flows are rows in `sign_in_flows` (`connections/sign_in_flows.py`), asGitHub's are, so any switch-core process can take any step: ten minutes each,@@ -28,7 +29,6 @@ from dataclasses import dataclassfrom urllib.parse import urlencodefrom switch_core.connections.adapters import (- ConnectionSecret,ReauthorizationRequiredError,ServiceAdapterError,)@@ -60,6 +60,10 @@ MAX_CODE_LENGTH = 8192INTERRUPTED = "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."++class FlowError(Exception):"""The flow cannot go on; the message is for the person."""@@ -68,8 +72,8 @@ class FlowError(Exception):class ServiceFlow:"""A service sign-in as its row stands.- Status runs pending → authorizing → (core: returning → delivered) →- checking → ready | failed.+ Status runs pending → authorizing → (core: delivered) → checking →+ connected | failed."""stored: StoredFlow@@ -98,30 +102,27 @@ class ServiceFlow:def port(self) -> int:return self.stored.port- @property- def owner_label(self) -> str:- return self.stored.owner_label-@propertydef error(self) -> str | None:return self.stored.error@property- def account(self) -> Identity | None:- result = self.stored.result- if result is None:- return None- return Identity(account_id=result["account_id"], label=result["account_label"])+ def account_label(self) -> str | None:+ return self.stored.account_label@property- def signed_in(self) -> SignIn | None:- result = self.stored.result- if result is None:- return None- return SignIn(- secret=ConnectionSecret(dict(result["secret"])),- granted_scopes=list(result["granted_scopes"]),- )+ def warning(self) -> str | None:+ return self.stored.warning+++@dataclass(frozen=True)+class Exchange:+ """What the vendor issued for a flow's code: held in memory only until+ the connection is written, never in the flow's row."""++ flow: StoredFlow+ signed_in: SignIn+ account: Identityclass ServiceFlows:@@ -234,13 +235,19 @@ class ServiceFlows:self, flow: ServiceFlow, adapter: OAuthAdapter) -> tuple[str, str]:"""Where the browser signs in at the vendor, and the nonce that marks- the browser sent there; once per flow."""+ the browser sent there; once per flow. The flow records the client it+ is sent through, so a code issued to one client is never exchanged+ with another."""nonce = secrets.token_urlsafe(32)+ client_id = await adapter.client_id()taken = await self._flows.advance(flow.stored,expect=("pending",),to="authorizing",- changes={"browser_nonce_hash": digest(nonce)},+ changes={+ "browser_nonce_hash": digest(nonce),+ "details": {**flow.stored.details, "client_id": client_id},+ },)if taken is None:raise FlowError("This sign-in has already been used. Connect again.")@@ -256,11 +263,12 @@ class ServiceFlows:raisereturn url, nonce- async def returning(self, flow: ServiceFlow, code: str, nonce: str) -> None:- """The browser is back at Core's callback, in core mode."""+ async def deliver(self, flow: ServiceFlow, code: str, nonce: str) -> str:+ """The browser is back at Core's callback, in core mode: where it+ takes the code on to Console's listener. Once per flow."""if (flow.mode != "core"- or flow.status not in ("authorizing", "returning")+ or flow.status != "authorizing"or len(code) > MAX_CODE_LENGTHor not flow.stored.holds_nonce(nonce)):@@ -269,29 +277,13 @@ class ServiceFlows:error = f"{flow.name} sign-in was cancelled."await self._flows.advance(flow.stored,- expect=("authorizing", "returning"),+ expect=("authorizing",),to="failed",changes={"error": error},)raise FlowError(error)taken = await self._flows.advance(- flow.stored, expect=("authorizing", "returning"), to="returning", changes={}- )- if taken is None:- raise FlowError("The sign-in could not be verified.")-- async def deliver(self, flow: ServiceFlow, code: str, nonce: str) -> str:- """The person continued: where their browser takes the code to Console."""- if (- flow.mode != "core"- or flow.status != "returning"- or not code- or len(code) > MAX_CODE_LENGTH- or not flow.stored.holds_nonce(nonce)- ):- raise FlowError("The sign-in could not be verified.")- taken = await self._flows.advance(- flow.stored, expect=("returning",), to="delivered", changes={}+ flow.stored, expect=("authorizing",), to="delivered", changes={})if taken is None:raise FlowError("The sign-in could not be verified.")@@ -306,8 +298,10 @@ class ServiceFlows:completion_secret: str,code: str,adapter: OAuthAdapter,- ) -> None:- """Console hands back the code; Core exchanges it and reads the account."""+ ) -> Exchange:+ """Console hands back the code; Core exchanges it and reads the account.+ The flow stays `checking` until the caller writes the connection and+ settles it with `connected` or `failed`."""ready_for = "authorizing" if flow.mode == "loopback" else "delivered"refused = FlowError(f"{flow.name} sign-in could not be verified. Connect again."@@ -325,6 +319,9 @@ class ServiceFlows:if checking is None:raise refusedtry:+ recorded = flow.stored.details.get("client_id")+ if recorded is not None and recorded != await adapter.client_id():+ raise ServiceAdapterError(client_changed(flow.name))signed_in = await adapter.exchange_code(code=code,verifier=flow.stored.verifier,@@ -333,64 +330,48 @@ class ServiceFlows:)account = await adapter.identify(signed_in.secret.access_token or "")except ReauthorizationRequiredError:- await self._fail(+ await self.failed(checking, f"{flow.name} refused the sign-in. Connect again.")raise FlowError(f"{flow.name} refused the sign-in. Connect again.") from Noneexcept ServiceAdapterError as error:- await self._fail(checking, str(error))+ await self.failed(checking, str(error))raise FlowError(str(error)) from Noneexcept BaseException:- await self._fail(checking, INTERRUPTED)+ await self.failed(checking, INTERRUPTED)raise- ready = await self._flows.advance(- checking,- expect=("checking",),- to="ready",- changes={- "encrypted_result": self._flows.seal(- {- "secret": signed_in.secret.values,- "granted_scopes": list(signed_in.granted_scopes),- "account_id": account.account_id,- "account_label": account.label,- }- ),- "account_label": account.label,- },- )- if ready is None:- # The flow expired or was cancelled while the code was exchanged:- # what the vendor issued has nowhere to go.- raise FlowError(INTERRUPTED)+ return Exchange(flow=checking, signed_in=signed_in, account=account)- async def _fail(self, flow: StoredFlow, error: str) -> None:- await self._flows.advance(- flow, expect=("checking",), to="failed", changes={"error": error}- )-- def consent(self, flow: ServiceFlow) -> AccessLevel:+ def consent(self, exchange: Exchange) -> AccessLevel:"""What the person consented to, as the vendor granted it."""- signed_in = flow.signed_in- assert signed_in is not None- granted = set(signed_in.granted_scopes)- write_scopes = set(flow.stored.details["write_scopes"])+ granted = set(exchange.signed_in.granted_scopes)+ details = exchange.flow.details+ write_scopes = set(details["write_scopes"])if write_scopes and write_scopes <= granted:return "write"- if set(flow.stored.details["read_scopes"]) <= granted:+ if set(details["read_scopes"]) <= granted:return "read"raise FlowError(- f"{flow.name} granted less than Switch needs to read. Connect again "- "and allow what it asks for."+ f"{details['name']} granted less than Switch needs to read. Connect "+ "again and allow what it asks for.")- def ready(self, flow: ServiceFlow, completion_secret: str) -> None:- if not flow.stored.holds_secret(completion_secret):- raise FlowError(INTERRUPTED)- if flow.status != "ready":- raise FlowError(f"Finish signing in to {flow.name} before confirming.")+ async def connected(self, exchange: Exchange, warning: str | None) -> None:+ """The connection is written: the outcome stays on the flow, without+ the token, for Console to read."""+ await self._flows.advance(+ exchange.flow,+ expect=("checking",),+ to="connected",+ changes={"account_label": exchange.account.label, "warning": warning},+ )++ async def failed(self, flow: StoredFlow, error: str) -> None:+ await self._flows.advance(+ flow, expect=("checking",), to="failed", changes={"error": error}+ )async def discard(self, flow: ServiceFlow) -> None:await self._flows.discard(flow.stored)diff --git a/core/switch_core/connections/loader.py b/core/switch_core/connections/loader.pyindex bec56261e..4fdd411d2 100644--- a/core/switch_core/connections/loader.py+++ b/core/switch_core/connections/loader.py@@ -65,8 +65,8 @@ AuthorizationParam = Literal["access_type", "include_granted_scopes"]class OAuthClient(BaseModel):"""How Core has its OAuth client at the vendor, and where a sign-in returns.- `registration`: `static`, a client the operator registers and names in- `<client_settings>_CLIENT_CONFIG_PATH`; or `dynamic`, one Core registers+ `registration`: `static`, a client the operator registers and saves from+ the dashboard or names in `<client_settings>_CLIENT_CONFIG_PATH`; or `dynamic`, one Core registersitself on first connect and stores. `redirect`: where the browser may comeback with the code, `core` (Core's own callback) or `loopback` (SwitchConsole's listener on 127.0.0.1), in the order offered. Without@@ -74,8 +74,6 @@ class OAuthClient(BaseModel):server's metadata. `revocation_url` is where a disconnect revokes thesign-in, where the vendor has one; `revocation_discovered` revokes at theauthorization server's advertised revocation endpoint instead.- `setup_note` tells people what a server without the client's settings- lacks.`loopback_ports`: the only ports Switch Console's listener may use, for avendor that matches a loopback redirect exactly, port included; without@@ -106,9 +104,6 @@ class OAuthClient(BaseModel):token_url: str | None = Field(default=None, pattern=HTTPS_URL_PATTERN)revocation_url: str | None = Field(default=None, pattern=HTTPS_URL_PATTERN)revocation_discovered: bool = False- setup_note: str | None = Field(- default=None, min_length=1, max_length=200, pattern=r"^[^\n]+$"- )@model_validator(mode="after")def _consistent(self) -> "OAuthClient":diff --git a/core/switch_core/connections/oauth_clients.py b/core/switch_core/connections/oauth_clients.pyindex 28f5627f8..c1f6a20b0 100644--- a/core/switch_core/connections/oauth_clients.py+++ b/core/switch_core/connections/oauth_clients.py@@ -115,6 +115,9 @@ class RegisteredClient:self._known: tuple[str, OAuthClientCredentials] | None = Noneself._lock = asyncio.Lock()+ def known_client_id(self) -> str | None:+ return None if self._known is None else self._known[1].client_id+async def credentials(self, endpoints: AuthorizationEndpoints) -> OAuthClientCredentials:diff --git a/core/switch_core/connections/registry.py b/core/switch_core/connections/registry.pyindex b8fd40e84..2099d7af5 100644--- a/core/switch_core/connections/registry.py+++ b/core/switch_core/connections/registry.py@@ -7,7 +7,9 @@ be used stop the server, rather than surfacing at the first connect.A static OAuth client's settings are a JSON file named by`<PREFIX>_CLIENT_CONFIG_PATH`, the prefix being the entry's-`auth.oauth.client_settings`, beside `GITHUB_APP_CONFIG_PATH` for GitHub.+`auth.oauth.client_settings`, beside `GITHUB_APP_CONFIG_PATH` for GitHub, or+the operator saves them from the dashboard; `connections/app_credentials.py`+resolves which applies, and hands the result here."""from __future__ import annotations@@ -99,77 +101,91 @@ def _every_scope(definition: ConnectionDefinition) -> list[str]:)+def build_adapter(+ slug: str,+ definition: ConnectionDefinition,+ *,+ github_app: GitHubApp | None,+ oauth_client: OAuthClientCredentials | None,+ http: httpx.AsyncClient,+ registration: ClientRegistration,+) -> ServiceAdapter | None:+ """The adapter for one enabled entry, or None where it is not set up.++ `github_app` and `oauth_client` are the app the operator set up for the+ entry, where its adapter needs one.+ """+ if definition.adapter == "github":+ # With the App alone, GitHub can be connected but not granted.+ if github_app is None:+ return None+ return GitHubAdapter(github_app.connections, github_app.signer)+ if definition.adapter == "oauth":+ oauth = definition.auth.oauth+ assert oauth is not None+ if oauth.registration == "dynamic":+ uris = redirect_uris(+ slug, oauth.redirect, registration.public_url, oauth.loopback_ports+ )+ if not uris:+ raise ServiceSetupError(+ f"Connection {slug} signs in only through Core's callback, "+ "which needs GATEWAY_PUBLIC_URL."+ )+ return OAuthAdapter(+ definition,+ RegisteredClient(+ service=slug,+ name=definition.name,+ session_factory=registration.session_factory,+ keyring=registration.keyring,+ http=http,+ client_name=client_name(+ registration.public_url, registration.server_name+ ),+ redirect_uris=uris,+ scopes=_every_scope(definition),+ ),+ http,+ )+ if oauth_client is None:+ return None+ return OAuthAdapter(definition, StaticClient(oauth_client), http)+ if definition.adapter == "api_key":+ # A key needs nothing set up on the server: people paste their own.+ return ApiKeyAdapter(definition, http)+ raise ServiceSetupError(+ f"Connection {slug} names the {definition.adapter} adapter, which "+ "this server does not have."+ )++def build_adapters(catalog: dict[str, Connection],*,github_app: GitHubApp | None,- environ: Mapping[str, str],+ oauth_clients: Mapping[str, OAuthClientCredentials],http: httpx.AsyncClient,registration: ClientRegistration,) -> dict[str, ServiceAdapter]:"""An adapter for each enabled entry this server is set up for.+ `oauth_clients` are the static clients the operator set up, by service.`http` is how OAuth/MCP adapters reach their vendors: one client, held tothe server's outbound policy."""adapters: dict[str, ServiceAdapter] = {}for slug, entry in catalog.items():- definition = entry.definition- if not definition.enabled:+ if not entry.definition.enabled:continue- if definition.adapter == "github":- # With the App alone, GitHub can be connected but not granted.- if github_app is not None:- adapters[slug] = GitHubAdapter(- github_app.connections, github_app.signer- )- elif definition.adapter == "oauth":- oauth = definition.auth.oauth- assert oauth is not None- if oauth.registration == "dynamic":- uris = redirect_uris(- slug, oauth.redirect, registration.public_url, oauth.loopback_ports- )- if not uris:- raise ServiceSetupError(- f"Connection {slug} signs in only through Core's callback, "- "which needs GATEWAY_PUBLIC_URL."- )- adapters[slug] = OAuthAdapter(- definition,- RegisteredClient(- service=slug,- name=definition.name,- session_factory=registration.session_factory,- keyring=registration.keyring,- http=http,- client_name=client_name(- registration.public_url, registration.server_name- ),- redirect_uris=uris,- scopes=_every_scope(definition),- ),- http,- )- continue- assert oauth.client_settings is not None- settings = load_client_settings(oauth.client_settings, environ)- if settings is not None:- adapters[slug] = OAuthAdapter(- definition,- StaticClient(- OAuthClientCredentials(- settings.client_id, settings.client_secret- )- ),- http,- )- elif definition.adapter == "api_key":- # A key needs nothing set up on the server: people paste their own.- adapters[slug] = ApiKeyAdapter(definition, http)- else:- raise ServiceSetupError(- f"Connection {slug} names the {definition.adapter} adapter, which "- "this server does not have."- )+ adapter = build_adapter(+ slug,+ entry.definition,+ github_app=github_app,+ oauth_client=oauth_clients.get(slug),+ http=http,+ registration=registration,+ )+ if adapter is not None:+ adapters[slug] = adapterreturn adaptersdiff --git a/core/switch_core/connections/sign_in_flows.py b/core/switch_core/connections/sign_in_flows.pyindex 7fd9afd23..de0075dbd 100644--- a/core/switch_core/connections/sign_in_flows.py+++ b/core/switch_core/connections/sign_in_flows.py@@ -4,7 +4,7 @@ any step of one.A person connecting GitHub (`gateway/github_connections.py`) or a catalogservice (`connections/flows.py`) from Switch Console goes through half a dozenrequests: Console starts the flow, the browser leaves for the vendor and comes-back, Console hands over the code, follows the flow and confirms it. With+back, Console hands over the code and reads the outcome. Withseveral processes behind one address each request may reach a different one,so the flow is a row in `sign_in_flows` rather than an entry in one process'smemory.@@ -85,6 +85,7 @@ class StoredFlow:result: Mapping[str, Any] | Noneaccount_label: str | Noneerror: str | None+ warning: str | Nonedef holds_secret(self, presented: str) -> bool:"""Whether `presented` is the completion secret Console started with."""@@ -294,4 +295,5 @@ class SignInFlows:),account_label=row.account_label,error=row.error,+ warning=row.warning,)diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex a141681d0..9d288d17e 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -1,4 +1,7 @@-"""The tenant audit log: append an event in the caller's transaction, read it back.+"""The audit logs: append an event in the caller's transaction, read it back.++A tenant's changes go to `audit_events`; a change to the server as a whole,+which no tenant owns, goes to `server_audit_events`.Functions rather than an injected store because there is nothing to hold: eachcall takes the session of the change it records, so the event commits or rolls@@ -14,7 +17,7 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import AuditEvent+from switch_core.db.models import AuditEvent, ServerAuditEventclass AuditAction(StrEnum):@@ -43,6 +46,14 @@ class AuditAction(StrEnum):SERVICE_DISCONNECTED = "service.disconnected"SERVICE_GRANT_SET = "service_grant.set"SERVICE_GRANT_REMOVED = "service_grant.removed"+ WORKSPACE_SERVICE_ENABLED = "workspace_service.enabled"+ WORKSPACE_SERVICE_DISABLED = "workspace_service.disabled"+++class ServerAuditAction(StrEnum):+ CONNECTOR_APP_SAVED = "connector_app.saved"+ CONNECTOR_APP_IMPORTED = "connector_app.imported"+ CONNECTOR_APP_REMOVED = "connector_app.removed"async def record_audit_event(@@ -69,6 +80,28 @@ async def record_audit_event(return event+async def record_server_audit_event(+ session: AsyncSession,+ *,+ actor_user_id: str | None,+ action: ServerAuditAction,+ target_type: str,+ target_id: str | None,+ details: dict[str, Any] | None,+) -> ServerAuditEvent:+ """Add a server-wide event to `session`; it lands when the caller commits."""+ event = ServerAuditEvent(+ actor_user_id=actor_user_id,+ action=action.value,+ target_type=target_type,+ target_id=target_id,+ details=details,+ )+ session.add(event)+ await session.flush()+ return event++async def list_audit_events(session: AsyncSession,*,diff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.pyindex e07ae787e..1dd0b5994 100644--- a/core/switch_core/db/key_rotation.py+++ b/core/switch_core/db/key_rotation.py@@ -38,6 +38,7 @@ from switch_core.db.models import (MessagingInstall,ProviderConnection,ServerConnector,+ ServiceAppCredential,ServiceConnection,ServiceOAuthClient,ServiceTokenIssuance,@@ -66,11 +67,13 @@ _ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = ((SignInFlow, "encrypted_result"),)# In tables no tenant holds (`db/rls_ddl.py`, GLOBAL_TABLES), one row set for-# the whole deployment (`trust_settings`, `service_oauth_clients`): rewritten+# the whole deployment (`trust_settings`, `service_oauth_clients`,+# `service_app_credentials`): rewritten# once, in a session bound to no tenant, rather than once per tenant._GLOBAL_ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = ((TrustSettings, "api_key_encrypted"),(ServiceOAuthClient, "encrypted_secret"),+ (ServiceAppCredential, "encrypted_secrets"),)diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 3d6c12c68..b5189b800 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -3960,6 +3960,10 @@ class ServiceConnection(TenantScoped, Base):encrypted_secret: Mapped[str] = mapped_column(Text, nullable=False)secret_revision: Mapped[int] = mapped_column(Integer, nullable=False)error_code: Mapped[str | None] = mapped_column(Text, nullable=True)+ # The OAuth client the sign-in went through, so a connection made through+ # a client the operator has since replaced is known to need reconnecting.+ # Null for a key, and for a sign-in made before it was recorded.+ oauth_client_id: Mapped[str | None] = mapped_column(Text, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)@@ -3987,13 +3991,17 @@ class SignInFlow(TenantScoped, Base):conditional update only, so of two requests racing for one step exactlyone takes it.- Nothing secret is stored in the clear: the PKCE verifier and, once the code- is exchanged, the vendor's credentials are keyring-encrypted, and the- completion secret and browser nonce are kept as SHA-256 hashes, compared- against what Console and the browser present. `details` holds what the- flow asked the vendor for (its name, scopes and consent), none of it- secret. Rows expire after ten minutes, and expired ones are deleted as the- next flow in the workspace starts.+ Nothing secret is stored in the clear: the PKCE verifier is+ keyring-encrypted, and the completion secret and browser nonce are kept as+ SHA-256 hashes, compared against what Console and the browser present.+ The vendor's credentials never reach the row: the request that exchanges+ the code writes the connection, and the flow then holds the outcome+ (`account_label`, `warning` or `error`) for Console to read until it drops+ the flow. `encrypted_result` held those credentials between the exchange+ and a confirm step that is gone; it stays for a release that still writes+ it. `details` holds what the flow asked the vendor for (its name, scopes+ and consent), none of it secret. Rows expire after ten minutes, and+ expired ones are deleted as the next flow in the workspace starts."""__tablename__ = "sign_in_flows"@@ -4001,7 +4009,7 @@ class SignInFlow(TenantScoped, Base):CheckConstraint("kind IN ('github', 'service')", name="ck_sign_in_flows_kind"),CheckConstraint("status IN ('pending', 'authorizing', 'returning', 'delivered', "- "'checking', 'ready', 'failed')",+ "'checking', 'ready', 'connected', 'failed')",name="ck_sign_in_flows_status",),CheckConstraint("mode IN ('loopback', 'core')", name="ck_sign_in_flows_mode"),@@ -4026,6 +4034,7 @@ class SignInFlow(TenantScoped, Base):encrypted_result: Mapped[str | None] = mapped_column(Text, nullable=True)account_label: Mapped[str | None] = mapped_column(Text, nullable=True)error: Mapped[str | None] = mapped_column(Text, nullable=True)+ warning: Mapped[str | None] = mapped_column(Text, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)@@ -4058,6 +4067,88 @@ class ServiceOAuthClient(Base):)+class ServiceAppCredential(Base):+ """The app the operator registered at a service's vendor, for the whole server.++ A GitHub App or a static OAuth client, entered from the dashboard rather+ than a settings file (`connections/app_credentials.py`). One row per+ deployment and service, as `ServiceOAuthClient` is: the vendor sees one+ Switch. `service` is a catalog slug, checked in code. `client_id` and+ `settings` (non-secret extras, such as a GitHub App's slug) are kept in the+ clear; `encrypted_secrets` is keyring-encrypted JSON of every secret the+ kind has, so a kind with more secrets needs no migration.+ """++ __tablename__ = "service_app_credentials"++ service: Mapped[str] = mapped_column(Text, primary_key=True)+ client_id: Mapped[str] = mapped_column(Text, nullable=False)+ settings: Mapped[dict] = mapped_column(JSONB, nullable=False)+ encrypted_secrets: Mapped[str] = mapped_column(Text, nullable=False)+ updated_by: Mapped[str] = mapped_column(+ Text, ForeignKey("users.id"), nullable=False+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+++class ServerAuditEvent(Base):+ """One change to the server as a whole: who did what, to what, when.++ `AuditEvent` records a tenant's history; a change no tenant owns, such as+ the operator setting up a connector's app, has no tenant to be filed+ under, so it lands here. The same shape and the same rules: append-only+ for the runtime role (`grant_runtime_role`), `actor_user_id` with no+ foreign key so the history outlives the account, and `details` holding+ identifiers and field names, never a secret.+ """++ __tablename__ = "server_audit_events"++ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)+ occurred_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.clock_timestamp(), nullable=False+ )+ actor_user_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ action: Mapped[str] = mapped_column(Text, nullable=False)+ target_type: Mapped[str] = mapped_column(Text, nullable=False)+ target_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ details: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+++class WorkspaceServiceSetting(TenantScoped, Base):+ """A workspace admin switched a catalog service on or off for the workspace.++ No row means on: a row is written only when an admin touches the switch,+ so `updated_by` always names a person. `service` is a catalog slug, checked+ in code as `ServiceConnection.service` is. Off, nobody in the workspace can+ connect, grant or be issued a token for it, and its grants drop out of+ what agents' sessions are given; the grants themselves are kept.+ """++ __tablename__ = "workspace_service_settings"+ __table_args__ = (PrimaryKeyConstraint("tenant_id", "service"),)++ service: Mapped[str] = mapped_column(Text, nullable=False)+ enabled: Mapped[bool] = mapped_column(Boolean, nullable=False)+ updated_by: Mapped[str] = mapped_column(+ Text, ForeignKey("users.id"), nullable=False+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )++class ServiceGrant(TenantScoped, Base):"""An agent may use its owner's connection to a service.diff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.pyindex 9947aa757..858b49689 100644--- a/core/switch_core/db/rls_ddl.py+++ b/core/switch_core/db/rls_ddl.py@@ -158,6 +158,15 @@ POLICY_NAME = "tenant_isolation"# added to the schema (`db/schema_version.py`), as Alembic's own# `alembic_version` records which is applied. It describes the schema and# holds no data of anyone's.+#+# `service_app_credentials` is the same for an app the operator registered at+# the vendor (a GitHub App, a static OAuth client) and entered from the+# dashboard: one per deployment and service, shared by every tenant's+# sign-ins. A workspace's own app would be a new scoped table, not a row here.+#+# `server_audit_events` is the history of changes no tenant owns, such as the+# operator setting up one of those apps. `audit_events` is scoped, so a+# server-wide change has no tenant to be filed under there.GLOBAL_TABLES = frozenset({"cloud_machines",@@ -171,6 +180,8 @@ GLOBAL_TABLES = frozenset("trust_settings","service_oauth_clients","schema_expand_only_revisions",+ "service_app_credentials",+ "server_audit_events",})diff --git a/core/switch_core/db/runtime_role.py b/core/switch_core/db/runtime_role.pyindex afe02c908..c942c6b3c 100644--- a/core/switch_core/db/runtime_role.py+++ b/core/switch_core/db/runtime_role.py@@ -153,9 +153,10 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:it is a statement about what this owner creates, and this owner createsonly this schema.- `audit_events` is the one table the role may not change once written: it- gets `SELECT` and `INSERT` there and nothing else, so a compromised or- buggy process can add to a tenant's history but not rewrite it. The+ `audit_events` and `server_audit_events` are the tables the role may not+ change once written: it gets `SELECT` and `INSERT` there and nothing+ else, so a compromised or buggy process can add to a tenant's or the+ server's history but not rewrite it. Therevoke follows the blanket grant on every boot, so the next boot puts itback if anything granted more in between.@@ -168,6 +169,7 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:f"GRANT USAGE ON SCHEMA public TO {identifier}",f"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {identifier}",f"REVOKE UPDATE, DELETE ON audit_events FROM {identifier}",+ f"REVOKE UPDATE, DELETE ON server_audit_events FROM {identifier}",f"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {identifier}","REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC",f"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO {identifier}",diff --git a/core/switch_core/db/stores/service_app_credential_store.py b/core/switch_core/db/stores/service_app_credential_store.pynew file mode 100644index 000000000..bc1860b53--- /dev/null+++ b/core/switch_core/db/stores/service_app_credential_store.py@@ -0,0 +1,132 @@+"""The apps the operator registered at connectors' vendors, one per service.++A global table (`rls_ddl.GLOBAL_TABLES`): read and written in whatever+session the caller holds, bound to a tenant or not. The secrets are one+keyring-encrypted JSON object per row; a save that names only some of them+keeps the rest.+"""++from __future__ import annotations++import json++from sqlalchemy import delete, select, text+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import ServiceAppCredential+from switch_core.keys import Keyring+++class MissingSecretsError(ValueError):+ """A save would leave the service without every secret its kind has."""++ def __init__(self, names: list[str]) -> None:+ super().__init__(f"Missing: {', '.join(names)}.")+ self.names = names+++class ServiceAppCredentialStore:+ def __init__(self, keyring: Keyring) -> None:+ self._keyring = keyring++ async def get(+ self, session: AsyncSession, service: str+ ) -> ServiceAppCredential | None:+ result = await session.execute(+ select(ServiceAppCredential)+ .where(ServiceAppCredential.service == service)+ .execution_options(populate_existing=True)+ )+ return result.scalar_one_or_none()++ async def list_all(self, session: AsyncSession) -> dict[str, ServiceAppCredential]:+ return {+ row.service: row+ for row in await session.scalars(+ select(ServiceAppCredential).execution_options(populate_existing=True)+ )+ }++ def secrets(self, row: ServiceAppCredential) -> dict[str, str]:+ """The row's secrets. Raises `UndecryptableError` when no key opens them."""+ values = json.loads(self._keyring.decrypt(row.encrypted_secrets))+ if not isinstance(values, dict) or not all(+ isinstance(value, str) for value in values.values()+ ):+ raise ValueError(f"The stored secrets for {row.service} are malformed.")+ return values++ async def save(+ self,+ session: AsyncSession,+ *,+ service: str,+ client_id: str,+ settings: dict[str, str],+ secrets: dict[str, str],+ secret_names: frozenset[str],+ updated_by: str,+ ) -> ServiceAppCredential:+ """Write the row, merging `secrets` over those already stored.++ `secret_names` are every secret the service's kind has. A save naming+ them all replaces what is stored without reading it, so one under a+ key since retired can be entered again; any other save must find the+ rest stored, or raises `MissingSecretsError`.++ Saves of one service are serialised by a lock held to the end of the+ caller's transaction, so two operators saving different secrets at+ once both land, and a first save racing another cannot insert twice.+ """+ await session.execute(+ text("SELECT pg_advisory_xact_lock(hashtextextended(:key, 0))"),+ {"key": f"service-app-credential:{service}"},+ )+ row = await self.get(session, service)+ if set(secrets) - secret_names:+ raise ValueError(+ f"{service} has no secret named {sorted(set(secrets) - secret_names)}."+ )+ stored = (+ {} if row is None or secret_names <= set(secrets) else self.secrets(row)+ )+ merged = {+ name: value+ for name, value in {**stored, **secrets}.items()+ if name in secret_names+ }+ missing = secret_names - set(merged)+ if missing:+ raise MissingSecretsError(sorted(missing))+ encrypted = self._keyring.encrypt(json.dumps(merged))+ if row is None:+ row = ServiceAppCredential(+ service=service,+ client_id=client_id,+ settings=dict(settings),+ encrypted_secrets=encrypted,+ updated_by=updated_by,+ )+ session.add(row)+ else:+ row.client_id = client_id+ row.settings = dict(settings)+ row.encrypted_secrets = encrypted+ row.updated_by = updated_by+ await session.flush()+ await session.refresh(row)+ return row++ async def remove(+ self, session: AsyncSession, service: str+ ) -> ServiceAppCredential | None:+ """Delete the row; the one removed, or None when there was none."""+ row = await self.get(session, service)+ if row is not None:+ await session.execute(+ delete(ServiceAppCredential).where(+ ServiceAppCredential.service == service+ )+ )+ await session.flush()+ return rowdiff --git a/core/switch_core/db/stores/service_connection_store.py b/core/switch_core/db/stores/service_connection_store.pyindex 5629a45c0..e364cc0ab 100644--- a/core/switch_core/db/stores/service_connection_store.py+++ b/core/switch_core/db/stores/service_connection_store.py@@ -101,6 +101,7 @@ class ServiceConnectionStore:account_id: str,external_identity: str,encrypted_secret: str,+ oauth_client_id: str | None,) -> None:"""Connect, or re-link in place: the grants on it are kept.@@ -114,6 +115,7 @@ class ServiceConnectionStore:"account_id": account_id,"external_identity": external_identity,"encrypted_secret": encrypted_secret,+ "oauth_client_id": oauth_client_id,"error_code": None,}await session.execute(diff --git a/core/switch_core/db/stores/workspace_service_store.py b/core/switch_core/db/stores/workspace_service_store.pynew file mode 100644index 000000000..af0666cc8--- /dev/null+++ b/core/switch_core/db/stores/workspace_service_store.py@@ -0,0 +1,67 @@+"""Which catalog services a workspace admin switched off for the workspace.++No row means on. Every query runs in the bound tenant.+"""++from __future__ import annotations++from sqlalchemy import func, select+from sqlalchemy.dialects.postgresql import insert+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import WorkspaceServiceSetting, require_tenant_id+++class WorkspaceServiceStore:+ async def disabled_services(self, session: AsyncSession) -> set[str]:+ return set(+ await session.scalars(+ select(WorkspaceServiceSetting.service).where(+ WorkspaceServiceSetting.tenant_id == require_tenant_id(),+ WorkspaceServiceSetting.enabled.is_(False),+ )+ )+ )++ async def is_enabled(self, session: AsyncSession, service: str) -> bool:+ enabled = await session.scalar(+ select(WorkspaceServiceSetting.enabled).where(+ WorkspaceServiceSetting.tenant_id == require_tenant_id(),+ WorkspaceServiceSetting.service == service,+ )+ )+ return enabled is not False++ async def list_settings(+ self, session: AsyncSession+ ) -> dict[str, WorkspaceServiceSetting]:+ """Every switch an admin has touched in the workspace, by service."""+ return {+ setting.service: setting+ for setting in await session.scalars(+ select(WorkspaceServiceSetting)+ .where(WorkspaceServiceSetting.tenant_id == require_tenant_id())+ .execution_options(populate_existing=True)+ )+ }++ async def set_enabled(+ self, session: AsyncSession, service: str, enabled: bool, user_id: str+ ) -> None:+ await session.execute(+ insert(WorkspaceServiceSetting)+ .values(+ tenant_id=require_tenant_id(),+ service=service,+ enabled=enabled,+ updated_by=user_id,+ )+ .on_conflict_do_update(+ index_elements=["tenant_id", "service"],+ set_={+ "enabled": enabled,+ "updated_by": user_id,+ "updated_at": func.now(),+ },+ )+ )diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 8fcda59a8..2870b4e3c 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -21,7 +21,7 @@ from switch_core.bridges.resource.service import ResourceServicefrom switch_core.chats.service import ChatError, ChatServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfig-from switch_core.connections.adapters.github import load_github_app+from switch_core.connections.app_credentials import ConnectorApps, install_github_appfrom switch_core.connections.flows import ServiceFlowsfrom switch_core.connections.sign_in_flows import SignInFlowsfrom switch_core.db.stores.agent_store import AgentStore@@ -45,6 +45,7 @@ from switch_core.gateway.chats import chat_error_responsefrom switch_core.gateway.chats import router as chats_routerfrom switch_core.gateway.collaborations import router as collaborations_routerfrom switch_core.gateway.connection_catalog import router as connection_catalog_router+from switch_core.gateway.connector_apps import router as connector_apps_routerfrom switch_core.gateway.connectors import router as connectors_routerfrom switch_core.gateway.dependencies import init_dependenciesfrom switch_core.gateway.documents import router as documents_router@@ -74,6 +75,9 @@ from switch_core.gateway.template_runs import router as template_runs_routerfrom switch_core.gateway.templates import router as templates_routerfrom switch_core.gateway.tenants import router as tenants_routerfrom switch_core.gateway.trust_settings import router as trust_settings_router+from switch_core.gateway.workspace_services import (+ router as workspace_services_router,+)from switch_core.keys import Purposefrom switch_core.providers.hosted import HostedControllerSettingsfrom switch_core.room_service import RoomService@@ -107,6 +111,7 @@ def create_gateway_app(install_service: MessagingInstallService | None,invite_mailer: InviteMailer | None,chat_service: ChatService,+ connector_apps: ConnectorApps,config: SwitchConfig,) -> FastAPI:init_dependencies(@@ -151,10 +156,8 @@ def create_gateway_app()app.include_router(hosted_machines_router, tags=["hosted-machines"])app.include_router(hosted_controller_router, tags=["hosted-controller"])- app.state.github_app = load_github_app(config)- app.state.github_connections = (- app.state.github_app.connections if app.state.github_app else None- )+ app.state.connector_apps = connector_apps+ install_github_app(app.state, connector_apps.github_app())app.include_router(github_connections_router,tags=["provider-connections"],@@ -170,6 +173,8 @@ def create_gateway_app(if config.service_connections_enabled:app.include_router(service_connections_router, tags=["service-connections"])app.include_router(service_flows_router, tags=["service-connections"])+ app.include_router(workspace_services_router, tags=["service-connections"])+ app.include_router(connector_apps_router, tags=["connector-apps"])# authlib's OIDC client stores transient state/nonce/PKCE in the request# session across the IdP redirect round-trip; SameSite=Lax lets the cookiediff --git a/core/switch_core/gateway/connector_apps.py b/core/switch_core/gateway/connector_apps.pynew file mode 100644index 000000000..8434ab1a7--- /dev/null+++ b/core/switch_core/gateway/connector_apps.py@@ -0,0 +1,641 @@+"""The operator sets up the apps connectors sign in through.++Deployment-operator only: `require_admin` (`users.role == "admin"`) gates+every route here, never `require_tenant_admin`, since one app serves every+workspace on the server. A workspace admin keeps the switch per service+(`gateway/workspace_services.py`) and nothing more. Mounted only with the+`service_connections` flag, with the rest of service connections, so a+server without the feature shows none of it; an app saved earlier still+loads at boot and serves GitHub's own sign-in.++Where an app comes from, and why configuration wins over a saved one, is+`connections/app_credentials.py`. A save is checked with the vendor first+(`connections/app_checks.py`) and stored only if the vendor accepts it; it+takes effect at once, in every process (`connections/app_signals.py`). No+response carries a secret: a client secret shows its last four characters,+a private key its fingerprint.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Annotated, Any, cast+from urllib.parse import urlsplit++from fastapi import APIRouter, Depends, HTTPException, Query, Request+from fastapi.responses import JSONResponse+from pydantic import BaseModel, ConfigDict, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.connections.app_checks import (+ CheckResult,+ VendorUnreachableError,+ check_app,+)+from switch_core.connections.app_credentials import (+ GITHUB_NEEDS_HTTPS,+ AppSpec,+ AppValues,+ ConnectorApps,+ EffectiveCredentials,+)+from switch_core.connections.broker import ServiceBroker, get_service_broker+from switch_core.connections.loader import CATALOG+from switch_core.connections.oauth_clients import core_callback+from switch_core.db.audit import ServerAuditAction, record_server_audit_event+from switch_core.db.models import (+ ServiceAppCredential,+ ServiceConnection,+ ServiceOAuthClient,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.service_app_credential_store import MissingSecretsError+from switch_core.db.tenant_lookup import all_tenant_ids+from switch_core.gateway.auth import require_admin+from switch_core.gateway.dependencies import get_session, get_session_factory+from switch_core.keys import UndecryptableError+from switch_core.providers.github_installation import GitHubInstallationCredentials++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/connector-apps")++GITHUB_CALLBACK_PATH = "/gateway/provider-connections/github/callback"+++def get_connector_apps(request: Request) -> ConnectorApps:+ apps = getattr(request.app.state, "connector_apps", None)+ if not isinstance(apps, ConnectorApps):+ raise RuntimeError("No connector apps are installed on this app.")+ return cast(ConnectorApps, apps)+++class SaveApp(BaseModel):+ """A save. A secret left out keeps the stored one; the first save, or+ one replacing a row no key opens, names them all. `replace` says the+ operator means to switch to another app: a different `client_id` is+ refused without it."""++ model_config = ConfigDict(extra="forbid")+ client_id: str = Field(min_length=1, max_length=512, pattern=r"^\S+$")+ client_secret: str | None = Field(default=None, min_length=1, max_length=4096)+ private_key: str | None = Field(default=None, min_length=1, max_length=16384)+ replace: bool+++@dataclass(frozen=True)+class Usage:+ """The connections a service has across every workspace."""++ # (tenant, status, recorded client) for each connection.+ rows: list[tuple[str, str, str | None]]++ def through(self, client_id: str | None) -> tuple[int, int]:+ """People and workspaces whose live connection goes through+ `client_id`; one recorded before clients were is taken to."""+ affected = [+ tenant+ for tenant, status, recorded in self.rows+ if status == "active" and (recorded is None or recorded == client_id)+ ]+ return len(affected), len(set(affected))++ def not_through(self, proposed: str, current: str | None) -> tuple[int, int]:+ """People and workspaces who must reconnect if `proposed` replaces+ `current`."""+ affected = [+ tenant+ for tenant, status, recorded in self.rows+ if status == "active" and (recorded or current) != proposed+ ]+ return len(affected), len(set(affected))++ def stale(self, current: str | None) -> int:+ """Connections made through an app this server no longer uses."""+ if current is None:+ return 0+ return sum(+ 1+ for _, _, recorded in self.rows+ if recorded is not None and recorded != current+ )+++async def _usage(+ session_factory: async_sessionmaker[AsyncSession], service: str+) -> Usage:+ """Read one workspace at a time, each bound before it is touched."""+ rows: list[tuple[str, str, str | None]] = []+ for tenant_id in await all_tenant_ids(session_factory):+ async with tenant_session(session_factory, tenant_id) as session:+ result = await session.execute(+ select(+ ServiceConnection.status, ServiceConnection.oauth_client_id+ ).where(+ ServiceConnection.tenant_id == tenant_id,+ ServiceConnection.service == service,+ )+ )+ rows.extend((tenant_id, status, client) for status, client in result)+ return Usage(rows)+++def _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.")+ return spec+++def _setup_blocked(spec: AppSpec, public_url: str | None) -> str | None:+ """Why the operator can't set this app up here, known before any vendor+ is asked. An unset GATEWAY_PUBLIC_URL is the page's own banner; Google+ accepts an http redirect for local development, GitHub does not."""+ if (+ spec.kind == "github_app"+ and public_url is not None+ and urlsplit(public_url).scheme != "https"+ ):+ return GITHUB_NEEDS_HTTPS+ return None+++def _refuse_while_blocked(spec: AppSpec, public_url: str | None) -> None:+ blocked = _setup_blocked(spec, public_url)+ if blocked is not None:+ raise HTTPException(409, blocked)+++def _redirect(+ spec: AppSpec, effective: EffectiveCredentials, public_url: str | None+) -> str | None:+ """Where the vendor sends people back to Switch, for the operator to register."""+ if spec.kind == "github_app":+ if effective.github_app is not None:+ return effective.github_app.connections.callback+ return (+ None+ if public_url is None or _setup_blocked(spec, public_url) is not None+ else public_url.rstrip("/") + GITHUB_CALLBACK_PATH+ )+ return None if public_url is None else core_callback(public_url, spec.service)+++def _secret_views(+ spec: AppSpec, secrets: dict[str, str] | None, stored: bool+) -> dict[str, dict[str, Any]]:+ """Whether each secret is set, and how the operator recognises it: never+ the secret, never more than its last four characters."""+ views: dict[str, dict[str, Any]] = {}+ for name in sorted(spec.secret_names):+ value = None if secrets is None else secrets.get(name)+ if name == "private_key":+ fingerprint = None+ if value is not None:+ try:+ fingerprint = GitHubInstallationCredentials(+ "unused", value.encode()+ ).fingerprint+ except ValueError:+ # A key that does not load: the entry's `load_error` says so.+ pass+ views[name] = {+ "set": value is not None or stored,+ "fingerprint": fingerprint,+ }+ else:+ views[name] = {+ "set": value is not None or stored,+ "last4": None if value is None or len(value) < 8 else value[-4:],+ }+ return views+++async def _entry(+ session: AsyncSession,+ session_factory: async_sessionmaker[AsyncSession],+ apps: ConnectorApps,+ spec: AppSpec,+) -> dict[str, Any]:+ effective = apps.effective(spec.service)+ row = await apps.store.get(session, spec.service)+ values = effective.values+ saved: AppValues | None = None+ if row is not None:+ try:+ saved = AppValues(+ row.client_id, dict(row.settings), apps.store.secrets(row)+ )+ except (UndecryptableError, ValueError):+ saved = None+ shown = values or saved+ current = None if values is None else values.client_id+ usage = await _usage(session_factory, spec.service)+ people, workspaces = usage.through(current) if current is not None else (0, 0)+ updated_by = None+ if row is not None:+ user = await session.get(User, row.updated_by)+ updated_by = None if user is None else user.name+ slug = None if shown is None else shown.settings.get("slug")+ return {+ "slug": spec.service,+ "name": spec.name,+ "kind": spec.kind,+ "source": effective.source,+ "configuration_variables": list(+ effective.configuration_variables+ if effective.source == "configuration"+ else spec.variables+ ),+ "deprecated": effective.deprecated,+ "client_id": (+ current if current is not None else (None if row is None else row.client_id)+ ),+ "saved_client_id": None if row is None else row.client_id,+ "fields": {"slug": slug} if spec.kind == "github_app" else {},+ "secrets": _secret_views(+ spec, None if shown is None else shown.secrets, row is not None+ ),+ "saved_ignored": effective.saved_ignored,+ "unreadable": effective.unreadable,+ "load_error": effective.load_error,+ "redirect_uri": _redirect(spec, effective, apps.public_url),+ "setup_blocked": _setup_blocked(spec, apps.public_url),+ "install_url": (+ f"https://github.com/apps/{slug}/installations/new"+ if spec.kind == "github_app" and slug+ else None+ ),+ "updated_by_name": updated_by,+ "updated_at": None if row is None else row.updated_at.isoformat(),+ "connected_members": people,+ "workspaces": workspaces,+ "stale_connections": usage.stale(current),+ }+++async def _registered(session: AsyncSession) -> list[dict[str, Any]]:+ """Services whose client Core registers for itself: nothing to set up."""+ rows = {+ row.service: row for row in await session.scalars(select(ServiceOAuthClient))+ }+ entries = []+ for slug, entry in CATALOG.items():+ oauth = entry.definition.auth.oauth+ if (+ not entry.definition.enabled+ or entry.definition.adapter != "oauth"+ or oauth is None+ or oauth.registration != "dynamic"+ ):+ continue+ row = rows.get(slug)+ entries.append(+ {+ "slug": slug,+ "name": entry.definition.name,+ "kind": "registered",+ "client_id": None if row is None else row.oauth_client_id,+ "registered_at": None if row is None else row.created_at.isoformat(),+ }+ )+ return entries+++def _refuse_while_configured(effective: EffectiveCredentials) -> None:+ if effective.source == "configuration":+ variables = " and ".join(effective.configuration_variables)+ verb = "are" if len(effective.configuration_variables) > 1 else "is"+ raise HTTPException(+ 409,+ f"{variables} {verb} set, so Switch uses that. Copy it into Switch, "+ "then unset it and restart.",+ )+++def _checks_body(result: CheckResult) -> list[dict[str, Any]]:+ return [+ {+ "name": check.name,+ "ok": check.ok,+ "message": check.message,+ "field": check.field,+ }+ for check in result.checks+ ]+++async def _check(apps: ConnectorApps, spec: AppSpec, values: AppValues) -> CheckResult:+ public_url = apps.public_url+ if public_url is None:+ raise HTTPException(+ 409,+ "Set GATEWAY_PUBLIC_URL first: the vendor needs to know where to send "+ "people back to Switch.",+ )+ try:+ return await check_app(+ apps.http,+ spec,+ apps.definition(spec.service),+ values,+ core_callback(public_url, spec.service),+ )+ except VendorUnreachableError as error:+ raise HTTPException(503, str(error)) from None+++def _fields_changed(+ previous: AppValues | None,+ client_id: str,+ settings: dict[str, str],+ given: dict[str, str],+) -> list[str]:+ if previous is None:+ return sorted({"client_id", *settings, *given})+ changed = {+ name for name, value in given.items() if previous.secrets.get(name) != value+ }+ if previous.client_id != client_id:+ changed.add("client_id")+ changed.update(+ name for name, value in settings.items() if previous.settings.get(name) != value+ )+ return sorted(changed)+++async def list_connector_apps(+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[Any, Depends(get_session_factory)],+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ _admin: Annotated[User, Depends(require_admin)],+) -> dict[str, Any]:+ entries = [+ await _entry(session, session_factory, apps, spec)+ for spec in apps.specs.values()+ ]+ return {+ "public_url": apps.public_url,+ "apps": entries,+ "registered": await _registered(session),+ }++[email protected]("/{service}", response_model=None)+async def save_connector_app(+ service: str,+ body: SaveApp,+ request: Request,+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[Any, Depends(get_session_factory)],+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ admin: Annotated[User, Depends(require_admin)],+) -> dict[str, Any] | JSONResponse:+ spec = _spec(apps, service)+ _refuse_while_configured(apps.effective(service))+ _refuse_while_blocked(spec, apps.public_url)+ given = {+ name: value+ for name, value in (+ ("client_secret", body.client_secret),+ ("private_key", body.private_key),+ )+ if value is not None+ }+ unknown = set(given) - spec.secret_names+ if unknown:+ raise HTTPException(422, f"{spec.name} has no {', '.join(sorted(unknown))}.")+ row = await apps.store.get(session, service)+ if row is not None and row.client_id != body.client_id and not body.replace:+ raise HTTPException(+ 409,+ "This is a different app: everyone connected through the current one "+ "would have to reconnect. Use a different app to switch on purpose.",+ )+ previous: AppValues | None = None+ if row is not None:+ try:+ previous = AppValues(+ row.client_id, dict(row.settings), apps.store.secrets(row)+ )+ except UndecryptableError:+ if not spec.secret_names <= set(given):+ raise HTTPException(+ 422,+ "Switch can't read the saved secret any more. Enter every "+ "secret again.",+ ) from None+ # Another app's secrets are no use to this one: switching names them all.+ kept = (+ {}+ if previous is None or previous.client_id != body.client_id+ else previous.secrets+ )+ candidate_secrets = {**kept, **given}+ missing = spec.secret_names - set(candidate_secrets)+ if missing:+ names = " and ".join(name.replace("_", " ") for name in sorted(missing))+ raise HTTPException(422, f"Enter the {names}.")+ result = await _check(+ apps,+ spec,+ AppValues(+ body.client_id,+ {} if previous is None else previous.settings,+ candidate_secrets,+ ),+ )+ if not result.ok:+ failure = result.first_failure()+ assert failure is not None+ return JSONResponse(+ status_code=422,+ content={+ "detail": failure.message,+ "field": failure.field,+ "checks": _checks_body(result),+ },+ )+ previous_client_id = None if row is None else row.client_id+ try:+ await apps.store.save(+ session,+ service=service,+ client_id=body.client_id,+ settings=result.settings,+ secrets=given,+ secret_names=spec.secret_names,+ updated_by=admin.id,+ )+ except MissingSecretsError as error:+ raise HTTPException(422, str(error)) from None+ details: dict[str, Any] = {+ "service": service,+ "fields_changed": _fields_changed(+ previous, body.client_id, result.settings, given+ ),+ "client_id": body.client_id,+ }+ if previous_client_id is not None and previous_client_id != body.client_id:+ details["previous_client_id"] = previous_client_id+ await record_server_audit_event(+ session,+ actor_user_id=admin.id,+ action=ServerAuditAction.CONNECTOR_APP_SAVED,+ target_type="service",+ target_id=service,+ details=details,+ )+ await session.commit()+ await apps.apply(service, broker=broker, state=request.app.state)+ apps.announce(service)+ logger.warning(+ "The operator saved %s's app: user=%s fields=%s",+ spec.name,+ admin.id,+ details["fields_changed"],+ )+ return await _entry(session, session_factory, apps, spec)++[email protected]("/{service}/import")+async def import_connector_app(+ service: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[Any, Depends(get_session_factory)],+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ admin: Annotated[User, Depends(require_admin)],+) -> dict[str, Any]:+ """Copy the app configuration names into a saved one, so the+ configuration can be removed with nothing retyped."""+ spec = _spec(apps, service)+ effective = apps.effective(service)+ if effective.source != "configuration" or effective.values is None:+ raise HTTPException(409, f"{spec.name} is not set from configuration.")+ _refuse_while_blocked(spec, apps.public_url)+ if effective.deprecated:+ raise HTTPException(+ 409,+ "HOSTED_GITHUB_CONFIG_PATH names no private key, so it can't be "+ "copied. Set up the GitHub App here instead, after unsetting it.",+ )+ app = effective.github_app+ if app is not None:+ expected = (+ None+ if apps.public_url is None+ else apps.public_url.rstrip("/") + GITHUB_CALLBACK_PATH+ )+ if app.connections.callback != expected:+ raise HTTPException(+ 409,+ f"The configured GitHub App is called back at "+ f"{app.connections.callback}, but a GitHub App saved here is called "+ f"back at GATEWAY_PUBLIC_URL ({apps.public_url or 'unset'}). Make "+ "them the same first.",+ )+ await apps.store.save(+ session,+ service=service,+ client_id=effective.values.client_id,+ settings=effective.values.settings,+ secrets=effective.values.secrets,+ secret_names=spec.secret_names,+ updated_by=admin.id,+ )+ await record_server_audit_event(+ session,+ actor_user_id=admin.id,+ action=ServerAuditAction.CONNECTOR_APP_IMPORTED,+ target_type="service",+ target_id=service,+ details={+ "service": service,+ "client_id": effective.values.client_id,+ "source_variables": list(effective.configuration_variables),+ },+ )+ await session.commit()+ await apps.reload(service)+ apps.announce(service)+ return await _entry(session, session_factory, apps, spec)++[email protected]("/{service}/check")+async def check_connector_app(+ service: str,+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ _admin: Annotated[User, Depends(require_admin)],+) -> dict[str, Any]:+ """Ask the vendor about the app in use; nothing is stored."""+ spec = _spec(apps, service)+ effective = apps.effective(service)+ # A configured GitHub App is called back at its own origin, not this URL.+ if effective.source != "configuration":+ _refuse_while_blocked(spec, apps.public_url)+ if effective.values is None:+ raise HTTPException(409, f"{spec.name} has no app to check.")+ if effective.deprecated:+ raise HTTPException(+ 409, "HOSTED_GITHUB_CONFIG_PATH names no private key to check."+ )+ result = await _check(apps, spec, effective.values)+ return {"ok": result.ok, "checks": _checks_body(result)}++[email protected]("/{service}/impact")+async def connector_app_impact(+ service: str,+ client_id: Annotated[str, Query(min_length=1, max_length=512)],+ session_factory: Annotated[Any, Depends(get_session_factory)],+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ _admin: Annotated[User, Depends(require_admin)],+) -> dict[str, int]:+ """Who would have to reconnect if `client_id` replaced the app in use."""+ _spec(apps, service)+ values = apps.effective(service).values+ usage = await _usage(session_factory, service)+ people, workspaces = usage.not_through(+ client_id, None if values is None else values.client_id+ )+ return {"connected_members": people, "workspaces": workspaces}++[email protected]("/{service}")+async def remove_connector_app(+ service: str,+ request: Request,+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[Any, Depends(get_session_factory)],+ apps: Annotated[ConnectorApps, Depends(get_connector_apps)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ admin: Annotated[User, Depends(require_admin)],+) -> dict[str, int]:+ """Remove the saved app. The connections made through it are kept, and+ unusable until an app is set up again; they can still be disconnected."""+ spec = _spec(apps, service)+ _refuse_while_configured(apps.effective(service))+ removed: ServiceAppCredential | None = await apps.store.remove(session, service)+ if removed is None:+ raise HTTPException(404, f"{spec.name} has no saved app.")+ await record_server_audit_event(+ session,+ actor_user_id=admin.id,+ action=ServerAuditAction.CONNECTOR_APP_REMOVED,+ target_type="service",+ target_id=service,+ details={"service": service, "client_id": removed.client_id},+ )+ await session.commit()+ await apps.apply(service, broker=broker, state=request.app.state)+ apps.announce(service)+ logger.warning("The operator removed %s's app: user=%s", spec.name, admin.id)+ people, workspaces = (await _usage(session_factory, service)).through(+ removed.client_id+ )+ return {"connected_members": people, "workspaces": workspaces}diff --git a/core/switch_core/gateway/github_connections.py b/core/switch_core/gateway/github_connections.pyindex e69eb9fc3..55054dd61 100644--- a/core/switch_core/gateway/github_connections.py+++ b/core/switch_core/gateway/github_connections.py@@ -1,9 +1,8 @@import asyncioimport loggingimport secrets-from html import escapefrom typing import Annotated, cast-from urllib.parse import parse_qs, urlencode+from urllib.parse import urlencodefrom fastapi import APIRouter, Depends, HTTPException, Request, Responsefrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse@@ -98,7 +97,7 @@ def page(message: str, status: int) -> HTMLResponse:headers={"Cache-Control": "no-store","Referrer-Policy": "no-referrer",- "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'",+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; base-uri 'none'",},)@@ -119,14 +118,19 @@ class CompleteFlow(FlowSecret):code: str = Field(min_length=1, max_length=512)[email protected]("/flows")[email protected]("/flows", response_model=None)async def start(body: StartFlow,session: Annotated[AsyncSession, Depends(get_session)],user: Annotated[User, Depends(get_current_user)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],github: Annotated[GitHubConnections, Depends(service)],flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],-) -> dict:+) -> dict | JSONResponse:+ try:+ await broker.require_workspace_enabled(session, "github")+ except ServiceError as error:+ return service_refusal(error)tenant = await session.get(Tenant, require_tenant_id())if tenant is None:raise HTTPException(404, "Workspace not found.")@@ -141,7 +145,7 @@ async def start(port=body.port,redirect_uri=github.callback,owner_label=f"{user.name} ({user.email}) in {tenant.name}",- details={},+ details={"client_id": github.client_id},completion_secret=body.completion_secret,)except FlowUsedError:@@ -201,12 +205,14 @@ async def callback(github: Annotated[GitHubConnections, Depends(service)],flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],) -> Response:+ """Back from GitHub: the browser takes the code on to Switch Console, on+ the computer it left from. Once per flow."""state = request.query_params.get("state", "")code = request.query_params.get("code", "")try:flow = await browser_flow(flows, state)if (- flow.status not in {"authorizing", "returning"}+ flow.status != "authorizing"or len(code) > 512or not flow.holds_nonce(request.cookies.get("switch_github_" + state, ""))):@@ -214,64 +220,18 @@ async def callback(if not code:await flows.advance(flow,- expect=("authorizing", "returning"),+ expect=("authorizing",),to="failed",changes={"error": "GitHub authorization was cancelled."},)raise GitHubError("GitHub authorization was cancelled.")if (await flows.advance(- flow, expect=("authorizing", "returning"), to="returning", changes={}+ flow, expect=("authorizing",), to="delivered", changes={})is None):raise GitHubError("Authorization could not be verified.")- response = page(- f"Linking GitHub to <strong>{escape(flow.owner_label)}</strong>. "- "Continue only if this is your Switch account. Use the same computer where you started the connection."- '<form method="post" action="/gateway/provider-connections/github/callback">'- f'<input type="hidden" name="state" value="{escape(state, quote=True)}">'- f'<input type="hidden" name="code" value="{escape(code, quote=True)}">'- '<button type="submit">Continue in Switch Console</button></form>',- 200,- )- response.headers["Content-Security-Policy"] = (- "default-src 'none'; frame-ancestors 'none'; "- f"form-action 'self' http://127.0.0.1:{flow.port}; base-uri 'none'"- )- return response- except GitHubError:- return page(INTERRUPTED, 400)--[email protected]("/callback")-async def relay(- request: Request,- github: Annotated[GitHubConnections, Depends(service)],- flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],-) -> Response:- body = bytearray()- async for chunk in request.stream():- body.extend(chunk)- if len(body) > 2048:- return page("Invalid authorization response.", 400)- value = parse_qs(body.decode("utf-8", errors="replace"))- state = value.get("state", [""])[0]- code = value.get("code", [""])[0]- try:- flow = await browser_flow(flows, state)- if (- not code- or len(code) > 512- or flow.status != "returning"- or not flow.holds_nonce(request.cookies.get("switch_github_" + state, ""))- ):- raise GitHubError("Authorization could not be verified.")- if (- await flows.advance(flow, expect=("returning",), to="delivered", changes={})- is None- ):- raise GitHubError("Authorization could not be verified.")response = RedirectResponse(f"http://127.0.0.1:{flow.port}/switch-github/callback?"+ urlencode({"code": code, "state": state}),@@ -290,18 +250,40 @@ async def relay(return page(INTERRUPTED, 400)[email protected]("/flows/{flow_id}/complete", status_code=204)+async def _settled(+ flows: SignInFlows, flow: StoredFlow, status: str, **changes: str | None+) -> None:+ """The flow's outcome, kept without the token for Console to read."""+ await flows.advance(flow, expect=("checking",), to=status, changes=changes)++[email protected]("/flows/{flow_id}/complete")async def complete(flow_id: str,body: CompleteFlow,user: Annotated[User, Depends(get_current_user)],+ session: Annotated[AsyncSession, Depends(get_session)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],github: Annotated[GitHubConnections, Depends(service)],flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],) -> Response:+ """Console hands back the code its listener received, with its secret:+ Core exchanges it, reads the account and writes the connection."""flow = await owned_flow(flows, flow_id, user.id)refused = "GitHub authorization could not be verified. Connect again."if not flow.holds_secret(body.completion_secret) or flow.status != "delivered":raise HTTPException(400, refused)+ recorded = flow.details.get("client_id")+ if recorded is not None and recorded != github.client_id:+ # The code was issued to the App the flow started with: with another+ # in its place, GitHub would refuse it, and less clearly.+ changed = (+ "This server's GitHub App changed during your sign-in. Start it again."+ )+ await flows.advance(+ flow, expect=("delivered",), to="failed", changes={"error": changed}+ )+ raise HTTPException(400, changed)checking = await flows.advance(flow, expect=("delivered",), to="checking", changes={})@@ -310,73 +292,10 @@ async def complete(try:credentials = await github.sign_in(body.code, flow.verifier)except (GitHubError, asyncio.CancelledError) as error:- await flows.advance(- checking,- expect=("checking",),- to="failed",- changes={"error": str(error) or INTERRUPTED},- )+ await _settled(flows, checking, "failed", error=str(error) or INTERRUPTED)if isinstance(error, GitHubError):raise HTTPException(400, str(error)) from Noneraise- ready = await flows.advance(- checking,- expect=("checking",),- to="ready",- changes={- "encrypted_result": flows.seal(credentials),- "account_label": credentials["login"],- },- )- if ready is None:- # The flow expired or was cancelled while the code was exchanged.- raise HTTPException(410, INTERRUPTED)- return Response(status_code=204)--[email protected]("/flows/{flow_id}")-async def flow_status(- flow_id: str,- user: Annotated[User, Depends(get_current_user)],- github: Annotated[GitHubConnections, Depends(service)],- flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],-) -> dict:- flow = await owned_flow(flows, flow_id, user.id)- return {- "status": flow.status- if flow.status in {"checking", "ready", "failed"}- else "pending",- "login": flow.account_label or "",- }--[email protected]("/flows/{flow_id}", status_code=204)-async def cancel(- flow_id: str,- user: Annotated[User, Depends(get_current_user)],- github: Annotated[GitHubConnections, Depends(service)],- flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],-) -> Response:- await flows.discard(await owned_flow(flows, flow_id, user.id))- return Response(status_code=204)--[email protected]("/flows/{flow_id}/confirm")-async def confirm(- flow_id: str,- body: FlowSecret,- user: Annotated[User, Depends(get_current_user)],- session: Annotated[AsyncSession, Depends(get_session)],- broker: Annotated[ServiceBroker, Depends(get_service_broker)],- github: Annotated[GitHubConnections, Depends(service)],- flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],-) -> Response:- flow = await owned_flow(flows, flow_id, user.id)- if not flow.holds_secret(body.completion_secret):- raise HTTPException(404, "Authorization not found.")- if flow.status != "ready" or flow.result is None:- raise HTTPException(409, "Finish GitHub authorization before confirming.")- credentials = dict(flow.result)await session.execute(text("SELECT pg_advisory_xact_lock(hashtextextended(:key, 0))"),{"key": f"github-link:{require_tenant_id()}"},@@ -391,10 +310,15 @@ async def confirm())if taken is not None:+ linked = (+ "This GitHub account is already linked to another Switch user in "+ "this workspace. Remove that link first."+ )+ await _settled(flows, checking, "failed", error=linked)return JSONResponse(status_code=409,content={- "detail": "This GitHub account is already linked to another Switch user in this workspace. Remove that link first.",+ "detail": linked,"code": "account_linked_elsewhere","retryable": False,},@@ -409,17 +333,55 @@ async def confirm(account_id=account_id,external_identity=credentials["login"],secret=ConnectionSecret(credentials),+ oauth_client_id=github.client_id,)except ServiceError as error:+ await _settled(flows, checking, "failed", error=error.message)return service_refusal(error)- await flows.discard(flow)+ await _settled(+ flows,+ checking,+ "connected",+ account_label=credentials["login"],+ warning=warning,+ )logger.info("GitHub account linked: tenant=%s user=%s github_user=%s",require_tenant_id(),user.id,account_id,)- return JSONResponse({"warning": warning})+ return JSONResponse({"warning": warning, "login": credentials["login"]})++[email protected]("/flows/{flow_id}")+async def flow_status(+ flow_id: str,+ user: Annotated[User, Depends(get_current_user)],+ github: Annotated[GitHubConnections, Depends(service)],+ flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],+) -> dict:+ flow = await owned_flow(flows, flow_id, user.id)+ return {+ "status": flow.status+ if flow.status in {"checking", "connected", "failed"}+ else "pending",+ "login": flow.account_label or "",+ "error": flow.error,+ "warning": flow.warning,+ }++[email protected]("/flows/{flow_id}", status_code=204)+async def drop(+ flow_id: str,+ user: Annotated[User, Depends(get_current_user)],+ github: Annotated[GitHubConnections, Depends(service)],+ flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],+) -> Response:+ """Console is done with the flow: cancelled, or its outcome read."""+ await flows.discard(await owned_flow(flows, flow_id, user.id))+ return Response(status_code=204)@router.get("")@@ -472,10 +434,14 @@ async def disconnect(user: Annotated[User, Depends(get_current_user)],session: Annotated[AsyncSession, Depends(get_session)],broker: Annotated[ServiceBroker, Depends(get_service_broker)],- github: Annotated[GitHubConnections, Depends(service)],flows: Annotated[SignInFlows, Depends(get_sign_in_flows)],) -> Response:- """Disconnect GitHub: its grants go, and what was issued is revoked."""+ """Disconnect GitHub: its grants go, and what was issued is revoked.++ Works with no App on the server too, so a connection made under an App+ since removed can still be dropped; the warning then says the sign-in+ could not be revoked.+ """try:warning = await broker.disconnect(session, user.id, "github")except ServiceError as error:diff --git a/core/switch_core/gateway/service_connections.py b/core/switch_core/gateway/service_connections.pyindex 04b9033c6..8c9ed2009 100644--- a/core/switch_core/gateway/service_connections.py+++ b/core/switch_core/gateway/service_connections.py@@ -87,6 +87,17 @@ def _grant_view(broker: ServiceBroker, agent: Agent, grant: ServiceGrant) -> dic}+def _status(broker: ServiceBroker, connection: ServiceConnection | None) -> str:+ """The connection's status, as a person acts on it: one made through an+ app this server has since replaced needs reconnecting before anyone uses+ it and finds out."""+ if connection is None:+ return "not_connected"+ if connection.status == "active" and broker.client_replaced(connection):+ return "needs_reauthorization"+ return connection.status++@router.get("/service-connections")async def list_service_connections(user: Annotated[User, Depends(get_current_user)],@@ -98,6 +109,7 @@ async def list_service_connections(connection.service: connectionfor connection in await STORE.list_connections(session, user.id)}+ switched_off = await broker.workspace_disabled(session)entries = []for entry in CATALOG.values():definition = entry.definition@@ -114,6 +126,11 @@ async def list_service_connections("connectable": broker.connectable(definition.slug),"configured": unavailable is None,"unavailable_reason": unavailable,+ # Whether it waits on the server's operator setting up its app+ # under Connectors, so a client can offer them that.+ "server_setup_needed": broker.server_setup_needed(definition.slug),+ # Whether a workspace admin left it on for this workspace.+ "workspace_enabled": definition.slug not in switched_off,# A grant hands the agent the owner's own token: it is on or# off, at the connection's level, and lasts the token's life."pass_through": (@@ -133,7 +150,7 @@ async def list_service_connections(# What a person pastes to connect a service connected with a# key, and where they make one; null for any other."key": _key_form(definition),- "status": "not_connected" if connection is None else connection.status,+ "status": _status(broker, connection),"consent": None if connection is None else connection.consent,"external_identity": (None if connection is None else connection.external_identity@@ -143,6 +160,44 @@ async def list_service_connections(return {"connections": entries}[email protected]("/service-connections/{service}/agents")+async def list_service_agents(+ service: str,+ user: Annotated[User, Depends(get_current_user)],+ session: Annotated[AsyncSession, Depends(get_session)],+) -> list[dict[str, Any]]:+ """The person's own agents in this workspace, whether each has a grant+ on `service`, and whether others can address it."""+ entry = CATALOG.get(service)+ if entry is None or not entry.definition.enabled:+ raise HTTPException(status_code=404, detail=f"No service named {service!r}.")+ agents = list(+ await session.scalars(+ select(Agent)+ .where(Agent.tenant_id == require_tenant_id(), Agent.owner_id == user.id)+ .order_by(Agent.name)+ )+ )+ granted = set(+ await session.scalars(+ select(ServiceGrant.agent_id).where(+ ServiceGrant.tenant_id == require_tenant_id(),+ ServiceGrant.owner_id == user.id,+ ServiceGrant.service == service,+ )+ )+ )+ return [+ {+ "agent_id": agent.id,+ "name": agent.display_name or agent.name,+ "granted": agent.id in granted,+ "addressing_open": await _others_can_address(session, agent, user),+ }+ for agent in agents+ ]++def _key_form(definition: ConnectionDefinition) -> dict[str, Any] | None:sign_in = definition.auth.api_keyif definition.adapter != "api_key" or sign_in is None:@@ -181,6 +236,8 @@ async def connect_with_key(sent back. Re-pasting replaces it in place, keeping the grants."""try:+ await broker.require_workspace_enabled(session, service)+ await session.commit()checked = await broker.check_key(service, body.fields)except ServiceError as error:return service_refusal(error)@@ -219,6 +276,7 @@ async def connect_with_key(account_id=checked.account_id,external_identity=checked.label,secret=checked.secret,+ oauth_client_id=None,)except ServiceError as error:return service_refusal(error)@@ -257,20 +315,14 @@ async def list_service_grants(async def _others_can_address(session: AsyncSession, agent: Agent, owner: User) -> bool:- """Whether someone other than the owner, or another person's agent, may- address the agent: what makes its grants usable by them."""+ """Whether someone other than the owner, or any agent, may address the+ agent: what makes its grants usable by them."""policy = parse_policy(agent.addressing_policy)if policy.is_open():return Trueidentities = await ExternalUserStore().get_by_user(session, owner.id)- own_agents = await session.scalars(- select(Agent.id).where(- Agent.tenant_id == require_tenant_id(), Agent.owner_id == owner.id- )- )return policy.admits_others(- owner_identity_ids={identity.id for identity in identities},- owner_agent_ids=set(own_agents),+ owner_identity_ids={identity.id for identity in identities})diff --git a/core/switch_core/gateway/service_flows.py b/core/switch_core/gateway/service_flows.pyindex fa694ce2b..440d4b401 100644--- a/core/switch_core/gateway/service_flows.py+++ b/core/switch_core/gateway/service_flows.py@@ -2,7 +2,7 @@The routes of `connections/flows.py`, for any catalog entry with the`oauth` adapter; GitHub keeps its own (`gateway/github_connections.py`).-Switch Console starts, completes, follows and confirms a flow as the signed-in+Switch Console starts, completes, follows and drops a flow as the signed-inperson; `authorize` and `callback` are the browser's, in core mode, and aretied to the flow by its state and a cookie rather than by a session."""@@ -12,7 +12,6 @@ from __future__ import annotationsimport loggingfrom html import escapefrom typing import Annotated, cast-from urllib.parse import parse_qsfrom fastapi import APIRouter, Depends, HTTPException, Request, Responsefrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse@@ -75,8 +74,7 @@ def _page(name: str, message: str, status: int) -> HTMLResponse:"Cache-Control": "no-store","Referrer-Policy": "no-referrer","Content-Security-Policy": (- "default-src 'none'; frame-ancestors 'none'; form-action 'self'; "- "base-uri 'none'"+ "default-src 'none'; frame-ancestors 'none'; base-uri 'none'"),},)@@ -121,6 +119,7 @@ async def start() -> dict | JSONResponse:"""Begin signing in: where to send the browser, and which way it returns."""try:+ await broker.require_workspace_enabled(session, service)definition, adapter = broker.sign_in(service)except ServiceError as error:return service_refusal(error)@@ -191,49 +190,10 @@ async def callback(request: Request,flows: Annotated[ServiceFlows, Depends(get_service_flows)],) -> Response:- """Back from the vendor: the person says this is their Switch account."""+ """Back from the vendor: the browser takes the code on to Switch Console,+ on the computer it left from."""state = request.query_params.get("state", "")code = request.query_params.get("code", "")- try:- flow = await flows.flow(state)- if flow.service != service:- raise FlowError(INTERRUPTED)- await flows.returning(flow, code, request.cookies.get(_cookie(state), ""))- except FlowError:- return _page("Connections", INTERRUPTED, 400)- response = _page(- flow.name,- f"Linking {escape(flow.name)} to <strong>{escape(flow.owner_label)}</strong>. "- "Continue only if this is your Switch account. Use the same computer where "- "you started the connection."- f'<form method="post" action="{_cookie_path(service)}">'- f'<input type="hidden" name="state" value="{escape(state, quote=True)}">'- f'<input type="hidden" name="code" value="{escape(code, quote=True)}">'- '<button type="submit">Continue in Switch Console</button></form>',- 200,- )- response.headers["Content-Security-Policy"] = (- "default-src 'none'; frame-ancestors 'none'; "- f"form-action 'self' http://127.0.0.1:{flow.port}; base-uri 'none'"- )- return response--[email protected]("/callback")-async def relay(- service: str,- request: Request,- flows: Annotated[ServiceFlows, Depends(get_service_flows)],-) -> Response:- """The person continued: their browser takes the code to Switch Console."""- body = bytearray()- async for chunk in request.stream():- body.extend(chunk)- if len(body) > 2 * MAX_CODE_LENGTH:- return _page("Connections", "Invalid sign-in response.", 400)- value = parse_qs(body.decode("utf-8", errors="replace"))- state = value.get("state", [""])[0]- code = value.get("code", [""])[0]try:flow = await flows.flow(state)if flow.service != service:@@ -258,23 +218,25 @@ async def relay(return response[email protected]("/{flow_id}/complete", status_code=204, response_model=None)[email protected]("/{flow_id}/complete", response_model=None)async def complete(service: str,flow_id: str,body: CompleteFlow,user: Annotated[User, Depends(get_current_user)],+ session: Annotated[AsyncSession, Depends(get_session)],broker: Annotated[ServiceBroker, Depends(get_service_broker)],flows: Annotated[ServiceFlows, Depends(get_service_flows)],-) -> Response:- """Console hands back the code its listener received, with its secret."""+) -> dict | JSONResponse:+ """Console hands back the code its listener received, with its secret:+ Core exchanges it, reads the account and writes the connection."""flow = await _owned(flows, service, flow_id, user)try:_, adapter = broker.sign_in(service)except ServiceError as error:return service_refusal(error)try:- await flows.complete(+ exchange = await flows.complete(flow,completion_secret=body.completion_secret,code=body.code,@@ -284,56 +246,12 @@ async def complete(raise HTTPException(400, str(error)) from Noneexcept ServiceUnavailableError as error:raise HTTPException(503, str(error)) from None- return Response(status_code=204)--[email protected]("/{flow_id}")-async def flow_status(- service: str,- flow_id: str,- user: Annotated[User, Depends(get_current_user)],- flows: Annotated[ServiceFlows, Depends(get_service_flows)],-) -> dict:- flow = await _owned(flows, service, flow_id, user)- return {- "status": (- flow.status if flow.status in ("checking", "ready", "failed") else "pending"- ),- "account": None if flow.account is None else flow.account.label,- "error": flow.error,- }--[email protected]("/{flow_id}", status_code=204)-async def cancel(- service: str,- flow_id: str,- user: Annotated[User, Depends(get_current_user)],- flows: Annotated[ServiceFlows, Depends(get_service_flows)],-) -> Response:- await flows.discard(await _owned(flows, service, flow_id, user))- return Response(status_code=204)--[email protected]("/{flow_id}/confirm", response_model=None)-async def confirm(- service: str,- flow_id: str,- body: FlowSecret,- user: Annotated[User, Depends(get_current_user)],- session: Annotated[AsyncSession, Depends(get_session)],- broker: Annotated[ServiceBroker, Depends(get_service_broker)],- flows: Annotated[ServiceFlows, Depends(get_service_flows)],-) -> dict | JSONResponse:- """The person confirms the account: the connection is written."""- flow = await _owned(flows, service, flow_id, user)try:- flows.ready(flow, body.completion_secret)- consent = flows.consent(flow)+ consent = flows.consent(exchange)except FlowError as error:- raise HTTPException(409, str(error)) from None- account, signed_in = flow.account, flow.signed_in- assert account is not None and signed_in is not None+ await flows.failed(exchange.flow, str(error))+ raise HTTPException(400, str(error)) from None+ account, signed_in = exchange.account, exchange.signed_inawait session.execute(text("SELECT pg_advisory_xact_lock(hashtextextended(:key, 0))"),{"key": f"service-link:{require_tenant_id()}:{service}"},@@ -347,13 +265,15 @@ async def confirm())if taken is not None:+ linked = (+ f"This {flow.name} account is already linked to another Switch "+ "user in this workspace. Remove that link first."+ )+ await flows.failed(exchange.flow, linked)return JSONResponse(status_code=409,content={- "detail": (- f"This {flow.name} account is already linked to another Switch "- "user in this workspace. Remove that link first."- ),+ "detail": linked,"code": "account_linked_elsewhere","retryable": False,},@@ -368,14 +288,48 @@ async def confirm(account_id=account.account_id,external_identity=account.label,secret=signed_in.secret,+ oauth_client_id=signed_in.client_id,)except ServiceError as error:+ await flows.failed(exchange.flow, error.message)return service_refusal(error)- await flows.discard(flow)+ await flows.connected(exchange, warning)logger.info("Service account linked: tenant=%s user=%s service=%s",require_tenant_id(),user.id,service,)- return {"warning": warning, "consent": consent}+ return {"warning": warning, "consent": consent, "account": account.label}++[email protected]("/{flow_id}")+async def flow_status(+ service: str,+ flow_id: str,+ user: Annotated[User, Depends(get_current_user)],+ flows: Annotated[ServiceFlows, Depends(get_service_flows)],+) -> dict:+ flow = await _owned(flows, service, flow_id, user)+ return {+ "status": (+ flow.status+ if flow.status in ("checking", "connected", "failed")+ else "pending"+ ),+ "account": flow.account_label,+ "error": flow.error,+ "warning": flow.warning,+ }++[email protected]("/{flow_id}", status_code=204)+async def drop(+ service: str,+ flow_id: str,+ user: Annotated[User, Depends(get_current_user)],+ flows: Annotated[ServiceFlows, Depends(get_service_flows)],+) -> Response:+ """Console is done with the flow: cancelled, or its outcome read."""+ await flows.discard(await _owned(flows, service, flow_id, user))+ return Response(status_code=204)diff --git a/core/switch_core/gateway/workspace_services.py b/core/switch_core/gateway/workspace_services.pynew file mode 100644index 000000000..82c7bad7e--- /dev/null+++ b/core/switch_core/gateway/workspace_services.py@@ -0,0 +1,138 @@+"""A workspace admin's switch for each catalog service, for the whole workspace.++On by default: a service with no setting is usable. Switched off, nobody in the+workspace can connect it, grant it or be issued a token for it, and it drops+out of the grants every agent's session reads, so the session's host restarts+it without the service within about half a minute. Grants are kept, so+switching it back on returns them. A token already handed out may be used+until that restart; one the vendor can revoke (GitHub's) is revoked here.+"""++from __future__ import annotations++from datetime import datetime+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel, ConfigDict+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.connections.broker import (+ ACCESS_WARNING,+ ServiceBroker,+ get_service_broker,+)+from switch_core.connections.loader import CATALOG+from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import (+ ServiceConnection,+ ServiceGrant,+ ServiceTokenIssuance,+ User,+ require_tenant_id,+)+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore+from switch_core.gateway.auth import require_tenant_admin+from switch_core.gateway.dependencies import get_session++router = APIRouter(prefix="/workspace/services")+STORE = WorkspaceServiceStore()+++async def _counts(session: AsyncSession, column: Any, model: Any) -> dict[str, int]:+ rows = await session.execute(+ select(model.service, func.count(func.distinct(column)))+ .where(model.tenant_id == require_tenant_id())+ .group_by(model.service)+ )+ return {service: count for service, count in rows.tuples()}+++async def list_workspace_services(+ _: Annotated[User, Depends(require_tenant_admin)],+ session: Annotated[AsyncSession, Depends(get_session)],+) -> dict[str, Any]:+ """Every catalog service that can be connected, whether the workspace has+ it on, and who it reaches: what an admin weighs before switching it off."""+ settings = await STORE.list_settings(session)+ names = {+ user.id: user.name+ for user in await session.scalars(+ select(User).where(+ User.id.in_({setting.updated_by for setting in settings.values()})+ )+ )+ }+ connected = await _counts(session, ServiceConnection.user_id, ServiceConnection)+ granted = await _counts(session, ServiceGrant.agent_id, ServiceGrant)+ services = []+ for entry in CATALOG.values():+ definition = entry.definition+ if not definition.enabled:+ continue+ setting = settings.get(definition.slug)+ updated_at: datetime | None = None if setting is None else setting.updated_at+ services.append(+ {+ "slug": definition.slug,+ "name": definition.name,+ "enabled": setting is None or setting.enabled,+ "updated_by_name": (+ None if setting is None else names.get(setting.updated_by)+ ),+ "updated_at": None if updated_at is None else updated_at.isoformat(),+ "connected_members": connected.get(definition.slug, 0),+ "granted_agents": granted.get(definition.slug, 0),+ }+ )+ return {"services": services}+++class SwitchBody(BaseModel):+ model_config = ConfigDict(extra="forbid", strict=True)+ enabled: bool++[email protected]("/{service}")+async def set_workspace_service(+ service: str,+ body: SwitchBody,+ user: Annotated[User, Depends(require_tenant_admin)],+ session: Annotated[AsyncSession, Depends(get_session)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+) -> dict[str, Any]:+ """Switch `service` on or off for the workspace.++ Off queues every live token this workspace was issued for it, in the same+ transaction, and revokes them before answering; `warning` says when some+ could not be revoked yet, which the periodic tick keeps trying.+ """+ entry = CATALOG.get(service)+ if entry is None or not entry.definition.enabled:+ raise HTTPException(status_code=404, detail=f"No service named {service!r}.")+ await STORE.set_enabled(session, service, body.enabled, user.id)+ issued_for_it = (ServiceTokenIssuance.service == service,)+ if not body.enabled:+ await broker.queue_revocation(session, *issued_for_it)+ await record_audit_event(+ session,+ tenant_id=require_tenant_id(),+ actor_user_id=user.id,+ action=(+ AuditAction.WORKSPACE_SERVICE_ENABLED+ if body.enabled+ else AuditAction.WORKSPACE_SERVICE_DISABLED+ ),+ target_type="service",+ target_id=service,+ details={"service": service},+ )+ await session.commit()+ pending = not body.enabled and await broker.revoke_pending(session, issued_for_it)+ return {+ "slug": service,+ "enabled": body.enabled,+ "warning": ACCESS_WARNING if pending else None,+ }diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex dc97618d4..c61901204 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -101,7 +101,8 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.clients.client_signals import ClientSignalsfrom switch_core.clients.command_consumer import CommandConsumerfrom switch_core.config import SwitchConfig, deprecated_env_names-from switch_core.connections.adapters.github import GitHubApp+from switch_core.connections.app_credentials import ConnectorApps+from switch_core.connections.app_signals import ConnectorAppSignalsfrom switch_core.connections.broker import ServiceBrokerfrom switch_core.connections.github_move import move_github_connectionsfrom switch_core.connections.loader import CATALOG@@ -163,6 +164,7 @@ from switch_core.db.stores.room_link_store import RoomLinkStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.db.stores.service_app_credential_store import ServiceAppCredentialStorefrom switch_core.db.stores.service_connection_store import ServiceConnectionStorefrom switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStorefrom switch_core.db.stores.task_store import TaskStore@@ -170,6 +172,7 @@ from switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.delivery.conversation import ConversationRules, ConversationSettingsfrom switch_core.delivery.recipient import RecipientServices@@ -1116,6 +1119,27 @@ async def run(config: SwitchConfig, process_id: str) -> None:room_service.on_room_agents_changed(chat_service.sync_room)protocol.set_room_agents_listener(room_service.room_agents_changed)+ # ── Connector app credentials ─────────────────────────────────────────────+ # Each connector's app, from configuration or a row the operator saved,+ # before anything that serves a sign-in reads them.+ service_http = guarded_async_client(config.outbound_policy, timeout=20)+ service_registration = ClientRegistration(+ session_factory=session_factory,+ keyring=config.keyring,+ public_url=config.gateway_public_url,+ server_name=config.id_server_name,+ )+ connector_apps = ConnectorApps(+ catalog=CATALOG,+ config=config,+ environ=os.environ,+ session_factory=session_factory,+ store=ServiceAppCredentialStore(config.keyring),+ http=service_http,+ registration=service_registration,+ )+ await connector_apps.load()+# ── Gateway app ───────────────────────────────────────────────────────────gateway_app = create_gateway_app(agent_store=agent_store,@@ -1146,6 +1170,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:else None),chat_service=chat_service,+ connector_apps=connector_apps,config=config,)@@ -1246,29 +1271,32 @@ async def run(config: SwitchConfig, process_id: str) -> None:# A service is issued only where this server is set up for it, as its# catalog entry's adapter says (`connections/registry.py`). Without any,# the broker's upkeep still revokes and prunes whatever records exist.- github_app: GitHubApp | None = gateway_app.state.github_appservice_broker = ServiceBroker(session_factory=session_factory,keyring=config.keyring,catalog=CATALOG,adapters=build_adapters(CATALOG,- github_app=github_app,- environ=os.environ,- http=guarded_async_client(config.outbound_policy, timeout=20),- registration=ClientRegistration(- session_factory=session_factory,- keyring=config.keyring,- public_url=config.gateway_public_url,- server_name=config.id_server_name,- ),+ github_app=connector_apps.github_app(),+ oauth_clients=connector_apps.oauth_clients(),+ http=service_http,+ registration=service_registration,),disabled=config.disabled_services,store=ServiceConnectionStore(),token_retention=timedelta(days=config.service_token_retention_days),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=config.service_connections_enabled,)agent_bridge_app.state.service_broker = service_brokergateway_app.state.service_broker = service_broker+ # A connector app the operator saves or removes, put to work in every process.+ ConnectorAppSignals(+ apps=connector_apps,+ broker=service_broker,+ state=gateway_app.state,+ bus=signal_bus,+ )if config.service_connections_enabled:protocol.service_broker = service_brokerdiff --git a/core/switch_core/migrations/versions/98c28a6e7c55_workspace_service_settings.py b/core/switch_core/migrations/versions/98c28a6e7c55_workspace_service_settings.pynew file mode 100644index 000000000..a19c8313f--- /dev/null+++ b/core/switch_core/migrations/versions/98c28a6e7c55_workspace_service_settings.py@@ -0,0 +1,73 @@+"""workspace service settings: an admin's switch per service, per workspace++One tenant-scoped table, `workspace_service_settings`, keyed by tenant and+catalog slug, holding whether a workspace admin switched the service on or off.+No row means on, so an upgraded server behaves as before with the table empty:+there is no data step.++The row-level-security DDL is a verbatim copy of `switch_core/db/rls_ddl.py`+as it stood when this migration was written, copied rather than imported for+the reason `265ed188ad6f` gives.++Expand only: a process from before this revision never reads the table, and+reads every service as on, as it always did.++Revision ID: 98c28a6e7c55+Revises: 5f97c7c7407a+Create Date: 2026-10-14 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "98c28a6e7c55"+down_revision: str | Sequence[str] | None = "5f97c7c7407a"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"+TABLE = "workspace_service_settings"++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+++def _create_policy(table: str) -> str:+ return (+ f'CREATE POLICY {POLICY_NAME} ON "{table}"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+ )+++def upgrade() -> None:+ op.create_table(+ TABLE,+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("service", sa.Text(), nullable=False),+ sa.Column("enabled", sa.Boolean(), nullable=False),+ sa.Column("updated_by", sa.Text(), nullable=False),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.PrimaryKeyConstraint("tenant_id", "service"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_workspace_service_settings_tenant"+ ),+ sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),+ )+ op.execute(f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY')+ op.execute(_create_policy(TABLE))+++def downgrade() -> None:+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"')+ op.drop_table(TABLE)diff --git a/core/switch_core/migrations/versions/bf016e18bc16_sign_in_flows_settle_in_place.py b/core/switch_core/migrations/versions/bf016e18bc16_sign_in_flows_settle_in_place.pynew file mode 100644index 000000000..04506689b--- /dev/null+++ b/core/switch_core/migrations/versions/bf016e18bc16_sign_in_flows_settle_in_place.py@@ -0,0 +1,52 @@+"""sign_in_flows: a flow settles as connected or failed, with any warning++A sign-in connects as Switch Console hands the code back: that one request+exchanges it, reads the account and writes the connection, where before the+flow waited as `ready` for a confirm step. The flow then stays, holding no+token, so Console can read the outcome: `connected`, with any warning the+write carried, or `failed` with the reason. `status` admits `connected`, and+the row gains a nullable `warning`.++Expand only: every status a process from before this revision writes is still+admitted, and that process never reads `warning`. A `connected` row it reads+it reports as pending, as it does any status it does not know.++Revision ID: bf016e18bc16+Revises: 98c28a6e7c55+Create Date: 2026-10-16 12:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "bf016e18bc16"+down_revision: str | Sequence[str] | None = "98c28a6e7c55"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++TABLE = "sign_in_flows"+CONSTRAINT = "ck_sign_in_flows_status"+STATUSES_BEFORE = (+ "'pending', 'authorizing', 'returning', 'delivered', 'checking', 'ready', 'failed'"+)+STATUSES = (+ "'pending', 'authorizing', 'returning', 'delivered', 'checking', 'ready', "+ "'connected', 'failed'"+)+++def upgrade() -> None:+ op.add_column(TABLE, sa.Column("warning", sa.Text(), nullable=True))+ op.drop_constraint(CONSTRAINT, TABLE, type_="check")+ op.create_check_constraint(CONSTRAINT, TABLE, f"status IN ({STATUSES})")+++def downgrade() -> None:+ op.execute(f"DELETE FROM {TABLE} WHERE status = 'connected'")+ op.drop_constraint(CONSTRAINT, TABLE, type_="check")+ op.create_check_constraint(CONSTRAINT, TABLE, f"status IN ({STATUSES_BEFORE})")+ op.drop_column(TABLE, "warning")diff --git a/core/switch_core/migrations/versions/c7715ebb95c9_connector_app_credentials.py b/core/switch_core/migrations/versions/c7715ebb95c9_connector_app_credentials.pynew file mode 100644index 000000000..0ae25721a--- /dev/null+++ b/core/switch_core/migrations/versions/c7715ebb95c9_connector_app_credentials.py@@ -0,0 +1,82 @@+"""connector app credentials: the operator's apps at connectors' vendors++Two global tables, carrying no tenant and no policy (`db/rls_ddl.py`,+GLOBAL_TABLES):++- `service_app_credentials`: the app the operator registered at a service's+ vendor (a GitHub App, a static OAuth client), entered from the dashboard.+ One row per deployment and service, its secrets encrypted with the keyring.+- `server_audit_events`: the history of changes to the server as a whole,+ append-only for the runtime role as `audit_events` is (the revoke is+ reissued by `grant_runtime_role` on every boot).++And one nullable column, `service_connections.oauth_client_id`: the OAuth+client a sign-in went through. Existing rows stay null, meaning unknown;+there is no data step.++Revision ID: c7715ebb95c9+Revises: bf016e18bc16+Create Date: 2026-10-15 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "c7715ebb95c9"+down_revision: str | Sequence[str] | None = "bf016e18bc16"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "service_app_credentials",+ sa.Column("service", sa.Text(), nullable=False),+ sa.Column("client_id", sa.Text(), nullable=False),+ sa.Column("settings", postgresql.JSONB(), nullable=False),+ sa.Column("encrypted_secrets", sa.Text(), nullable=False),+ sa.Column("updated_by", sa.Text(), nullable=False),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ ),+ sa.PrimaryKeyConstraint("service"),+ sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),+ )+ op.create_table(+ "server_audit_events",+ sa.Column("id", sa.Text(), nullable=False),+ sa.Column(+ "occurred_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("clock_timestamp()"),+ nullable=False,+ ),+ sa.Column("actor_user_id", sa.Text(), nullable=True),+ sa.Column("action", sa.Text(), nullable=False),+ sa.Column("target_type", sa.Text(), nullable=False),+ sa.Column("target_id", sa.Text(), nullable=True),+ sa.Column("details", postgresql.JSONB(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ )+ op.add_column(+ "service_connections", sa.Column("oauth_client_id", sa.Text(), nullable=True)+ )+++def downgrade() -> None:+ op.drop_column("service_connections", "oauth_client_id")+ op.drop_table("server_audit_events")+ op.drop_table("service_app_credentials")diff --git a/core/switch_core/providers/github.py b/core/switch_core/providers/github.pyindex caa8e85f6..8c3ef6f94 100644--- a/core/switch_core/providers/github.py+++ b/core/switch_core/providers/github.py@@ -96,12 +96,13 @@ class GitHubReach:class GitHubConnections:- def __init__(self, config_path: str):- config = json.loads(Path(config_path).read_text())- self.client_id = config["client_id"]- self.client_secret = config["client_secret"]- self.slug = config["slug"]- self.origin = config["origin"].rstrip("/")+ def __init__(+ self, *, client_id: str, client_secret: str, slug: str, origin: str+ ) -> None:+ self.client_id = client_id+ self.client_secret = client_secret+ self.slug = slug+ self.origin = origin.rstrip("/")url = urlsplit(self.origin)if (url.scheme != "https"@@ -119,6 +120,16 @@ class GitHubConnections:self.callback = self.origin + "/gateway/provider-connections/github/callback"self.install_url = f"https://github.com/apps/{self.slug}/installations/new"+ @classmethod+ def from_file(cls, config_path: str) -> GitHubConnections:+ config = json.loads(Path(config_path).read_text())+ return cls(+ client_id=config["client_id"],+ client_secret=config["client_secret"],+ slug=config["slug"],+ origin=config["origin"],+ )+async def revoke(self, token: str) -> None:try:async with httpx.AsyncClient(timeout=8, follow_redirects=False) as client:diff --git a/core/switch_core/providers/github_installation.py b/core/switch_core/providers/github_installation.pyindex 7454c22ca..3c84ffc0a 100644--- a/core/switch_core/providers/github_installation.py+++ b/core/switch_core/providers/github_installation.py@@ -1,6 +1,8 @@from __future__ import annotationsimport asyncio+import base64+import hashlibimport loggingimport timefrom dataclasses import dataclass, field@@ -10,7 +12,11 @@ from pathlib import Pathimport httpximport jwtfrom cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey-from cryptography.hazmat.primitives.serialization import load_pem_private_key+from cryptography.hazmat.primitives.serialization import (+ Encoding,+ PublicFormat,+ load_pem_private_key,+)from switch_core.providers.github import (GitHubConnections,@@ -43,14 +49,12 @@ class RepositoryCredential:class GitHubInstallationCredentials:- def __init__(self, client_id: str, private_key_path: str):+ def __init__(self, client_id: str, private_key: bytes):if not client_id:raise ValueError("A GitHub App client ID is required.")try:- key = load_pem_private_key(- Path(private_key_path).read_bytes(), password=None- )- except (ValueError, TypeError, OSError):+ key = load_pem_private_key(private_key, password=None)+ except (ValueError, TypeError):raise ValueError("The GitHub App signing key could not be loaded.") from None@@ -61,6 +65,35 @@ class GitHubInstallationCredentials:self._key = keyself._client_id = client_id+ def assertion(self) -> str:+ """A JWT that authenticates as the App, for nine minutes."""+ now = int(time.time())+ return jwt.encode(+ {"iat": now - 60, "exp": now + 540, "iss": self._client_id},+ self._key,+ algorithm="RS256",+ )++ @property+ def fingerprint(self) -> str:+ """The key as GitHub's App settings list it: SHA-256 of the public key."""+ public = self._key.public_key().public_bytes(+ Encoding.DER, PublicFormat.SubjectPublicKeyInfo+ )+ return "SHA256:" + base64.b64encode(hashlib.sha256(public).digest()).decode()++ @classmethod+ def from_file(+ cls, client_id: str, private_key_path: str+ ) -> GitHubInstallationCredentials:+ try:+ private_key = Path(private_key_path).read_bytes()+ except OSError:+ raise ValueError(+ "The GitHub App signing key could not be loaded."+ ) from None+ return cls(client_id, private_key)+@staticmethodasync def revoke(token: str) -> None:try:@@ -143,12 +176,7 @@ class GitHubInstallationCredentials:or any(level not in ("read", "write") for level in permissions.values())):raise GitHubError("These GitHub permissions cannot be granted.")- now = int(time.time())- assertion = jwt.encode(- {"iat": now - 60, "exp": now + 540, "iss": self._client_id},- self._key,- algorithm="RS256",- )+ assertion = self.assertion()token = Nonetry:async with httpx.AsyncClient(timeout=20, follow_redirects=False) as client:diff --git a/core/tests/switch_core/bridges/agent/test_service_tokens.py b/core/tests/switch_core/bridges/agent/test_service_tokens.pyindex 317ab9824..a24dd0ced 100644--- a/core/tests/switch_core/bridges/agent/test_service_tokens.py+++ b/core/tests/switch_core/bridges/agent/test_service_tokens.py@@ -51,7 +51,7 @@ def vendor() -> FakeVendor:def harness(session_factory: async_sessionmaker[AsyncSession], vendor: FakeVendor) -> Harness:- return build_service_harness(session_factory, vendor)[0]+ return build_service_harness(session_factory, vendor, workspace_gate=False)[0]async def _fetch(harness: Harness, agent_id: str, headers: dict[str, str]):diff --git a/core/tests/switch_core/connections/adapters/test_oauth.py b/core/tests/switch_core/connections/adapters/test_oauth.pyindex 956094044..48edd27e6 100644--- a/core/tests/switch_core/connections/adapters/test_oauth.py+++ b/core/tests/switch_core/connections/adapters/test_oauth.py@@ -38,6 +38,7 @@ from switch_core.connections.adapters.oauth import (from switch_core.connections.broker import Principal, ServiceBrokerfrom switch_core.connections.loader import ConnectionDefinitionfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.fake_vendor import (IDENTITY_URL,@@ -471,6 +472,8 @@ class TestThroughTheBroker:disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)secret = await _sign_in(adapter, vendor)# Due for renewal: inside the fifteen minutes a pass-through keeps.@@ -490,6 +493,7 @@ class TestThroughTheBroker:account_id="acct-1",external_identity="[email protected]",encrypted_secret=TEST_KEYRING.encrypt(json.dumps(values)),+ oauth_client_id=None,)for agent in agents:await STORE.save_grant(diff --git a/core/tests/switch_core/connections/fake_vendor.py b/core/tests/switch_core/connections/fake_vendor.pyindex 9d33c5053..325cd741a 100644--- a/core/tests/switch_core/connections/fake_vendor.py+++ b/core/tests/switch_core/connections/fake_vendor.py@@ -54,6 +54,10 @@ class FakeVendor:self.grant_error: Exception | None = Noneself.checked: list[tuple[str, dict[str, Any]]] = []self.resolved: list[list[str]] = []+ self.client_id: str | None = None++ def current_client_id(self) -> str | None:+ return self.client_idasync def refresh(self, secret: ConnectionSecret) -> ConnectionSecret:self.refreshes += 1diff --git a/core/tests/switch_core/connections/github_seed.py b/core/tests/switch_core/connections/github_seed.pyindex d588b1314..1d3091993 100644--- a/core/tests/switch_core/connections/github_seed.py+++ b/core/tests/switch_core/connections/github_seed.py@@ -17,6 +17,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.connections.broker import ServiceBrokerfrom switch_core.connections.loader import CATALOGfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.keys import Keyringfrom tests.switch_core.connections.fake_vendor import FakeVendor@@ -51,6 +52,7 @@ async def connect_github(session: AsyncSession, owner: str, keyring: Keyring) ->})),+ oauth_client_id=None,)@@ -85,4 +87,6 @@ def github_broker(disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)diff --git a/core/tests/switch_core/connections/service_harness.py b/core/tests/switch_core/connections/service_harness.pyindex a09dd38ed..5c3f52977 100644--- a/core/tests/switch_core/connections/service_harness.py+++ b/core/tests/switch_core/connections/service_harness.py@@ -3,8 +3,10 @@`tests/switch_core/management/harness.py` wires the agent bridge behind thereal bearer middleware and controller authenticator, with the gateway mountedat `/gateway` behind real cookie sign-in. This adds the service-token agent-routes and the gateway's connection and grant API, on a broker whose only-adapter is a fake vendor standing in for GitHub.+routes, the gateway's connection and grant API and the workspace's service+switches, on a broker whose only adapter is a fake vendor standing in for+GitHub. `workspace_gate` is the `service_connections` flag as the broker+sees it: whether an admin's switch applies."""from __future__ import annotations@@ -25,9 +27,13 @@ from switch_core.connections.loader import CATALOGfrom switch_core.db.models import Agent, ApiKey, Client, ServiceGrant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway.service_connections import (router as service_connections_router,)+from switch_core.gateway.workspace_services import (+ router as workspace_services_router,+)from tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.fake_vendor import FakeVendorfrom tests.switch_core.management.harness import (@@ -45,7 +51,10 @@ RESOURCES = {"installation_id": 7, "repository_ids": [70, 71]}def build_service_harness(- session_factory: async_sessionmaker[AsyncSession], vendor: FakeVendor+ session_factory: async_sessionmaker[AsyncSession],+ vendor: FakeVendor,+ *,+ workspace_gate: bool,) -> tuple[Harness, ServiceBroker]:harness = build_harness(session_factory)broker = ServiceBroker(@@ -56,9 +65,12 @@ def build_service_harness(disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=workspace_gate,)harness.app.include_router(service_router, prefix="/agents")harness.gateway_app.include_router(service_connections_router)+ harness.gateway_app.include_router(workspace_services_router)harness.app.state.service_broker = brokerharness.gateway_app.state.service_broker = brokerreturn harness, broker@@ -134,6 +146,7 @@ async def connect(})),+ oauth_client_id=None,)await session.commit()diff --git a/core/tests/switch_core/connections/test_app_checks.py b/core/tests/switch_core/connections/test_app_checks.pynew file mode 100644index 000000000..4881031a7--- /dev/null+++ b/core/tests/switch_core/connections/test_app_checks.py@@ -0,0 +1,144 @@+"""Which refusal a vendor chose, read as whether an app's values belong together."""++from __future__ import annotations++import httpx+import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa++from switch_core.connections.app_checks import (+ VendorUnreachableError,+ check_github_app,+ check_oauth_client,+)+from switch_core.connections.app_credentials import AppValues+from switch_core.connections.loader import CATALOG++REDIRECT = "https://switch.example.test/gateway/service-connections/google-workspace/flows/callback"+GOOGLE = CATALOG["google-workspace"].definition+++def _http(status: int, body: object) -> httpx.AsyncClient:+ def handle(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, json=body)++ return httpx.AsyncClient(transport=httpx.MockTransport(handle))+++def _google(secret: str = "example-secret-0000") -> AppValues:+ return AppValues("example-client-id", {}, {"client_secret": secret})+++class TestOAuthClient:+ @pytest.mark.parametrize(+ ("status", "error", "ok", "says", "field"),+ [+ (400, "invalid_grant", True, "accepts this client ID and secret", None),+ (401, "invalid_client", False, "doesn't recognise", "client_secret"),+ (400, "unauthorized_client", False, "doesn't recognise", "client_secret"),+ (400, "redirect_uri_mismatch", False, REDIRECT, None),+ (400, "something_new", False, "something_new", None),+ ],+ )+ async def test_reads_googles_refusal(+ self, status: int, error: str, ok: bool, says: str, field: str | None+ ) -> None:+ result = await check_oauth_client(+ _http(status, {"error": error}), GOOGLE, _google(), REDIRECT+ )+ [check] = result.checks+ assert (check.ok, check.field) == (ok, field)+ assert says in check.message++ async def test_unreachable_is_its_own_answer(self) -> None:+ def handle(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("unreachable", request=request)++ with pytest.raises(VendorUnreachableError, match="Couldn't reach"):+ await check_oauth_client(+ httpx.AsyncClient(transport=httpx.MockTransport(handle)),+ GOOGLE,+ _google(),+ REDIRECT,+ )++ async def test_the_secret_is_sent_only_to_the_token_endpoint(self) -> None:+ seen: list[httpx.Request] = []++ def handle(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(400, json={"error": "invalid_grant"})++ await check_oauth_client(+ httpx.AsyncClient(transport=httpx.MockTransport(handle)),+ GOOGLE,+ _google(),+ REDIRECT,+ )+ [request] = seen+ assert str(request.url) == "https://oauth2.googleapis.com/token"+++def _github_values(key: rsa.RSAPrivateKey) -> AppValues:+ pem = key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode()+ return AppValues(+ "example-client-id",+ {},+ {"client_secret": "example-secret-0000", "private_key": pem},+ )+++def _github(app: tuple[int, object], exchange: object) -> httpx.AsyncClient:+ def handle(request: httpx.Request) -> httpx.Response:+ if request.url.path == "/app":+ return httpx.Response(app[0], json=app[1])+ return httpx.Response(200, json=exchange)++ return httpx.AsyncClient(transport=httpx.MockTransport(handle))+++class TestGitHubApp:+ KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ APP = (200, {"slug": "example-app", "client_id": "example-client-id"})++ async def test_a_right_app_answers_its_slug(self) -> None:+ result = await check_github_app(+ _github(self.APP, {"error": "bad_verification_code"}),+ _github_values(self.KEY),+ )+ assert result.ok+ assert result.settings == {"slug": "example-app"}++ async def test_a_wrong_secret(self) -> None:+ result = await check_github_app(+ _github(self.APP, {"error": "incorrect_client_credentials"}),+ _github_values(self.KEY),+ )+ failure = result.first_failure()+ assert failure is not None and failure.field == "client_secret"++ async def test_a_key_github_refuses(self) -> None:+ result = await check_github_app(+ _github((401, {"message": "no"}), {}), _github_values(self.KEY)+ )+ failure = result.first_failure()+ assert failure is not None and failure.field == "private_key"++ async def test_a_key_of_another_app(self) -> None:+ result = await check_github_app(+ _github((200, {"slug": "other", "client_id": "other-client"}), {}),+ _github_values(self.KEY),+ )+ failure = result.first_failure()+ assert failure is not None and failure.field == "client_id"++ async def test_a_key_too_short_is_refused_before_asking(self) -> None:+ short = rsa.generate_private_key(public_exponent=65537, key_size=1024)+ result = await check_github_app(_github(self.APP, {}), _github_values(short))+ failure = result.first_failure()+ assert failure is not None and "2048" in failure.messagediff --git a/core/tests/switch_core/connections/test_app_credentials.py b/core/tests/switch_core/connections/test_app_credentials.pynew file mode 100644index 000000000..dc5e56bb0--- /dev/null+++ b/core/tests/switch_core/connections/test_app_credentials.py@@ -0,0 +1,381 @@+"""Where each connector's app comes from, and a change taking effect at once."""++from __future__ import annotations++import json+import logging+import uuid+from datetime import timedelta+from pathlib import Path++import httpx+import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ec, rsa+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from starlette.datastructures import State++from switch_core.connections.adapters.github import GitHubAdapter+from switch_core.connections.adapters.oauth import OAuthAdapter+from switch_core.connections.app_credentials import (+ SECRET_NAMES,+ ConnectorApps,+ install_github_app,+)+from switch_core.connections.broker import ServiceBroker+from switch_core.connections.loader import CATALOG+from switch_core.connections.registry import ClientRegistration, ServiceSetupError+from switch_core.db.models import User+from switch_core.db.stores.service_app_credential_store import (+ ServiceAppCredentialStore,+)+from switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore+from switch_core.keys import Keyring+from tests.conftest import TEST_KEYRING+from tests.switch_core.connections.adapters.test_github import _app_files, _config++PUBLIC_URL = "https://switch.example.test"+GOOGLE_VARIABLE = "GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH"+++def _pem(key: rsa.RSAPrivateKey | ec.EllipticCurvePrivateKey) -> str:+ return key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode()+++def _rsa_pem() -> str:+ return _pem(rsa.generate_private_key(public_exponent=65537, key_size=2048))+++def _google_file(tmp_path: Path, client_id: str = "configured-client-id") -> str:+ path = tmp_path / "google.json"+ path.write_text(+ json.dumps({"client_id": client_id, "client_secret": "example-secret-0000"})+ )+ return str(path)+++def _apps(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ environ: dict[str, str] | None = None,+ **config: object,+) -> ConnectorApps:+ settings = _config(**{"gateway_public_url": PUBLIC_URL, **config})+ return ConnectorApps(+ catalog=CATALOG,+ config=settings,+ environ=environ or {},+ session_factory=session_factory,+ store=ServiceAppCredentialStore(TEST_KEYRING),+ http=httpx.AsyncClient(),+ registration=ClientRegistration(+ session_factory=session_factory,+ keyring=TEST_KEYRING,+ public_url=settings.gateway_public_url,+ server_name="switch.local",+ ),+ )+++async def _operator(session_factory: async_sessionmaker[AsyncSession]) -> str:+ async with session_factory() as session:+ user = User(+ name="operator",+ email=f"operator-{uuid.uuid4().hex[:6]}@example.invalid",+ role="admin",+ )+ session.add(user)+ await session.commit()+ return user.id+++async def _save(+ session_factory: async_sessionmaker[AsyncSession],+ service: str,+ *,+ client_id: str,+ secrets: dict[str, str],+ settings: dict[str, str] | None = None,+ keyring: Keyring = TEST_KEYRING,+) -> None:+ operator = await _operator(session_factory)+ kind = "github_app" if service == "github" else "oauth_client"+ async with session_factory() as session:+ await ServiceAppCredentialStore(keyring).save(+ session,+ service=service,+ client_id=client_id,+ settings=settings or {},+ secrets=secrets,+ secret_names=SECRET_NAMES[kind],+ updated_by=operator,+ )+ await session.commit()+++def _broker(session_factory: async_sessionmaker[AsyncSession]) -> ServiceBroker:+ return ServiceBroker(+ session_factory=session_factory,+ keyring=TEST_KEYRING,+ catalog=CATALOG,+ adapters={},+ disabled={},+ store=ServiceConnectionStore(),+ token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,+ )+++class TestSpecs:+ def test_the_catalogs_apps_are_github_and_googles_client(self, session_factory):+ specs = _apps(session_factory).specs+ assert {slug: spec.kind for slug, spec in specs.items()} == {+ "github": "github_app",+ "google-workspace": "oauth_client",+ }+ assert specs["google-workspace"].variables == (GOOGLE_VARIABLE,)+ assert specs["github"].secret_names == {"client_secret", "private_key"}+++class TestPrecedence:+ async def test_nothing_set_is_not_set_up(self, session_factory) -> None:+ apps = _apps(session_factory)+ await apps.load()+ assert apps.effective("google-workspace").source == "none"+ assert apps.github_app() is None+ assert apps.oauth_clients() == {}++ async def test_configuration_is_used_as_it_always_was(+ self, session_factory, tmp_path: Path+ ) -> None:+ apps = _apps(session_factory, environ={GOOGLE_VARIABLE: _google_file(tmp_path)})+ await apps.load()+ effective = apps.effective("google-workspace")+ assert effective.source == "configuration"+ assert effective.configuration_variables == (GOOGLE_VARIABLE,)+ assert effective.saved_ignored is False+ assert apps.oauth_clients()["google-workspace"].client_id == (+ "configured-client-id"+ )++ async def test_configuration_set_but_unusable_stops_the_server(+ self, session_factory, tmp_path: Path+ ) -> None:+ path = tmp_path / "google.json"+ path.write_text("not json")+ apps = _apps(session_factory, environ={GOOGLE_VARIABLE: str(path)})+ with pytest.raises(ServiceSetupError):+ await apps.load()++ async def test_a_saved_client_is_used_when_configuration_is_unset(+ self, session_factory+ ) -> None:+ await _save(+ session_factory,+ "google-workspace",+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ apps = _apps(session_factory)+ await apps.load()+ effective = apps.effective("google-workspace")+ assert effective.source == "saved"+ client = apps.oauth_clients()["google-workspace"]+ assert (client.client_id, client.client_secret) == (+ "saved-client-id",+ "example-secret-1111",+ )++ async def test_configuration_wins_over_a_saved_client_and_says_so(+ self, session_factory, tmp_path: Path, caplog: pytest.LogCaptureFixture+ ) -> None:+ await _save(+ session_factory,+ "google-workspace",+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ apps = _apps(session_factory, environ={GOOGLE_VARIABLE: _google_file(tmp_path)})+ with caplog.at_level(logging.WARNING):+ await apps.load()+ effective = apps.effective("google-workspace")+ assert effective.source == "configuration"+ assert effective.saved_ignored is True+ assert apps.oauth_clients()["google-workspace"].client_id == (+ "configured-client-id"+ )+ assert any(+ GOOGLE_VARIABLE in record.getMessage() and record.levelno == logging.WARNING+ for record in caplog.records+ )++ async def test_the_deprecated_hosted_file_counts_as_configuration(+ self, session_factory, tmp_path: Path+ ) -> None:+ settings, _ = _app_files(tmp_path)+ apps = _apps(session_factory, hosted_github_config_path=settings)+ await apps.load()+ effective = apps.effective("github")+ assert effective.source == "configuration"+ assert effective.deprecated is True+ assert effective.configuration_variables == ("HOSTED_GITHUB_CONFIG_PATH",)+ app = apps.github_app()+ assert app is not None and app.signer is None++ async def test_a_configured_github_app_keeps_its_files_origin(+ self, session_factory, tmp_path: Path+ ) -> None:+ settings, key = _app_files(tmp_path)+ apps = _apps(+ session_factory,+ github_app_config_path=settings,+ github_app_private_key_path=key,+ )+ await apps.load()+ effective = apps.effective("github")+ assert effective.source == "configuration"+ assert effective.configuration_variables == (+ "GITHUB_APP_CONFIG_PATH",+ "GITHUB_APP_PRIVATE_KEY_PATH",+ )+ assert effective.values is not None+ assert effective.values.secrets["private_key"].startswith("-----BEGIN")+ app = apps.github_app()+ assert app is not None+ assert app.connections.origin == "https://switch.example.com"+++class TestSavedGitHubApp:+ async def test_it_is_called_back_at_the_public_url(self, session_factory) -> None:+ await _save(+ session_factory,+ "github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets={"client_secret": "example-secret-0000", "private_key": _rsa_pem()},+ )+ apps = _apps(session_factory)+ await apps.load()+ app = apps.github_app()+ assert app is not None and app.signer is not None+ assert app.connections.callback == (+ f"{PUBLIC_URL}/gateway/provider-connections/github/callback"+ )++ async def test_it_is_not_set_up_without_an_https_public_url(+ self, session_factory+ ) -> None:+ await _save(+ session_factory,+ "github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets={"client_secret": "example-secret-0000", "private_key": _rsa_pem()},+ )+ apps = _apps(session_factory, gateway_public_url="http://switch.example.test")+ await apps.load()+ effective = apps.effective("github")+ assert effective.source == "none"+ assert effective.load_error is not None+ assert "https" in effective.load_error++ async def test_a_key_that_is_not_rsa_leaves_it_not_set_up(+ self, session_factory, caplog: pytest.LogCaptureFixture+ ) -> None:+ await _save(+ session_factory,+ "github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets={+ "client_secret": "example-secret-0000",+ "private_key": _pem(ec.generate_private_key(ec.SECP256R1())),+ },+ )+ apps = _apps(session_factory)+ with caplog.at_level(logging.ERROR):+ await apps.load()+ effective = apps.effective("github")+ assert effective.source == "none"+ assert effective.load_error is not None and "RSA" in effective.load_error+ assert effective.unreadable is False+ assert any(record.levelno == logging.ERROR for record in caplog.records)++ async def test_a_row_no_key_opens_is_unreadable(self, session_factory) -> None:+ retired = Keyring.parse("retired:" + "r" * 40, legacy_secret=None)+ await _save(+ session_factory,+ "google-workspace",+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ keyring=retired,+ )+ apps = _apps(session_factory)+ await apps.load()+ effective = apps.effective("google-workspace")+ assert effective.source == "none"+ assert effective.unreadable is True+++class TestApply:+ async def test_a_saved_client_is_in_use_at_once(self, session_factory) -> None:+ apps = _apps(session_factory)+ await apps.load()+ broker = _broker(session_factory)+ assert broker.connectable("google-workspace") is False++ await _save(+ session_factory,+ "google-workspace",+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ await apps.apply("google-workspace", broker=broker, state=State())++ assert broker.connectable("google-workspace") is True+ _, adapter = broker.sign_in("google-workspace")+ assert isinstance(adapter, OAuthAdapter)++ async with session_factory() as session:+ await apps.store.remove(session, "google-workspace")+ await session.commit()+ await apps.apply("google-workspace", broker=broker, state=State())+ assert broker.connectable("google-workspace") is False++ async def test_the_saved_github_app_is_swapped_in_place(+ self, session_factory+ ) -> None:+ await _save(+ session_factory,+ "github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets={"client_secret": "example-secret-0000", "private_key": _rsa_pem()},+ )+ apps = _apps(session_factory)+ await apps.load()+ state = State()+ install_github_app(state, apps.github_app())+ before = state.github_connections++ await _save(+ session_factory,+ "github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets={"client_secret": "example-secret-1111"},+ )+ broker = _broker(session_factory)+ await apps.apply("github", broker=broker, state=state)++ after = state.github_connections+ assert after is not before+ assert after.client_secret == "example-secret-1111"+ assert state.github_app.connections is after+ assert isinstance(broker._adapters["github"], GitHubAdapter)diff --git a/core/tests/switch_core/connections/test_app_signals.py b/core/tests/switch_core/connections/test_app_signals.pynew file mode 100644index 000000000..cd50874ef--- /dev/null+++ b/core/tests/switch_core/connections/test_app_signals.py@@ -0,0 +1,169 @@+"""A connector app saved or removed in one process is put to work in every one.++Two "processes" on one database, each with its own `ConnectorApps`, broker,+gateway state and signal bus: a save announced by one has to reach the+other's broker, which only the signal and the re-read of the row can do. A+process that missed the signal finds the change on its re-check.+"""++from __future__ import annotations++import asyncio+import uuid+from collections.abc import AsyncIterator, Callable+from dataclasses import dataclass++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import NullPool+from starlette.datastructures import State++from switch_core.connections.app_credentials import ConnectorApps+from switch_core.connections.app_signals import (+ CONNECTOR_APP_CHANGED_SIGNAL,+ ConnectorAppSignals,+)+from switch_core.connections.broker import ServiceBroker+from switch_core.signals import SignalBus+from tests.switch_core.connections.test_app_credentials import _apps, _broker, _save++DELIVERY_TIMEOUT = 10.0+GOOGLE = "google-workspace"+++@dataclass+class _Process:+ apps: ConnectorApps+ broker: ServiceBroker+ state: State+ bus: SignalBus+ signals: ConnectorAppSignals+++def _bus(+ postgres_url: str, session_factory: async_sessionmaker[AsyncSession]+) -> SignalBus:+ return SignalBus(+ session_factory,+ lambda: create_async_engine(postgres_url, poolclass=NullPool),+ process_id=str(uuid.uuid4()),+ )+++async def _process(+ postgres_url: str, session_factory: async_sessionmaker[AsyncSession]+) -> _Process:+ apps = _apps(session_factory)+ await apps.load()+ broker = _broker(session_factory)+ state = State()+ bus = _bus(postgres_url, session_factory)+ signals = ConnectorAppSignals(apps=apps, broker=broker, state=state, bus=bus)+ return _Process(apps, broker, state, bus, signals)+++async def _eventually(check: Callable[[], bool]) -> None:+ async with asyncio.timeout(DELIVERY_TIMEOUT):+ while not check():+ await asyncio.sleep(0.02)+++async def two_processes(+ postgres_url: str, session_factory: async_sessionmaker[AsyncSession]+) -> AsyncIterator[tuple[_Process, _Process]]:+ processes = [await _process(postgres_url, session_factory) for _ in range(2)]+ for process in processes:+ await process.bus.start()+ for process in processes:+ await asyncio.wait_for(process.bus.connected.wait(), DELIVERY_TIMEOUT)+ yield processes[0], processes[1]+ for process in processes:+ await process.bus.stop()+++class TestAcrossProcesses:+ async def test_a_client_saved_in_one_process_is_in_use_in_the_other(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ two_processes: tuple[_Process, _Process],+ ) -> None:+ here, there = two_processes+ assert there.broker.connectable(GOOGLE) is False++ # As the save route does: commit, apply here, announce.+ await _save(+ session_factory,+ GOOGLE,+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ await here.apps.apply(GOOGLE, broker=here.broker, state=here.state)+ here.apps.announce(GOOGLE)++ await _eventually(lambda: there.broker.connectable(GOOGLE))+ assert there.apps.effective(GOOGLE).values.client_id == "saved-client-id" # type: ignore[union-attr]++ async def test_a_client_removed_in_one_process_goes_from_the_other(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ two_processes: tuple[_Process, _Process],+ ) -> None:+ here, there = two_processes+ await _save(+ session_factory,+ GOOGLE,+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ for process in (here, there):+ await process.apps.apply(GOOGLE, broker=process.broker, state=process.state)+ assert there.broker.connectable(GOOGLE) is True++ async with session_factory() as session:+ await here.apps.store.remove(session, GOOGLE)+ await session.commit()+ await here.apps.apply(GOOGLE, broker=here.broker, state=here.state)+ here.apps.announce(GOOGLE)++ await _eventually(lambda: not there.broker.connectable(GOOGLE))+++class TestRecheck:+ async def test_a_missed_signal_is_made_up_by_the_recheck(+ self,+ postgres_url: str,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ process = await _process(postgres_url, session_factory)+ assert await process.apps.changed_since_resolved() == []++ # Saved by another process whose signal never arrived.+ await _save(+ session_factory,+ GOOGLE,+ client_id="saved-client-id",+ secrets={"client_secret": "example-secret-1111"},+ )+ assert await process.apps.changed_since_resolved() == [GOOGLE]++ await process.bus.start()+ try:+ await process.signals.recheck()+ await _eventually(lambda: process.broker.connectable(GOOGLE))+ finally:+ await process.bus.stop()+ assert await process.apps.changed_since_resolved() == []++ async def test_a_signal_for_a_service_this_build_has_no_app_for_is_ignored(+ self,+ postgres_url: str,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ process = await _process(postgres_url, session_factory)++ process.signals._on_changed(+ {"kind": CONNECTOR_APP_CHANGED_SIGNAL, "service": "not-a-service"}+ )++ assert process.signals._owed.pending == 0diff --git a/core/tests/switch_core/connections/test_broker.py b/core/tests/switch_core/connections/test_broker.pyindex aa50b2536..af6045579 100644--- a/core/tests/switch_core/connections/test_broker.py+++ b/core/tests/switch_core/connections/test_broker.py@@ -28,6 +28,8 @@ from switch_core.connections.adapters import (ServiceAdapterError,)from switch_core.connections.broker import (+ CLIENT_REPLACED,+ CONNECTOR_REVOKED,Principal,ServiceBroker,ServiceError,@@ -46,6 +48,7 @@ from switch_core.db.models import (User,)from switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.observability.metrics import MetricsRegistry, install, uninstallfrom tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.fake_vendor import FakeVendor@@ -77,6 +80,8 @@ def broker(disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)@@ -136,6 +141,7 @@ async def _connect(encrypted_secret=TEST_KEYRING.encrypt(json.dumps(_secret(expires_in=expires_in))),+ oauth_client_id=None,)@@ -447,6 +453,8 @@ class TestChecks:disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)world = await _world(session_factory)refused = await _refused(broker, session_factory, world.agent.id)@@ -731,6 +739,8 @@ class TestConnectOnly:disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)world = await _world(session_factory, expires_in=60)@@ -802,6 +812,8 @@ def _switched_off(disabled=disabled,store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)@@ -848,6 +860,7 @@ class TestSwitchedOff:account_id="1001",external_identity="ada-gh",secret=ConnectionSecret(_secret(expires_in=3600)),+ oauth_client_id=None,)assert (caught.value.status_code, caught.value.message) == (403, reason)@@ -913,6 +926,8 @@ async def _pass_through(disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)async with session_factory() as session:owner = await _user(session, "ada")@@ -934,6 +949,7 @@ async def _pass_through(})),+ oauth_client_id=None,)grant = await STORE.save_grant(session,@@ -1160,3 +1176,425 @@ class TestPassThrough:await maintain_once(session_factory, pt.broker, prune=False)assert pt.vendor.revoked == []assert pt.vendor.connections_revoked == []+++def _workspace_refusal(name: str) -> str:+ return (+ f"{name} is not enabled in this workspace. Ask a workspace admin; they "+ "switch it on under Connectors in Switch Console."+ )+++class Gated:+ """A broker with the workspace switch wired, over the shipped catalog and+ `example`, a pass-through OAuth vendor. Ada owns `builder`, connected to+ GitHub and `example` and granted both."""++ def __init__(+ self,+ broker: ServiceBroker,+ github: FakeVendor,+ example: FakeVendor,+ world: World,+ ) -> None:+ self.broker = broker+ self.github = github+ self.example = example+ self.world = world+++async def _gated(+ session_factory: async_sessionmaker[AsyncSession],+ root: Path,+ *,+ gate: bool,+ disabled: dict[str, str] | None = None,+) -> Gated:+ github = FakeVendor()+ example = FakeVendor()+ example.pass_through = True+ example.revocable = False+ broker = ServiceBroker(+ session_factory=session_factory,+ keyring=TEST_KEYRING,+ catalog=pass_through_catalog(root),+ adapters={"github": github, "example": example},+ disabled=disabled or {},+ store=STORE,+ token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=gate,+ )+ world = await _world(session_factory)+ async with session_factory() as session:+ await STORE.save_connection(+ session,+ user_id=world.owner.id,+ service="example",+ consent="write",+ granted_scopes=["read:items", "write:items"],+ account_id="acct-1",+ external_identity="[email protected]",+ encrypted_secret=TEST_KEYRING.encrypt(+ json.dumps(+ {+ "access_token": "owner_access_0",+ "expires_at": time.time() + 50 * 60,+ "refresh_token": "owner_refresh_0",+ }+ )+ ),+ oauth_client_id=None,+ )+ await STORE.save_grant(+ session,+ agent_id=world.agent.id,+ owner_id=world.owner.id,+ service="example",+ access="write",+ tool_mode="deny",+ tools=[],+ resources={},+ account_id="acct-1",+ created_by=world.owner.id,+ )+ await session.commit()+ return Gated(broker, github, example, world)+++async def _switch(+ session_factory: async_sessionmaker[AsyncSession],+ service: str,+ enabled: bool,+ admin_id: str,+) -> None:+ async with session_factory() as session:+ await WorkspaceServiceStore().set_enabled(session, service, enabled, admin_id)+ await session.commit()+++async def _issue_github(g: Gated, session_factory) -> None:+ await _issue(g.broker, session_factory, g.world.agent.id)+++async def _set_grant_github(g: Gated, session_factory) -> None:+ async with session_factory() as session:+ agent = await session.get(Agent, g.world.agent.id)+ assert agent is not None+ await g.broker.set_grant(+ session,+ agent=agent,+ actor_id=g.world.owner.id,+ service="github",+ access="read",+ tool_mode=None,+ tools=None,+ resources=RESOURCES,+ )+++NEW_GITHUB_SIGN_IN = {**_secret(expires_in=3600), "access_token": "gho_access_new"}+NEW_EXAMPLE_SIGN_IN = {+ "access_token": "owner_access_new",+ "expires_at": time.time() + 3600,+ "refresh_token": "owner_refresh_new",+}+DATADOG_KEY = {"api_key": "k", "application_key": "a", "site": "datadoghq.eu"}+++async def _connect_github(g: Gated, session_factory) -> None:+ async with session_factory() as session:+ await g.broker.connect(+ session,+ user_id=g.world.owner.id,+ service="github",+ consent="write",+ granted_scopes=[],+ account_id="1001",+ external_identity="ada-gh",+ secret=ConnectionSecret(dict(NEW_GITHUB_SIGN_IN)),+ oauth_client_id=None,+ )+++async def _connect_key(g: Gated, session_factory) -> None:+ async with session_factory() as session:+ await g.broker.connect(+ session,+ user_id=g.world.owner.id,+ service="datadog",+ consent="write",+ granted_scopes=[],+ account_id="dd-org",+ external_identity="Key · datadoghq.eu",+ secret=ConnectionSecret(dict(DATADOG_KEY)),+ oauth_client_id=None,+ )+++async def _relink_oauth(g: Gated, session_factory) -> None:+ async with session_factory() as session:+ await g.broker.connect(+ session,+ user_id=g.world.owner.id,+ service="example",+ consent="write",+ granted_scopes=["read:items", "write:items"],+ account_id="acct-1",+ external_identity="[email protected]",+ secret=ConnectionSecret(dict(NEW_EXAMPLE_SIGN_IN)),+ oauth_client_id=None,+ )+++# Each entry point, the service it acts on, and that service's name.+ENTRY_POINTS = {+ "issue": (_issue_github, "github", "GitHub"),+ "set_grant": (_set_grant_github, "github", "GitHub"),+ "connect_github": (_connect_github, "github", "GitHub"),+ "connect_key": (_connect_key, "datadog", "Datadog"),+ "relink_oauth": (_relink_oauth, "example", "Example"),+}+++class TestWorkspaceSwitch:+ @pytest.mark.parametrize("entry_point", sorted(ENTRY_POINTS))+ @pytest.mark.parametrize(+ ("gate", "row"),+ [(False, False), (True, True), (True, None)],+ ids=["gate_off_row_off", "gate_on_enabled", "gate_on_no_row"],+ )+ async def test_allowed(+ self, session_factory, tmp_path, entry_point, gate, row+ ) -> None:+ call, service, _ = ENTRY_POINTS[entry_point]+ g = await _gated(session_factory, tmp_path / "c", gate=gate)+ if row is not None:+ await _switch(session_factory, service, row, g.world.owner.id)+ await call(g, session_factory)++ @pytest.mark.parametrize("entry_point", sorted(ENTRY_POINTS))+ async def test_switched_off_in_the_workspace_is_refused_naming_who_and_where(+ self, session_factory, tmp_path, entry_point+ ) -> None:+ call, service, name = ENTRY_POINTS[entry_point]+ g = await _gated(session_factory, tmp_path / "c", gate=True)+ await _switch(session_factory, service, False, g.world.owner.id)+ before = await _all_connections(session_factory)++ with pytest.raises(ServiceError) as caught:+ await call(g, session_factory)++ refused = caught.value+ assert (refused.status_code, refused.code, refused.retryable) == (+ 403,+ "forbidden",+ False,+ )+ assert refused.message == _workspace_refusal(name)+ assert g.github.issued == [] and g.github.refreshes == 0+ assert g.github.checked == []+ assert await _all_connections(session_factory) == before++ @pytest.mark.parametrize("entry_point", sorted(ENTRY_POINTS))+ async def test_the_servers_own_reason_is_checked_first(+ self, session_factory, tmp_path, entry_point+ ) -> None:+ call, service, _ = ENTRY_POINTS[entry_point]+ g = await _gated(+ session_factory,+ tmp_path / "c",+ gate=True,+ disabled={service: "Maintenance"},+ )+ await _switch(session_factory, service, True, g.world.owner.id)+ with pytest.raises(ServiceError) as caught:+ await call(g, session_factory)+ assert caught.value.message == "Maintenance"+ # A grant reads the server's switch as unavailable, as it always has.+ assert caught.value.status_code == (422 if entry_point == "set_grant" else 403)++ async def test_a_new_sign_in_refused_by_the_workspace_is_revoked_at_the_vendor(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=True)+ await _switch(session_factory, "example", False, g.world.owner.id)+ with pytest.raises(ServiceError):+ await _relink_oauth(g, session_factory)+ assert [secret.values for secret in g.example.connections_revoked] == [+ NEW_EXAMPLE_SIGN_IN+ ]++ await _switch(session_factory, "github", False, g.world.owner.id)+ with pytest.raises(ServiceError):+ await _connect_github(g, session_factory)+ assert [secret.access_token for secret in g.github.connections_revoked] == [+ "gho_access_new"+ ]++ async def test_a_key_refused_by_the_workspace_is_not_stored(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=True)+ await _switch(session_factory, "datadog", False, g.world.owner.id)+ with pytest.raises(ServiceError) as caught:+ await _connect_key(g, session_factory)+ assert caught.value.message == _workspace_refusal("Datadog")+ assert "datadog" not in {+ service for service, _, _ in await _all_connections(session_factory)+ }++ async def test_switching_off_keeps_the_grant_and_switching_on_restores_it(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=True)+ await _switch(session_factory, "github", False, g.world.owner.id)++ refused = await _refused(g.broker, session_factory, g.world.agent.id)+ assert (refused.status_code, refused.code) == (403, "forbidden")+ async with session_factory() as session:+ grant = await STORE.get_grant(session, g.world.agent.id, "github")+ assert grant is not None+ assert (grant.id, grant.revision) == (g.world.grant.id, g.world.grant.revision)++ await _switch(session_factory, "github", True, g.world.owner.id)+ token = await _issue(g.broker, session_factory, g.world.agent.id)+ assert token.grant_revision == g.world.grant.revision++ async def test_a_switched_off_service_drops_out_of_the_sessions_grants(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=True)++ async def listed() -> list[str]:+ async with session_factory() as session:+ agent = await session.get(Agent, g.world.agent.id)+ assert agent is not None+ grants = await g.broker.grants_for(+ session, agent, Principal.agent_key()+ )+ return sorted(grant["service"] for grant in grants)++ assert await listed() == ["example", "github"]+ await _switch(session_factory, "example", False, g.world.owner.id)+ assert await listed() == ["github"]+ await _switch(session_factory, "example", True, g.world.owner.id)+ assert await listed() == ["example", "github"]++ async def test_with_the_gate_off_a_row_changes_nothing(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=False)+ await _switch(session_factory, "example", False, g.world.owner.id)+ async with session_factory() as session:+ agent = await session.get(Agent, g.world.agent.id)+ assert agent is not None+ grants = await g.broker.grants_for(session, agent, Principal.agent_key())+ assert await g.broker.workspace_disabled(session) == set()+ assert sorted(grant["service"] for grant in grants) == ["example", "github"]++ async def test_disconnecting_a_service_switched_off_still_works(+ self, session_factory, tmp_path+ ) -> None:+ g = await _gated(session_factory, tmp_path / "c", gate=True)+ await _switch(session_factory, "github", False, g.world.owner.id)+ async with session_factory() as session:+ await g.broker.disconnect(session, g.world.owner.id, "github")+ assert await _connection(session_factory, g.world.owner.id) is None+ assert len(g.github.connections_revoked) == 1+++async def _all_connections(+ session_factory: async_sessionmaker[AsyncSession],+) -> list[tuple[str, str, str]]:+ async with session_factory() as session:+ rows = await session.scalars(+ select(ServiceConnection).order_by(ServiceConnection.service)+ )+ return [(row.service, row.account_id, row.encrypted_secret) for row in rows]+++class TestReplacedClient:+ async def _recorded(+ self, session_factory: async_sessionmaker[AsyncSession], world: World, client+ ) -> None:+ async with session_factory() as session:+ await session.execute(+ update(ServiceConnection)+ .where(ServiceConnection.user_id == world.owner.id)+ .values(oauth_client_id=client)+ )+ await session.commit()++ async def test_a_connection_through_a_replaced_client_must_reconnect(+ self, broker, session_factory, vendor+ ) -> None:+ """Told at once, with no vendor call: a refresh token the old client+ issued is no use to the new one."""+ world = await _world(session_factory, expires_in=60)+ await self._recorded(session_factory, world, "old-client")+ vendor.client_id = "new-client"++ 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 vendor.refreshes == 0 and vendor.issued == []+ connection = await _connection(session_factory, world.owner.id)+ assert connection is not None+ assert (connection.status, connection.error_code) == (+ "needs_reauthorization",+ CLIENT_REPLACED,+ )++ async def test_the_same_client_issues_as_before(+ self, broker, session_factory, vendor+ ) -> None:+ world = await _world(session_factory)+ await self._recorded(session_factory, world, "example-client")+ vendor.client_id = "example-client"++ token = await _issue(broker, session_factory, world.agent.id)+ assert token.resources == RESOURCES++ async def test_a_disconnect_after_the_app_is_removed_says_why_nothing_was_revoked(+ self, broker, session_factory, vendor+ ) -> None:+ world = await _world(session_factory)+ broker.replace_adapter("github", None)+ 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 "+ "the sign-in. Revoke it at GitHub."+ )+ assert vendor.connections_revoked == []+ assert await _connection(session_factory, world.owner.id) is None++ async def test_a_vendor_that_answers_badly_keeps_the_general_warning(+ self, broker, session_factory, vendor+ ) -> None:+ world = await _world(session_factory)++ async def refused(secret: object) -> None:+ raise ServiceAdapterError("GitHub answered 500.")++ vendor.revoke_connection = refused # type: ignore[method-assign]+ async with session_factory() as session:+ warning = await broker.disconnect(session, world.owner.id, "github")+ assert warning == (+ "GitHub could not revoke the sign-in. Revoke it in your GitHub settings."+ )++ async def test_an_unrecorded_client_keeps_todays_behaviour(+ self, broker, session_factory, vendor+ ) -> None:+ world = await _world(session_factory)+ await self._recorded(session_factory, world, None)+ vendor.client_id = "new-client"++ token = await _issue(broker, session_factory, world.agent.id)+ assert token.resources == RESOURCES+ connection = await _connection(session_factory, world.owner.id)+ assert connection is not None+ assert broker.client_replaced(connection) is Falsediff --git a/core/tests/switch_core/connections/test_registry.py b/core/tests/switch_core/connections/test_registry.pyindex ae244c4ea..143cf1cbe 100644--- a/core/tests/switch_core/connections/test_registry.py+++ b/core/tests/switch_core/connections/test_registry.py@@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import async_sessionmakerfrom switch_core.connections.adapters.api_key import ApiKeyAdapterfrom switch_core.connections.adapters.github import GitHubAdapter, load_github_app-from switch_core.connections.adapters.oauth import OAuthAdapter+from switch_core.connections.adapters.oauth import OAuthAdapter, OAuthClientCredentialsfrom switch_core.connections.broker import ServiceBrokerfrom switch_core.connections.loader import CATALOG, CATALOG_ROOT, load_catalogfrom switch_core.connections.oauth_clients import RegisteredClient@@ -24,6 +24,7 @@ from switch_core.connections.registry import (load_client_settings,)from switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.adapters.test_github import _app_files, _configfrom tests.switch_core.connections.test_loader import (@@ -58,7 +59,7 @@ def test_github_gets_its_adapter_where_the_app_is_set_up(tmp_path: Path) -> None_config(github_app_config_path=settings, github_app_private_key_path=key))adapters = build_adapters(- CATALOG, github_app=app, environ={}, http=HTTP, registration=REG+ CATALOG, github_app=app, oauth_clients={}, http=HTTP, registration=REG)assert set(adapters) == {"github", "atlassian", "datadog"}assert isinstance(adapters["github"], GitHubAdapter)@@ -67,21 +68,21 @@ def test_github_gets_its_adapter_where_the_app_is_set_up(tmp_path: Path) -> Nonedef test_github_without_the_app_is_left_not_set_up() -> None:adapters = build_adapters(- CATALOG, github_app=None, environ={}, http=HTTP, registration=REG+ CATALOG, github_app=None, oauth_clients={}, http=HTTP, registration=REG)assert "github" not in adaptersdef test_a_key_service_needs_nothing_set_up_on_the_server() -> None:adapters = build_adapters(- CATALOG, github_app=None, environ={}, http=HTTP, registration=REG+ CATALOG, github_app=None, oauth_clients={}, http=HTTP, registration=REG)assert isinstance(adapters["datadog"], ApiKeyAdapter)def test_atlassian_needs_no_settings_and_registers_its_ports_and_scopes() -> None:adapters = build_adapters(- CATALOG, github_app=None, environ={}, http=HTTP, registration=REG+ CATALOG, github_app=None, oauth_clients={}, http=HTTP, registration=REG)adapter = adapters["atlassian"]assert isinstance(adapter, OAuthAdapter)@@ -100,12 +101,10 @@ def test_atlassian_needs_no_settings_and_registers_its_ports_and_scopes() -> Nondef test_a_static_oauth_client_gets_the_generic_adapter(tmp_path: Path) -> None:- path = tmp_path / "client.json"- path.write_text(json.dumps({"client_id": "c", "client_secret": "SYNTHETIC"}))adapters = build_adapters(_catalog(tmp_path, STATIC),github_app=None,- environ={"EXAMPLE_CLIENT_CONFIG_PATH": str(path)},+ oauth_clients={"example": OAuthClientCredentials("c", "SYNTHETIC")},http=HTTP,registration=REG,)@@ -113,19 +112,17 @@ def test_a_static_oauth_client_gets_the_generic_adapter(tmp_path: Path) -> None:def test_a_cli_entry_gets_the_generic_adapter_with_its_client(tmp_path: Path) -> None:- path = tmp_path / "client.json"- path.write_text(json.dumps({"client_id": "c", "client_secret": "SYNTHETIC"}))catalog = _catalog(tmp_path, CLI_ENTRY)adapters = build_adapters(catalog,github_app=None,- environ={"EXAMPLE_CLIENT_CONFIG_PATH": str(path)},+ oauth_clients={"example": OAuthClientCredentials("c", "SYNTHETIC")},http=HTTP,registration=REG,)assert isinstance(adapters["example"], OAuthAdapter)assert "example" not in build_adapters(- catalog, github_app=None, environ={}, http=HTTP, registration=REG+ catalog, github_app=None, oauth_clients={}, http=HTTP, registration=REG)@@ -135,7 +132,7 @@ def test_a_static_oauth_client_without_settings_is_not_set_up(adapters = build_adapters(_catalog(tmp_path, STATIC),github_app=None,- environ={},+ oauth_clients={},http=HTTP,registration=REG,)@@ -144,7 +141,11 @@ def test_a_static_oauth_client_without_settings_is_not_set_up(def test_a_dynamic_client_is_registered_by_core(tmp_path: Path) -> None:adapters = build_adapters(- _catalog(tmp_path), github_app=None, environ={}, http=HTTP, registration=REG+ _catalog(tmp_path),+ github_app=None,+ oauth_clients={},+ http=HTTP,+ registration=REG,)adapter = adapters["example"]assert isinstance(adapter, OAuthAdapter)@@ -159,41 +160,62 @@ def test_a_core_callback_without_a_public_address_stops_the_server(build_adapters(_catalog(tmp_path, core_only),github_app=None,- environ={},+ oauth_clients={},http=HTTP,registration=REG,)-def test_an_entry_not_set_up_here_shows_its_catalog_note(- tmp_path: Path, session_factory-) -> None:- root = tmp_path / "catalog"- shutil.copytree(CATALOG_ROOT, root)- _write_example(- root,- OAUTH_ENTRY.replace(- " registration: dynamic\n",- " registration: static\n"- " client_settings: EXAMPLE\n"- " setup_note: Its operator registers an Example app; see the docs.\n",- ),- )- broker = ServiceBroker(+def _broker(catalog: dict, session_factory, adapters: dict) -> ServiceBroker:+ return ServiceBroker(session_factory=session_factory,keyring=TEST_KEYRING,- catalog=load_catalog(root),- adapters={},+ catalog=catalog,+ adapters=adapters,disabled={},store=ServiceConnectionStore(),token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)- assert broker.availability("example") == (- "Not set up on this server. Its operator registers an Example app; see the docs."+++def test_an_app_not_set_up_here_says_who_sets_it_up(+ tmp_path: Path, session_factory+) -> None:+ broker = _broker(_catalog(tmp_path, STATIC), session_factory, {})+ reason = (+ "{} is not set up on this server. Ask whoever runs your Switch server "+ "to add it under Connectors in the Switch dashboard.")+ assert broker.availability("example") == reason.format("Example")+ assert broker.availability("github") == reason.format("GitHub")assert broker.connectable("example") is False+def test_a_replaced_adapter_is_used_at_once(tmp_path: Path, session_factory) -> None:+ catalog = _catalog(tmp_path, STATIC)+ broker = _broker(catalog, session_factory, {})+ adapter = build_adapters(+ catalog,+ github_app=None,+ oauth_clients={"example": OAuthClientCredentials("c", "SYNTHETIC")},+ http=HTTP,+ registration=REG,+ )["example"]++ broker.replace_adapter("example", adapter)+ assert broker.availability("example") is None+ assert broker.connectable("example") is True++ broker.replace_adapter("example", None)+ assert broker.availability("example") is not None+ assert broker.connectable("example") is False++ with pytest.raises(ValueError, match="No service named"):+ broker.replace_adapter("nowhere", None)++class TestClientSettings:def test_unset_means_not_set_up(self) -> None:assert load_client_settings("EXAMPLE", {}) is Nonediff --git a/core/tests/switch_core/db/stores/test_service_app_credential_store.py b/core/tests/switch_core/db/stores/test_service_app_credential_store.pynew file mode 100644index 000000000..99945dfe3--- /dev/null+++ b/core/tests/switch_core/db/stores/test_service_app_credential_store.py@@ -0,0 +1,221 @@+"""The operator's connector apps, stored encrypted, against Postgres."""++from __future__ import annotations++import asyncio+import json+import uuid++import pytest+from sqlalchemy import text+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import ServiceAppCredential, User+from switch_core.db.stores.service_app_credential_store import (+ MissingSecretsError,+ ServiceAppCredentialStore,+)+from switch_core.keys import Keyring, UndecryptableError+from tests.conftest import TEST_KEYRING++STORE = ServiceAppCredentialStore(TEST_KEYRING)+GITHUB_SECRETS = frozenset({"client_secret", "private_key"})+++async def _user(session_factory: async_sessionmaker[AsyncSession], name: str) -> str:+ async with session_factory() as session:+ user = User(+ name=name,+ email=f"{name}-{uuid.uuid4().hex[:6]}@example.invalid",+ role="admin",+ )+ session.add(user)+ await session.commit()+ return user.id+++async def _save(+ session: AsyncSession, operator: str, secrets: dict[str, str]+) -> ServiceAppCredential:+ return await STORE.save(+ session,+ service="github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets=secrets,+ secret_names=GITHUB_SECRETS,+ updated_by=operator,+ )+++class TestSave:+ async def test_a_first_save_stores_the_secrets_encrypted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ async with session_factory() as session:+ await _save(+ session,+ operator,+ {"client_secret": "example-secret-0000", "private_key": "pem-0000"},+ )+ await session.commit()+ raw = await session.scalar(+ text(+ "SELECT encrypted_secrets FROM service_app_credentials "+ "WHERE service = 'github'"+ )+ )+ row = await STORE.get(session, "github")++ assert isinstance(raw, str) and "example-secret-0000" not in raw+ assert row is not None+ assert row.client_id == "example-client-id"+ assert row.settings == {"slug": "example-app"}+ assert row.updated_by == operator+ assert STORE.secrets(row) == {+ "client_secret": "example-secret-0000",+ "private_key": "pem-0000",+ }++ async def test_a_first_save_needs_every_secret(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ async with session_factory() as session:+ with pytest.raises(MissingSecretsError) as refused:+ await _save(session, operator, {"client_secret": "example-secret-0000"})+ assert refused.value.names == ["private_key"]++ async def test_a_secret_the_kind_lacks_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ async with session_factory() as session:+ with pytest.raises(ValueError, match="no secret named"):+ await _save(+ session,+ operator,+ {+ "client_secret": "example-secret-0000",+ "private_key": "pem-0000",+ "certificate": "nope",+ },+ )++ async def test_a_partial_save_keeps_the_other_secret(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ first = await _user(session_factory, "first")+ second = await _user(session_factory, "second")+ async with session_factory() as session:+ await _save(+ session,+ first,+ {"client_secret": "example-secret-0000", "private_key": "pem-0000"},+ )+ await session.commit()+ row = await _save(session, second, {"client_secret": "example-secret-1111"})+ await session.commit()++ assert row.updated_by == second+ assert STORE.secrets(row) == {+ "client_secret": "example-secret-1111",+ "private_key": "pem-0000",+ }++ async def test_two_partial_saves_at_once_both_land(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ async with session_factory() as session:+ await _save(+ session,+ operator,+ {"client_secret": "example-secret-0000", "private_key": "pem-0000"},+ )+ await session.commit()++ async def save(secrets: dict[str, str]) -> None:+ async with session_factory() as session:+ await _save(session, operator, secrets)+ # Hold the lock long enough for the other save to queue on it.+ await asyncio.sleep(0.1)+ await session.commit()++ await asyncio.gather(+ save({"client_secret": "example-secret-1111"}),+ save({"private_key": "pem-1111"}),+ )++ async with session_factory() as session:+ row = await STORE.get(session, "github")+ assert row is not None+ assert STORE.secrets(row) == {+ "client_secret": "example-secret-1111",+ "private_key": "pem-1111",+ }++ async def test_every_secret_replaces_one_no_key_opens(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ retired = Keyring.parse("retired:" + "r" * 40, legacy_secret=None)+ async with session_factory() as session:+ session.add(+ ServiceAppCredential(+ service="github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ encrypted_secrets=retired.encrypt(+ json.dumps({"client_secret": "x"})+ ),+ updated_by=operator,+ )+ )+ await session.commit()++ with pytest.raises(UndecryptableError):+ await _save(session, operator, {"client_secret": "example-secret-1111"})+ await session.rollback()++ row = await _save(+ session,+ operator,+ {"client_secret": "example-secret-1111", "private_key": "pem-1111"},+ )+ await session.commit()+ assert STORE.secrets(row)["client_secret"] == "example-secret-1111"++ async def test_updated_by_is_required(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(IntegrityError):+ await _save(+ session,+ "no-such-user",+ {"client_secret": "example-secret-0000", "private_key": "pem"},+ )+++class TestRemove:+ async def test_remove_returns_the_row_and_leaves_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator = await _user(session_factory, "operator")+ async with session_factory() as session:+ await _save(+ session,+ operator,+ {"client_secret": "example-secret-0000", "private_key": "pem-0000"},+ )+ await session.commit()++ removed = await STORE.remove(session, "github")+ await session.commit()+ assert removed is not None and removed.client_id == "example-client-id"+ assert await STORE.get(session, "github") is None+ assert await STORE.list_all(session) == {}+ assert await STORE.remove(session, "github") is Nonediff --git a/core/tests/switch_core/db/stores/test_service_connection_store.py b/core/tests/switch_core/db/stores/test_service_connection_store.pyindex cadde781a..3a899475e 100644--- a/core/tests/switch_core/db/stores/test_service_connection_store.py+++ b/core/tests/switch_core/db/stores/test_service_connection_store.py@@ -72,6 +72,7 @@ async def _connect(account_id=account_id,external_identity=f"login-{account_id}",encrypted_secret=TEST_KEYRING.encrypt(json.dumps(secret or SECRET)),+ oauth_client_id=None,)diff --git a/core/tests/switch_core/db/test_key_rotation.py b/core/tests/switch_core/db/test_key_rotation.pyindex be155a2a4..732369ae2 100644--- a/core/tests/switch_core/db/test_key_rotation.py+++ b/core/tests/switch_core/db/test_key_rotation.py@@ -27,6 +27,7 @@ from switch_core.db.models import (Client,CollaborationBridge,MessagingInstall,+ ServiceAppCredential,ServiceConnection,ServiceTokenIssuance,Tenant,@@ -260,6 +261,56 @@ async def test_the_deployments_registered_clients_end_up_under_the_current_key(assert _NEW.decrypt(secret) == '{"client_id": "registered-1"}'+async def test_the_operators_connector_apps_end_up_under_the_current_key(+ rls_harness: RLSHarness,+) -> None:+ """An app the operator entered from the dashboard belongs to no tenant,+ and is rewritten once by the global pass."""+ _, operator = await _tenant_with_user(rls_harness.owner)+ async with rls_harness.owner() as session:+ session.add(+ ServiceAppCredential(+ service="google-workspace",+ client_id="example-client-id",+ settings={},+ encrypted_secrets=_legacy_encrypt('{"client_secret": "example"}'),+ updated_by=operator,+ )+ )+ await session.commit()++ await reencrypt_stored_secrets(rls_harness.restricted, _NEW, [])++ secret = await _raw_where(+ rls_harness.owner,+ "SELECT encrypted_secrets FROM service_app_credentials WHERE service = :service",+ {"service": "google-workspace"},+ )+ assert isinstance(secret, str) and secret.startswith(_NEW.current_prefix())+ assert _NEW.decrypt(secret) == '{"client_secret": "example"}'+++async def test_a_connector_app_no_key_opens_stops_the_boot(+ rls_harness: RLSHarness,+) -> None:+ _, operator = await _tenant_with_user(rls_harness.owner)+ async with rls_harness.owner() as session:+ session.add(+ ServiceAppCredential(+ service="google-workspace",+ client_id="example-client-id",+ settings={},+ encrypted_secrets=_OLD.encrypt('{"client_secret": "example"}'),+ updated_by=operator,+ )+ )+ await session.commit()++ too_early = Keyring.parse("new:" + "n" * 40, legacy_secret=None)+ with pytest.raises(UndecryptableError):+ await reencrypt_stored_secrets(rls_harness.restricted, too_early, [])++async def test_a_value_no_key_opens_stops_the_boot(rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/core/tests/switch_core/db/test_server_audit_events.py b/core/tests/switch_core/db/test_server_audit_events.pynew file mode 100644index 000000000..96a7e50f4--- /dev/null+++ b/core/tests/switch_core/db/test_server_audit_events.py@@ -0,0 +1,79 @@+"""The server's own audit log: recorded in the caller's transaction, and+append-only for the role the server connects as."""++from __future__ import annotations++import pytest+from sqlalchemy import select, text+from sqlalchemy.exc import ProgrammingError++from switch_core.db.audit import ServerAuditAction, record_server_audit_event+from switch_core.db.models import ServerAuditEvent+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++async def _seed(rls_harness: RLSHarness) -> None:+ async with rls_harness.restricted() as session:+ await record_server_audit_event(+ session,+ actor_user_id="operator-1",+ action=ServerAuditAction.CONNECTOR_APP_SAVED,+ target_type="service",+ target_id="github",+ details={"service": "github", "fields_changed": ["client_secret"]},+ )+ await session.commit()+++async def test_the_runtime_role_records_with_no_tenant_bound(+ rls_harness: RLSHarness,+) -> None:+ await _seed(rls_harness)++ async with rls_harness.restricted() as session:+ [event] = (await session.execute(select(ServerAuditEvent))).scalars().all()+ assert event.action == ServerAuditAction.CONNECTOR_APP_SAVED+ assert event.actor_user_id == "operator-1"+ assert event.target_id == "github"+ assert event.details == {"service": "github", "fields_changed": ["client_secret"]}+++async def test_a_change_that_rolls_back_leaves_no_event(+ rls_harness: RLSHarness,+) -> None:+ async with rls_harness.restricted() as session:+ await record_server_audit_event(+ session,+ actor_user_id="operator-1",+ action=ServerAuditAction.CONNECTOR_APP_REMOVED,+ target_type="service",+ target_id="github",+ details=None,+ )+ await session.rollback()++ async with rls_harness.owner() as session:+ assert (await session.execute(select(ServerAuditEvent))).scalars().all() == []+++ "statement",+ [+ "UPDATE server_audit_events SET action = 'rewritten'",+ "DELETE FROM server_audit_events",+ ],+)+async def test_the_runtime_role_cannot_rewrite_history(+ rls_harness: RLSHarness, statement: str+) -> None:+ await _seed(rls_harness)++ async with rls_harness.restricted() as session:+ with pytest.raises(ProgrammingError, match="permission denied"):+ await session.execute(text(statement))++ async with rls_harness.owner() as session:+ [event] = (await session.execute(select(ServerAuditEvent))).scalars().all()+ assert event.action == ServerAuditAction.CONNECTOR_APP_SAVEDdiff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 2e834c873..8acae20bd 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -66,6 +66,11 @@ _ALLOWED_MODULES = {# then bind each tenant and work under its own policy, the same shape as# session-activity upkeep above."switch_core.connections.maintenance",+ # The operator's Connectors page counts who is connected through each+ # app, and who would have to reconnect if it were replaced, across every+ # workspace: enumerate, then read each one's connections under its own+ # policy, the same shape as service-token upkeep above.+ "switch_core.gateway.connector_apps",# The runtime-state sweep reads every tenant's stale rows, one tenant at a# time; `register_agent_with_token` resolves a registration credential by# its globally unique hash, which is the read that produces a tenant.@@ -234,6 +239,11 @@ _RAW_SESSION_FACTORY_MODULES = {# tenant's: read and written in a session bound to none, and re-encrypted# once at boot by the global pass above."switch_core.connections.oauth_clients",+ # The apps the operator registered at connectors' vendors+ # (`service_app_credentials`, in `rls_ddl.GLOBAL_TABLES`): one per+ # deployment and service, shared by every tenant's sign-ins, so read at+ # boot and after the operator changes one, in a session bound to none.+ "switch_core.connections.app_credentials",}# Calls that end in `session_factory` but hand one back rather than open adiff --git a/core/tests/switch_core/db/test_tenant_schema_catalogue.py b/core/tests/switch_core/db/test_tenant_schema_catalogue.pyindex 1c97afe1f..a1660190d 100644--- a/core/tests/switch_core/db/test_tenant_schema_catalogue.py+++ b/core/tests/switch_core/db/test_tenant_schema_catalogue.py@@ -126,6 +126,13 @@ class TestEveryTableIsScopedUnlessItIsNamedGlobal:# Which schema revisions a release from before them can still# serve on, as Alembic applied them: a fact about the schema."schema_expand_only_revisions",+ # The app the operator registered at a vendor and entered from the+ # dashboard: one per deployment and service, as above. A+ # workspace's own app would be a new scoped table.+ "service_app_credentials",+ # Changes to the server as a whole, such as setting up one of those+ # apps: no tenant owns them, so `audit_events` cannot hold them.+ "server_audit_events",}async def test_scoped_is_everything_else(self) -> None:diff --git a/core/tests/switch_core/db/test_workspace_service_store.py b/core/tests/switch_core/db/test_workspace_service_store.pynew file mode 100644index 000000000..b60c704da--- /dev/null+++ b/core/tests/switch_core/db/test_workspace_service_store.py@@ -0,0 +1,102 @@+"""A workspace admin's switch per service, against Postgres.++No row means on. The isolation test writes through the restricted role the+server connects as, so a missing policy fails it rather than being bypassed+by the superuser's exemption.+"""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy import select, text+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Tenant, User, WorkspaceServiceSetting+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore+from tests.conftest import RLSHarness++STORE = WorkspaceServiceStore()+++async def _user(session_factory: async_sessionmaker[AsyncSession], name: str) -> str:+ async with session_factory() as session:+ user = User(+ name=name,+ email=f"{name}-{uuid.uuid4().hex[:6]}@example.invalid",+ role="user",+ )+ session.add(user)+ await session.commit()+ return user.id+++class TestSwitch:+ async def test_with_no_row_every_service_is_on(self, session_factory) -> None:+ async with session_factory() as session:+ assert await STORE.is_enabled(session, "datadog") is True+ assert await STORE.disabled_services(session) == set()+ assert await STORE.list_settings(session) == {}++ async def test_off_then_on_round_trips(self, session_factory) -> None:+ admin = await _user(session_factory, "admin")+ async with session_factory() as session:+ await STORE.set_enabled(session, "datadog", False, admin)+ await session.commit()+ assert await STORE.is_enabled(session, "datadog") is False+ assert await STORE.is_enabled(session, "atlassian") is True+ assert await STORE.disabled_services(session) == {"datadog"}++ await STORE.set_enabled(session, "datadog", True, admin)+ await session.commit()+ assert await STORE.is_enabled(session, "datadog") is True+ assert await STORE.disabled_services(session) == set()++ async def test_the_same_switch_twice_is_one_row_naming_the_last_admin(+ self, session_factory+ ) -> None:+ first = await _user(session_factory, "first")+ second = await _user(session_factory, "second")+ async with session_factory() as session:+ await STORE.set_enabled(session, "github", False, first)+ await session.commit()+ before = (await STORE.list_settings(session))["github"].updated_at+ await STORE.set_enabled(session, "github", False, second)+ await session.commit()+ rows = list(await session.scalars(select(WorkspaceServiceSetting)))+ assert [(row.service, row.enabled, row.updated_by) for row in rows] == [+ ("github", False, second)+ ]+ assert rows[0].updated_at >= before++[email protected]_ambient_tenant+class TestIsolation:+ async def test_a_row_written_in_one_workspace_is_invisible_from_another(+ self, rls_harness: RLSHarness+ ) -> None:+ mine = f"tenant-{uuid.uuid4().hex[:8]}"+ theirs = f"tenant-{uuid.uuid4().hex[:8]}"+ async with rls_harness.owner() as session:+ for tenant_id in (mine, theirs):+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+ admin = await _user(rls_harness.owner, "admin")++ async with tenant_session(rls_harness.restricted, mine) as session:+ await STORE.set_enabled(session, "datadog", False, admin)+ await session.commit()++ async with tenant_session(rls_harness.restricted, theirs) as session:+ # Unfiltered, so only the policy stands between this read and the row.+ raw = await session.execute(+ text("SELECT service FROM workspace_service_settings")+ )+ assert raw.all() == []+ assert await STORE.is_enabled(session, "datadog") is True+ assert await STORE.disabled_services(session) == set()++ async with tenant_session(rls_harness.restricted, mine) as session:+ assert await STORE.disabled_services(session) == {"datadog"}diff --git a/core/tests/switch_core/gateway/test_app_route_mounting.py b/core/tests/switch_core/gateway/test_app_route_mounting.pyindex 45fe998f8..b119e19ae 100644--- a/core/tests/switch_core/gateway/test_app_route_mounting.py+++ b/core/tests/switch_core/gateway/test_app_route_mounting.py@@ -42,6 +42,7 @@ def _app(**overrides: object) -> object:protocol=MagicMock(),install_service=None,invite_mailer=None,+ connector_apps=MagicMock(**{"github_app.return_value": None}),config=config,)@@ -70,6 +71,11 @@ SERVICE_ROUTES = {"/service-connections/{service}/key","/agents/{agent_id}/service-grants","/service-connections/{service}/flows",+ "/service-connections/{service}/agents",+ "/workspace/services",+ "/workspace/services/{service}",+ "/connector-apps",+ "/connector-apps/{service}",}diff --git a/core/tests/switch_core/gateway/test_connection_catalog.py b/core/tests/switch_core/gateway/test_connection_catalog.pyindex e3ba6bdfa..4f20627ad 100644--- a/core/tests/switch_core/gateway/test_connection_catalog.py+++ b/core/tests/switch_core/gateway/test_connection_catalog.py@@ -68,6 +68,7 @@ async def link_github(session_factory, user_id):encrypted_secret=TEST_KEYRING.encrypt(json.dumps({"access_token": "SYNTHETIC"})),+ oauth_client_id=None,)await session.commit()diff --git a/core/tests/switch_core/gateway/test_connector_apps.py b/core/tests/switch_core/gateway/test_connector_apps.pynew file mode 100644index 000000000..eacbe0c55--- /dev/null+++ b/core/tests/switch_core/gateway/test_connector_apps.py@@ -0,0 +1,756 @@+"""The operator's connector-app routes, against Postgres and fake vendors.++Only the server's operator reaches them; a save is checked with the vendor+and stored only when the vendor accepts it; it is in use at once; and no+secret leaves in a response, an audit row or a log line beyond its last four+characters.+"""++from __future__ import annotations++import json+import logging+import secrets+import uuid+from datetime import timedelta+from pathlib import Path+from urllib.parse import parse_qs++import httpx+import jwt+import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.connections.app_credentials import (+ GITHUB_NEEDS_HTTPS,+ ConnectorApps,+)+from switch_core.connections.broker import ServiceBroker+from switch_core.connections.flows import ServiceFlows+from switch_core.connections.loader import CATALOG+from switch_core.connections.registry import ClientRegistration, build_adapters+from switch_core.connections.sign_in_flows import SignInFlows+from switch_core.db.models import (+ ServerAuditEvent,+ ServiceAppCredential,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.service_app_credential_store import (+ ServiceAppCredentialStore,+)+from switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore+from switch_core.gateway.connector_apps import router as connector_apps_router+from switch_core.gateway.service_connections import (+ router as service_connections_router,+)+from switch_core.gateway.service_flows import router as service_flows_router+from tests.conftest import TEST_KEYRING+from tests.switch_core.connections.adapters.test_github import _config+from tests.switch_core.connections.fake_vendor import (+ STATIC_CLIENT_ID,+ STATIC_CLIENT_SECRET,+ FakeGoogle,+)+from tests.switch_core.management.harness import Harness, build_harness, cookies_for++PUBLIC = "https://switch.example.com"+HTTP_PUBLIC = "http://switch.example.com"+APPS = "/gateway/connector-apps"+GOOGLE = "google-workspace"+GITHUB_CLIENT_ID = "example-github-client-id"+GITHUB_SECRET = "example-github-secret-0000"+++class FakeGitHub:+ """GitHub's App side: `GET /app` with the App's JWT, and the code+ exchange that tells a right client secret from a wrong one."""++ def __init__(self) -> None:+ self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ self.client_id = GITHUB_CLIENT_ID+ self.client_secret = GITHUB_SECRET++ def pem(self, key: rsa.RSAPrivateKey | None = None) -> str:+ return (+ (key or self.key)+ .private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+ .decode()+ )++ def handle(self, request: httpx.Request) -> httpx.Response:+ if request.url.path == "/app" and request.method == "GET":+ token = request.headers.get("authorization", "").removeprefix("Bearer ")+ try:+ claims = jwt.decode(token, self.key.public_key(), algorithms=["RS256"])+ except jwt.InvalidTokenError:+ return httpx.Response(+ 401, json={"message": "A JSON web token could not be decoded"}+ )+ if claims.get("iss") != self.client_id:+ return httpx.Response(401, json={"message": "Integration not found"})+ return httpx.Response(+ 200, json={"slug": "example-app", "client_id": self.client_id}+ )+ if request.url.path == "/login/oauth/access_token":+ form = {k: v[0] for k, v in parse_qs(request.content.decode()).items()}+ if (form.get("client_id"), form.get("client_secret")) == (+ self.client_id,+ self.client_secret,+ ):+ return httpx.Response(200, json={"error": "bad_verification_code"})+ return httpx.Response(200, json={"error": "incorrect_client_credentials"})+ return httpx.Response(404)+++class World:+ def __init__(+ self, session_factory: async_sessionmaker[AsyncSession], public_url: str+ ) -> None:+ self.google = FakeGoogle()+ self.github = FakeGitHub()+ self.unreachable = False+ self.vendor_calls: list[str] = []+ self.public_url = public_url+ # Settings beyond the public URL, such as a configured GitHub App.+ self.config: dict[str, object] = {}+ self.harness: Harness = build_harness(session_factory)+ self.session_factory = session_factory++ def handle(self, request: httpx.Request) -> httpx.Response:+ self.vendor_calls.append(str(request.url))+ if self.unreachable:+ raise httpx.ConnectError("unreachable", request=request)+ if request.url.host in ("api.github.com", "github.com"):+ return self.github.handle(request)+ return self.google.handle(request)++ async def install(self, environ: dict[str, str] | None = None) -> ConnectorApps:+ http = httpx.AsyncClient(transport=httpx.MockTransport(self.handle))+ registration = ClientRegistration(+ session_factory=self.session_factory,+ keyring=TEST_KEYRING,+ public_url=self.public_url,+ server_name="switch.example.com",+ )+ apps = ConnectorApps(+ catalog=CATALOG,+ config=_config(gateway_public_url=self.public_url, **self.config),+ environ=environ or {},+ session_factory=self.session_factory,+ store=ServiceAppCredentialStore(TEST_KEYRING),+ http=http,+ registration=registration,+ )+ await apps.load()+ broker = ServiceBroker(+ session_factory=self.session_factory,+ keyring=TEST_KEYRING,+ catalog=CATALOG,+ adapters=build_adapters(+ CATALOG,+ github_app=apps.github_app(),+ oauth_clients=apps.oauth_clients(),+ http=http,+ registration=registration,+ ),+ disabled={},+ store=ServiceConnectionStore(),+ token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,+ )+ app = self.harness.gateway_app+ app.state.service_broker = broker+ app.state.connector_apps = apps+ app.state.github_connections = None+ app.state.service_flows = ServiceFlows(+ self.public_url, SignInFlows(self.session_factory, TEST_KEYRING)+ )+ app.include_router(connector_apps_router)+ app.include_router(service_connections_router)+ app.include_router(service_flows_router)+ return apps+++async def _user(+ session_factory: async_sessionmaker[AsyncSession],+ name: str,+ *,+ role: str = "user",+ member_role: str = "member",+ tenant_id: str = "default",+) -> User:+ async with session_factory() as session:+ user = User(+ name=name, email=f"{name}-{uuid.uuid4().hex[:6]}@example.invalid", role=role+ )+ session.add(user)+ await session.flush()+ session.add(+ TenantMember(+ tenant_id=await _tenant_id(session, tenant_id),+ user_id=user.id,+ role=member_role,+ )+ )+ await session.commit()+ return user+++async def _tenant_id(session: AsyncSession, slug: str) -> str:+ tenant = await session.scalar(select(Tenant).where(Tenant.slug == slug))+ if tenant is None:+ tenant = Tenant(id=f"tenant-{slug}", slug=slug, name=slug)+ session.add(tenant)+ await session.flush()+ return tenant.id+++def _google_body(**overrides: object) -> dict[str, object]:+ return {+ "client_id": STATIC_CLIENT_ID,+ "client_secret": STATIC_CLIENT_SECRET,+ "replace": False,+ **overrides,+ }+++async def _rows(session_factory) -> list[ServiceAppCredential]:+ async with session_factory() as session:+ return list(await session.scalars(select(ServiceAppCredential)))+++async def _audit(session_factory) -> list[ServerAuditEvent]:+ async with session_factory() as session:+ return list(+ await session.scalars(+ select(ServerAuditEvent).order_by(ServerAuditEvent.occurred_at)+ )+ )+++async def world(session_factory) -> World:+ return World(session_factory, PUBLIC)+++async def http_world(session_factory) -> World:+ return World(session_factory, HTTP_PUBLIC)+++async def operator(session_factory) -> User:+ return await _user(session_factory, "operator", role="admin")+++class TestOnlyTheOperator:+ @pytest.mark.parametrize("member_role", ["member", "admin", "owner"])+ async def test_everyone_else_is_refused_on_every_route(+ self, world: World, session_factory, member_role: str+ ) -> None:+ await world.install()+ someone = await _user(session_factory, "someone", member_role=member_role)+ async with world.harness.client() as client:+ cookies = cookies_for(someone)+ answers = [+ await client.get(APPS, cookies=cookies),+ await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies+ ),+ await client.post(f"{APPS}/{GOOGLE}/import", cookies=cookies),+ await client.post(f"{APPS}/{GOOGLE}/check", cookies=cookies),+ await client.get(+ f"{APPS}/{GOOGLE}/impact",+ params={"client_id": "x"},+ cookies=cookies,+ ),+ await client.delete(f"{APPS}/{GOOGLE}", cookies=cookies),+ ]+ assert [answer.status_code for answer in answers] == [403] * 6+ assert await _rows(session_factory) == []++ async def test_the_operator_reads_every_app(self, world: World, operator) -> None:+ await world.install()+ async with world.harness.client() as client:+ listed = await client.get(APPS, cookies=cookies_for(operator))+ assert listed.status_code == 200, listed.text+ body = listed.json()+ assert body["public_url"] == PUBLIC+ apps = {entry["slug"]: entry for entry in body["apps"]}+ assert set(apps) == {"github", GOOGLE}+ assert apps[GOOGLE]["source"] == "none"+ assert apps[GOOGLE]["redirect_uri"] == (+ f"{PUBLIC}/gateway/service-connections/{GOOGLE}/flows/callback"+ )+ assert apps["github"]["redirect_uri"] == (+ f"{PUBLIC}/gateway/provider-connections/github/callback"+ )+ assert [entry["slug"] for entry in body["registered"]] == ["atlassian"]++ async def test_an_unknown_service_is_not_found(+ self, world: World, operator+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/datadog", json=_google_body(), cookies=cookies_for(operator)+ )+ assert answer.status_code == 404+++class TestSaving:+ async def test_a_checked_client_is_saved_audited_and_in_use_at_once(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ port = secrets.token_urlsafe(32)+ start = {"port": 43123, "state": port, "completion_secret": "c" * 43}+ before = await client.post(+ f"/gateway/service-connections/{GOOGLE}/flows",+ json=start,+ cookies=cookies,+ )+ saved = await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies+ )+ after = await client.post(+ f"/gateway/service-connections/{GOOGLE}/flows",+ json={**start, "state": secrets.token_urlsafe(32)},+ cookies=cookies,+ )+ assert before.status_code == 503+ assert saved.status_code == 200, saved.text+ entry = saved.json()+ assert entry["source"] == "saved"+ assert entry["client_id"] == STATIC_CLIENT_ID+ assert entry["secrets"]["client_secret"] == {+ "set": True,+ "last4": STATIC_CLIENT_SECRET[-4:],+ }+ assert entry["updated_by_name"] == "operator"+ assert after.status_code == 200, after.text+ [event] = await _audit(session_factory)+ assert event.action == "connector_app.saved"+ assert event.actor_user_id == operator.id+ assert event.details == {+ "service": GOOGLE,+ "fields_changed": ["client_id", "client_secret"],+ "client_id": STATIC_CLIENT_ID,+ }++ async def test_the_first_save_needs_every_secret(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/{GOOGLE}",+ json=_google_body(client_secret=None),+ cookies=cookies_for(operator),+ )+ assert answer.status_code == 422+ assert answer.json()["detail"] == "Enter the client secret."+ assert await _rows(session_factory) == []++ async def test_a_refusal_stores_nothing(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/{GOOGLE}",+ json=_google_body(client_secret="example-wrong-secret"),+ cookies=cookies_for(operator),+ )+ assert answer.status_code == 422+ assert answer.json()["field"] == "client_secret"+ assert "doesn't recognise this client ID and secret" in answer.json()["detail"]+ assert await _rows(session_factory) == []+ assert await _audit(session_factory) == []++ async def test_an_unreachable_vendor_stores_nothing(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ world.unreachable = True+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies_for(operator)+ )+ assert answer.status_code == 503+ assert answer.json()["detail"] == "Couldn't reach Google Workspace. Try again."+ assert await _rows(session_factory) == []++ async def test_another_client_id_needs_replace(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ assert (+ await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies+ )+ ).status_code == 200+ world.google.client_id = "another-client-id"+ refused = await client.put(+ f"{APPS}/{GOOGLE}",+ json=_google_body(client_id="another-client-id"),+ cookies=cookies,+ )+ switched = await client.put(+ f"{APPS}/{GOOGLE}",+ json=_google_body(client_id="another-client-id", replace=True),+ cookies=cookies,+ )+ assert refused.status_code == 409+ assert "different app" in refused.json()["detail"]+ assert switched.status_code == 200, switched.text+ [row] = await _rows(session_factory)+ assert row.client_id == "another-client-id"+ events = await _audit(session_factory)+ assert events[-1].details["previous_client_id"] == STATIC_CLIENT_ID++ async def test_saving_is_refused_while_configuration_is_set(+ self, world: World, operator, session_factory, tmp_path: Path+ ) -> None:+ path = tmp_path / "google.json"+ path.write_text(+ json.dumps(+ {"client_id": STATIC_CLIENT_ID, "client_secret": STATIC_CLIENT_SECRET}+ )+ )+ await world.install({"GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH": str(path)})+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies_for(operator)+ )+ assert answer.status_code == 409+ assert answer.json()["detail"] == (+ "GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH is set, so Switch uses that. Copy "+ "it into Switch, then unset it and restart."+ )+ assert await _rows(session_factory) == []+++class TestGitHub:+ async def test_the_slug_comes_from_github_and_a_partial_save_keeps_the_key(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ first = await client.put(+ f"{APPS}/github",+ json={+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": GITHUB_SECRET,+ "private_key": world.github.pem(),+ "replace": False,+ },+ cookies=cookies,+ )+ world.github.client_secret = "example-github-secret-1111"+ rotated = await client.put(+ f"{APPS}/github",+ json={+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": "example-github-secret-1111",+ "replace": False,+ },+ cookies=cookies,+ )+ assert first.status_code == 200, first.text+ entry = first.json()+ assert entry["fields"] == {"slug": "example-app"}+ assert entry["install_url"] == (+ "https://github.com/apps/example-app/installations/new"+ )+ assert entry["secrets"]["private_key"]["fingerprint"].startswith("SHA256:")+ assert rotated.status_code == 200, rotated.text+ assert (+ rotated.json()["secrets"]["private_key"] == entry["secrets"]["private_key"]+ )+ app = world.harness.gateway_app.state.github_connections+ assert app.client_secret == "example-github-secret-1111"+ events = await _audit(session_factory)+ assert events[-1].details["fields_changed"] == ["client_secret"]++ async def test_a_key_of_another_app_is_refused(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ other = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ async with world.harness.client() as client:+ answer = await client.put(+ f"{APPS}/github",+ json={+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": GITHUB_SECRET,+ "private_key": world.github.pem(other),+ "replace": False,+ },+ cookies=cookies_for(operator),+ )+ assert answer.status_code == 422+ assert answer.json()["field"] == "private_key"+ assert await _rows(session_factory) == []+++class TestGitHubNeedsHttps:+ def _body(self, world: World) -> dict[str, object]:+ return {+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": GITHUB_SECRET,+ "private_key": world.github.pem(),+ "replace": False,+ }++ async def test_the_list_says_why_github_cannot_be_set_up(+ self, http_world: World, operator+ ) -> None:+ await http_world.install()+ async with http_world.harness.client() as client:+ listed = await client.get(APPS, cookies=cookies_for(operator))+ assert listed.status_code == 200, listed.text+ body = listed.json()+ assert body["public_url"] == HTTP_PUBLIC+ apps = {entry["slug"]: entry for entry in body["apps"]}+ assert apps["github"]["setup_blocked"] == GITHUB_NEEDS_HTTPS+ assert apps["github"]["redirect_uri"] is None+ assert apps[GOOGLE]["setup_blocked"] is None+ assert apps[GOOGLE]["redirect_uri"] == (+ f"{HTTP_PUBLIC}/gateway/service-connections/{GOOGLE}/flows/callback"+ )++ async def test_saving_and_checking_github_are_refused_before_github_is_asked(+ self, http_world: World, operator, session_factory+ ) -> None:+ await http_world.install()+ async with http_world.harness.client() as client:+ cookies = cookies_for(operator)+ saved = await client.put(+ f"{APPS}/github", json=self._body(http_world), cookies=cookies+ )+ checked = await client.post(f"{APPS}/github/check", cookies=cookies)+ for answer in (saved, checked):+ assert answer.status_code == 409, answer.text+ assert answer.json()["detail"] == GITHUB_NEEDS_HTTPS+ assert http_world.vendor_calls == []+ assert await _rows(session_factory) == []+ assert await _audit(session_factory) == []++ async def test_a_configured_github_app_is_checked_but_not_copied_in(+ self, http_world: World, operator, session_factory, tmp_path: Path+ ) -> None:+ config = tmp_path / "github.json"+ config.write_text(+ json.dumps(+ {+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": GITHUB_SECRET,+ "slug": "example-app",+ "origin": PUBLIC,+ }+ )+ )+ key = tmp_path / "github.pem"+ key.write_text(http_world.github.pem())+ http_world.config = {+ "github_app_config_path": str(config),+ "github_app_private_key_path": str(key),+ }+ apps = await http_world.install()+ assert apps.effective("github").source == "configuration"+ async with http_world.harness.client() as client:+ cookies = cookies_for(operator)+ copied = await client.post(f"{APPS}/github/import", cookies=cookies)+ checked = await client.post(f"{APPS}/github/check", cookies=cookies)+ assert copied.status_code == 409, copied.text+ assert copied.json()["detail"] == GITHUB_NEEDS_HTTPS+ assert await _rows(session_factory) == []+ assert checked.status_code == 200, checked.text+ assert checked.json()["ok"] is True++ async def test_google_is_set_up_as_before(+ self, http_world: World, operator, session_factory+ ) -> None:+ await http_world.install()+ async with http_world.harness.client() as client:+ saved = await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies_for(operator)+ )+ assert saved.status_code == 200, saved.text+ assert saved.json()["setup_blocked"] is None+ assert len(await _rows(session_factory)) == 1+++class TestImportAndRemove:+ async def test_copying_configuration_in_needs_nothing_retyped(+ self, world: World, operator, session_factory, tmp_path: Path+ ) -> None:+ path = tmp_path / "google.json"+ path.write_text(+ json.dumps(+ {"client_id": STATIC_CLIENT_ID, "client_secret": STATIC_CLIENT_SECRET}+ )+ )+ apps = await world.install({"GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH": str(path)})+ async with world.harness.client() as client:+ answer = await client.post(+ f"{APPS}/{GOOGLE}/import", cookies=cookies_for(operator)+ )+ again = await client.post(+ f"{APPS}/github/import", cookies=cookies_for(operator)+ )+ assert answer.status_code == 200, answer.text+ assert answer.json()["source"] == "configuration"+ assert answer.json()["saved_ignored"] is True+ assert again.status_code == 409+ [row] = await _rows(session_factory)+ assert apps.store.secrets(row) == {"client_secret": STATIC_CLIENT_SECRET}+ [event] = await _audit(session_factory)+ assert event.action == "connector_app.imported"+ assert event.details == {+ "service": GOOGLE,+ "client_id": STATIC_CLIENT_ID,+ "source_variables": ["GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH"],+ }++ async def test_removing_leaves_the_service_not_set_up(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ await client.put(f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies)+ removed = await client.delete(f"{APPS}/{GOOGLE}", cookies=cookies)+ listed = await client.get("/gateway/service-connections", cookies=cookies)+ gone = await client.delete(f"{APPS}/{GOOGLE}", cookies=cookies)+ assert removed.status_code == 200, removed.text+ assert removed.json() == {"connected_members": 0, "workspaces": 0}+ assert gone.status_code == 404+ assert await _rows(session_factory) == []+ [google] = [c for c in listed.json()["connections"] if c["slug"] == GOOGLE]+ assert google["server_setup_needed"] is True+ assert google["unavailable_reason"].startswith(+ "Google Workspace is not set up on this server."+ )+ assert [event.action for event in await _audit(session_factory)] == [+ "connector_app.saved",+ "connector_app.removed",+ ]+++class TestCheckAndImpact:+ async def test_checking_the_app_in_use_stores_nothing(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ nothing = await client.post(f"{APPS}/{GOOGLE}/check", cookies=cookies)+ await client.put(f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies)+ world.google.client_secret = "example-rotated-at-google"+ checked = await client.post(f"{APPS}/{GOOGLE}/check", cookies=cookies)+ assert nothing.status_code == 409+ assert checked.status_code == 200+ assert checked.json()["ok"] is False+ assert len(await _audit(session_factory)) == 1++ async def test_the_impact_counts_people_across_workspaces(+ self, world: World, operator, session_factory+ ) -> None:+ await world.install()+ store = ServiceConnectionStore()+ for name, tenant in (("ada", "default"), ("bo", "default"), ("cy", "other")):+ user = await _user(session_factory, name, tenant_id=tenant)+ async with session_factory() as session:+ tenant_id = await _tenant_id(session, tenant)+ async with tenant_session(session_factory, tenant_id) as session:+ await store.save_connection(+ session,+ user_id=user.id,+ service=GOOGLE,+ consent="read",+ granted_scopes=[],+ account_id=f"account-{name}",+ external_identity=f"{name}@example.invalid",+ encrypted_secret=TEST_KEYRING.encrypt("{}"),+ oauth_client_id=STATIC_CLIENT_ID,+ )+ await session.commit()+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ await client.put(f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies)+ other = await client.get(+ f"{APPS}/{GOOGLE}/impact",+ params={"client_id": "another-client-id"},+ cookies=cookies,+ )+ same = await client.get(+ f"{APPS}/{GOOGLE}/impact",+ params={"client_id": STATIC_CLIENT_ID},+ cookies=cookies,+ )+ listed = await client.get(APPS, cookies=cookies)+ assert other.json() == {"connected_members": 3, "workspaces": 2}+ assert same.json() == {"connected_members": 0, "workspaces": 0}+ [google] = [a for a in listed.json()["apps"] if a["slug"] == GOOGLE]+ assert (google["connected_members"], google["workspaces"]) == (3, 2)+ assert google["stale_connections"] == 0+++class TestNoSecretLeaves:+ async def test_not_in_a_response_an_audit_row_or_a_log_line(+ self, world: World, operator, session_factory, caplog+ ) -> None:+ await world.install()+ pem = world.github.pem()+ responses = []+ with caplog.at_level(logging.DEBUG):+ async with world.harness.client() as client:+ cookies = cookies_for(operator)+ responses.append(+ await client.put(+ f"{APPS}/{GOOGLE}", json=_google_body(), cookies=cookies+ )+ )+ responses.append(+ await client.put(+ f"{APPS}/github",+ json={+ "client_id": GITHUB_CLIENT_ID,+ "client_secret": GITHUB_SECRET,+ "private_key": pem,+ "replace": False,+ },+ cookies=cookies,+ )+ )+ responses.append(await client.get(APPS, cookies=cookies))+ responses.append(+ await client.post(f"{APPS}/github/check", cookies=cookies)+ )+ assert all(r.status_code == 200 for r in responses), [r.text for r in responses]+ audit = json.dumps([event.details for event in await _audit(session_factory)])+ logged = "\n".join(record.getMessage() for record in caplog.records)+ key_body = "".join(pem.splitlines()[1:-1])+ for secret in (STATIC_CLIENT_SECRET, GITHUB_SECRET, key_body[:40]):+ for text in [r.text for r in responses] + [audit, logged]:+ assert secret not in text+ assert STATIC_CLIENT_SECRET[-4:] in responses[2].textdiff --git a/core/tests/switch_core/gateway/test_github_connections.py b/core/tests/switch_core/gateway/test_github_connections.pyindex 175683015..65501cfbd 100644--- a/core/tests/switch_core/gateway/test_github_connections.py+++ b/core/tests/switch_core/gateway/test_github_connections.py@@ -24,6 +24,7 @@ from switch_core.db.models import (require_tenant_id,)from switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway.auth import get_current_userfrom switch_core.gateway.dependencies import get_config, get_sessionfrom switch_core.gateway.github_connections import router@@ -36,7 +37,10 @@ TEST_KEYRING = Keyring.parse("test:" + "x" * 40, legacy_secret=None)@pytest.fixture-async def github_app(tmp_path, session_factory):+async def github_app(request, tmp_path, session_factory):+ """The GitHub routes on their own. Parametrize indirectly with True for the+ workspace switch to apply, as the `service_connections` flag makes it."""+ workspace_gate = getattr(request, "param", False)config = tmp_path / "github.json"config.write_text(json.dumps(@@ -48,7 +52,7 @@ async def github_app(tmp_path, session_factory):}))- github = GitHubConnections(str(config))+ github = GitHubConnections.from_file(str(config))github.exchange = AsyncMock(return_value={"access_token": "SYNTHETIC-ACCESS",@@ -89,14 +93,14 @@ async def github_app(tmp_path, session_factory):await session.commit()identity = {"user": user}- app = _process(github, identity, session_factory)+ app = _process(github, identity, session_factory, workspace_gate)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="https://switch.example.com") as client:yield client, github, identity, session_factory-def _process(github, identity, session_factory) -> FastAPI:+def _process(github, identity, session_factory, workspace_gate: bool) -> FastAPI:"""One switch-core process's gateway: its own app, broker and flow store,on the shared database."""@@ -115,6 +119,8 @@ def _process(github, identity, session_factory) -> FastAPI:disabled={},store=ServiceConnectionStore(),token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=workspace_gate,)app.include_router(router, prefix="/gateway")app.dependency_overrides[get_current_user] = lambda: identity["user"]@@ -158,18 +164,10 @@ async def authorize(client):async def relay(client, flow_id):+ """The browser comes back from GitHub and is sent on to Console's listener."""response = await client.get(BASE + "/callback", params={"state": flow_id, "code": "SYNTHETIC-CODE"})- assert response.status_code == 200- assert "Linking GitHub" in response.text- assert (- "form-action 'self' http://127.0.0.1:12345"- in response.headers["content-security-policy"]- )- response = await client.post(- BASE + "/callback", data={"state": flow_id, "code": "SYNTHETIC-CODE"}- )assert response.status_code == 303location = urlsplit(response.headers["location"])assert (location.hostname, location.port, location.path) == (@@ -187,13 +185,7 @@ async def complete(client, flow_id):)-async def confirm(client, flow_id):- return await client.post(- BASE + f"/flows/{flow_id}/confirm", json={"completion_secret": SECRET}- )---async def test_browser_handoff_requires_console_completion_and_saves_encrypted(+async def test_browser_handoff_completes_through_console_and_saves_encrypted(github_app,):client, github, _, factory = github_app@@ -201,14 +193,17 @@ async def test_browser_handoff_requires_console_completion_and_saves_encrypted(await relay(client, flow_id)github.exchange.assert_not_called()assert (await client.get(BASE + f"/flows/{flow_id}")).json()["status"] == "pending"- assert (await confirm(client, flow_id)).status_code == 409- assert (await complete(client, flow_id)).status_code == 204assert (await client.get(BASE)).json()["status"] == "not_connected"+ completed = await complete(client, flow_id)+ assert completed.status_code == 200, completed.text+ assert completed.json() == {"warning": None, "login": "example-user"}+ # The outcome stays readable, without the token, until Console drops it.assert (await client.get(BASE + f"/flows/{flow_id}")).json() == {- "status": "ready",+ "status": "connected","login": "example-user",+ "error": None,+ "warning": None,}- assert (await confirm(client, flow_id)).status_code == 200status = await client.get(BASE)assert (status.json()["installations"][0]["repositories"][0]["name"]@@ -225,7 +220,10 @@ async def test_browser_handoff_requires_console_completion_and_saves_encrypted(json.loads(TEST_KEYRING.decrypt(row.encrypted_secret))["access_token"]== "SYNTHETIC-ACCESS")- assert (await confirm(client, flow_id)).status_code == 410+ flow = await session.scalar(select(SignInFlow).where(SignInFlow.id == flow_id))+ assert flow is not None and flow.encrypted_result is None+ assert (await client.delete(BASE + f"/flows/{flow_id}")).status_code == 204+ assert (await client.get(BASE + f"/flows/{flow_id}")).status_code == 410assert (await client.delete(BASE)).status_code == 200github.revoke.assert_awaited_once_with("SYNTHETIC-ACCESS")assert (await client.get(BASE)).json()["status"] == "not_connected"@@ -249,7 +247,7 @@ async def test_callback_rejects_missing_cookie_and_replayed_completion(github_ap)assert wrong.status_code == 400github.exchange.assert_not_called()- assert (await complete(client, flow_id)).status_code == 204+ assert (await complete(client, flow_id)).status_code == 200assert (await complete(client, flow_id)).status_code == 400assert github.exchange.await_count == 1assert (@@ -294,7 +292,7 @@ async def test_a_flow_keeps_nothing_secret_in_the_clear(github_app):client, _, _, factory = github_appflow_id = await authorize(client)await relay(client, flow_id)- assert (await complete(client, flow_id)).status_code == 204+ assert (await complete(client, flow_id)).status_code == 200async with factory() as session:row = await session.scalar(select(SignInFlow).where(SignInFlow.id == flow_id))assert row is not None@@ -308,30 +306,31 @@ async def test_a_sign_in_started_on_one_process_completes_on_another(github_app,):"""Every request of the sign-in lands on the other process from the one- before: start, the browser's three steps, completion, status and confirm."""+ before: start, the browser's two steps, completion and status."""_, github, identity, factory = github_app- first = _process(github, identity, factory)- second = _process(github, identity, factory)+ first = _process(github, identity, factory, False)+ second = _process(github, identity, factory, False)async with httpx.AsyncClient(transport=_EachRequestToTheNextProcess(first, second),base_url="https://switch.example.com",) as client:flow_id = await authorize(client)await relay(client, flow_id)- assert (await complete(client, flow_id)).status_code == 204+ assert (await complete(client, flow_id)).status_code == 200assert (await client.get(BASE + f"/flows/{flow_id}")).json() == {- "status": "ready",+ "status": "connected","login": "example-user",+ "error": None,+ "warning": None,}- assert (await confirm(client, flow_id)).status_code == 200assert (await client.get(BASE)).json()["login"] == "example-user"github.exchange.assert_awaited_once()async def test_two_processes_racing_to_complete_exchange_the_code_once(github_app):_, github, identity, factory = github_app- first = _process(github, identity, factory)- second = _process(github, identity, factory)+ first = _process(github, identity, factory, False)+ second = _process(github, identity, factory, False)async with httpx.AsyncClient(transport=_EachRequestToTheNextProcess(first, second),base_url="https://switch.example.com",@@ -341,7 +340,7 @@ async def test_two_processes_racing_to_complete_exchange_the_code_once(github_apresults = await asyncio.gather(complete(client, flow_id), complete(client, flow_id))- assert sorted(r.status_code for r in results) == [204, 400]+ assert sorted(r.status_code for r in results) == [200, 400]github.exchange.assert_awaited_once()@@ -351,7 +350,6 @@ async def test_refresh_saved_before_repository_failure(github_app):github.exchange.return_value["expires_at"] = 0await relay(client, flow_id)await complete(client, flow_id)- await confirm(client, flow_id)github.exchange.return_value = {"access_token": "NEW-SYNTHETIC-ACCESS","refresh_token": "NEW-SYNTHETIC-REFRESH",@@ -373,7 +371,6 @@ async def test_failed_authorization_preserves_saved_connection(github_app):flow_id = await authorize(client)await relay(client, flow_id)await complete(client, flow_id)- await confirm(client, flow_id)next_id = await authorize(client)await relay(client, next_id)github.exchange.side_effect = GitHubError("GitHub rejected authorization")@@ -404,8 +401,7 @@ async def test_github_identity_cannot_link_to_another_workspace_user(github_app)client, _, identity, factory = github_appfirst = await authorize(client)await relay(client, first)- assert (await complete(client, first)).status_code == 204- assert (await confirm(client, first)).status_code == 200+ assert (await complete(client, first)).status_code == 200async with factory() as session:other = User(id="other-github-user",@@ -419,10 +415,13 @@ async def test_github_identity_cannot_link_to_another_workspace_user(github_app)identity["user"] = othersecond = await authorize(client)await relay(client, second)- assert (await complete(client, second)).status_code == 204- response = await confirm(client, second)+ response = await complete(client, second)assert response.status_code == 409assert "already linked" in response.json()["detail"]+ assert (+ "already linked"+ in (await client.get(BASE + f"/flows/{second}")).json()["error"]+ )assert response.json()["code"] == "account_linked_elsewhere"assert response.json()["retryable"] is Falseasync with factory() as session:@@ -431,14 +430,15 @@ async def test_github_identity_cannot_link_to_another_workspace_user(github_app)assert rows[0].user_id == "github-user"-async def test_continue_page_reload_and_cancelled_consent(github_app):+async def test_callback_is_taken_once_and_a_cancelled_consent_fails(github_app):client, github, _, _ = github_appflow_id = await authorize(client)- for _ in range(2):- response = await client.get(- BASE + "/callback", params={"state": flow_id, "code": "SYNTHETIC-CODE"}- )- assert response.status_code == 200+ await relay(client, flow_id)+ response = await client.get(+ BASE + "/callback", params={"state": flow_id, "code": "SYNTHETIC-CODE"}+ )+ assert response.status_code == 400+ flow_id = await authorize(client)response = await client.get(BASE + "/callback", params={"state": flow_id, "error": "access_denied"})@@ -453,7 +453,6 @@ async def test_concurrent_refresh_exchanges_once_and_saves_on_cancel(github_app)github.exchange.return_value["expires_at"] = 0await relay(client, flow_id)await complete(client, flow_id)- await confirm(client, flow_id)entered, release = asyncio.Event(), asyncio.Event()async def refresh(data):@@ -495,8 +494,7 @@ async def test_disconnect_finishes_and_warns_when_github_revoke_fails(github_appclient, github, _, factory = github_appflow = await authorize(client)await relay(client, flow)- assert (await complete(client, flow)).status_code == 204- assert (await confirm(client, flow)).status_code == 200+ assert (await complete(client, flow)).status_code == 200github.revoke.side_effect = GitHubError("Synthetic revocation failure")result = await client.delete(BASE)assert result.status_code == 200@@ -510,6 +508,31 @@ async def test_disconnect_finishes_and_warns_when_github_revoke_fails(github_app)+async def test_disconnect_works_once_the_app_is_removed(github_app):+ client, github, _, factory = github_app+ flow = await authorize(client)+ await relay(client, flow)+ assert (await complete(client, flow)).status_code == 200+ # As `install_github_app(state, None)` and the broker leave the server.+ state = client._transport.app.state+ state.github_connections = None+ state.service_broker.replace_adapter("github", None)+ 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 "+ "sign-in. Revoke it at GitHub."+ )+ github.revoke.assert_not_called()+ async with factory() as session:+ assert (+ await session.scalar(+ select(ServiceConnection).where(ServiceConnection.service == "github")+ )+ is None+ )++@pytest.mark.parametrize("status", [204, 404, 422])async def test_oauth_revocation_deletes_only_the_selected_token(github_app, monkeypatch, status@@ -529,8 +552,7 @@ async def test_relink_queues_existing_installation_tokens(github_app, monkeypatcclient, github, identity, factory = github_appfirst = await authorize(client)await relay(client, first)- assert (await complete(client, first)).status_code == 204- assert (await confirm(client, first)).status_code == 200+ assert (await complete(client, first)).status_code == 200async with factory() as session:issued = ServiceTokenIssuance(grant_id="grant",@@ -560,11 +582,101 @@ async def test_relink_queues_existing_installation_tokens(github_app, monkeypatc}second = await authorize(client)await relay(client, second)- assert (await complete(client, second)).status_code == 204- response = await confirm(client, second)+ response = await complete(client, second)assert response.status_code == 200assert response.json()["warning"]github.revoke.assert_awaited_once_with("SYNTHETIC-ACCESS")async with factory() as session:row = await session.get(ServiceTokenIssuance, (require_tenant_id(), issued.id))assert row.revoke_requested and row.encrypted_token is not None+++GITHUB_REFUSAL = {+ "detail": (+ "GitHub is not enabled in this workspace. Ask a workspace admin; they "+ "switch it on under Connectors in Switch Console."+ ),+ "code": "forbidden",+ "retryable": False,+}+++async def _switch_github(factory, user_id: str, enabled: bool) -> None:+ async with factory() as session:+ await WorkspaceServiceStore().set_enabled(session, "github", enabled, user_id)+ await session.commit()+++async def _start(client):+ return await client.post(+ BASE + "/flows",+ json={+ "port": 12345,+ "state": secrets.token_urlsafe(32),+ "completion_secret": SECRET,+ },+ )++[email protected]("github_app", [True], indirect=True)+async def test_start_is_refused_where_the_workspace_switched_github_off(github_app):+ client, github, identity, factory = github_app+ await _switch_github(factory, identity["user"].id, False)+ response = await _start(client)+ assert response.status_code == 403+ assert response.json() == GITHUB_REFUSAL+ async with factory() as session:+ assert await session.scalar(select(SignInFlow)) is None+++async def test_with_the_flag_off_the_workspace_switch_is_ignored(github_app):+ client, _, identity, factory = github_app+ await _switch_github(factory, identity["user"].id, False)+ assert (await _start(client)).status_code == 200++[email protected]("github_app", [True], indirect=True)+async def test_switched_off_mid_flow_the_sign_in_is_revoked_and_not_kept(github_app):+ client, github, identity, factory = github_app+ flow_id = await authorize(client)+ await relay(client, flow_id)+ await _switch_github(factory, identity["user"].id, False)++ response = await complete(client, flow_id)++ assert response.status_code == 403+ assert response.json() == GITHUB_REFUSAL+ github.revoke.assert_awaited_once_with("SYNTHETIC-ACCESS")+ async with factory() as session:+ flow = await session.scalar(select(SignInFlow).where(SignInFlow.id == flow_id))+ assert flow is not None+ assert (flow.status, flow.encrypted_result) == ("failed", None)+ assert flow.error == GITHUB_REFUSAL["detail"]+ assert await session.scalar(select(ServiceConnection)) is None+++async def test_the_connection_records_the_apps_client(github_app):+ client, _, _, factory = github_app+ flow_id = await authorize(client)+ await relay(client, flow_id)+ assert (await complete(client, flow_id)).status_code == 200+ async with factory() as session:+ row = await session.scalar(+ select(ServiceConnection).where(ServiceConnection.service == "github")+ )+ assert row.oauth_client_id == "example-client"+++async def test_an_app_replaced_during_the_sign_in_is_refused(github_app):+ """The sign-in carried over to an App with another client: its code was+ issued to the old one, so it is refused before GitHub is asked."""+ client, github, _, _ = github_app+ flow_id = await authorize(client)+ await relay(client, flow_id)+ github.client_id = "another-client"+ response = await complete(client, flow_id)+ assert response.status_code == 400+ assert response.json()["detail"] == (+ "This server's GitHub App changed during your sign-in. Start it again."+ )+ github.exchange.assert_not_called()diff --git a/core/tests/switch_core/gateway/test_google_workspace.py b/core/tests/switch_core/gateway/test_google_workspace.pyindex 12ba7f62a..05ef46ea4 100644--- a/core/tests/switch_core/gateway/test_google_workspace.py+++ b/core/tests/switch_core/gateway/test_google_workspace.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport jsonimport secretsfrom datetime import timedelta-from pathlib import Pathfrom urllib.parse import parse_qs, urlsplitimport httpx@@ -19,6 +18,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.connections.adapters import ConnectionSecret+from switch_core.connections.adapters.oauth import OAuthAdapter, OAuthClientCredentialsfrom switch_core.connections.broker import Principal, ServiceBrokerfrom switch_core.connections.flows import ServiceFlowsfrom switch_core.connections.loader import CATALOG@@ -27,6 +27,7 @@ from switch_core.connections.registry import ClientRegistration, build_adaptersfrom switch_core.connections.sign_in_flows import SignInFlowsfrom switch_core.db.models import ServiceConnection, Userfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway.service_connections import (router as service_connections_router,)@@ -75,25 +76,19 @@ class World:def _world(session_factory: async_sessionmaker[AsyncSession],- tmp_path: Path,*,client_settings: bool = True,disabled: dict[str, str] | None = None,) -> World:google = FakeGoogle()- environ = {}- if client_settings:- path = tmp_path / "google-client.json"- path.write_text(- json.dumps(- {"client_id": STATIC_CLIENT_ID, "client_secret": STATIC_CLIENT_SECRET}- )- )- environ["GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH"] = str(path)adapters = build_adapters(CATALOG,github_app=None,- environ=environ,+ oauth_clients=(+ {SERVICE: OAuthClientCredentials(STATIC_CLIENT_ID, STATIC_CLIENT_SECRET)}+ if client_settings+ else {}+ ),http=google.client(),registration=ClientRegistration(session_factory=session_factory,@@ -110,6 +105,8 @@ def _world(disabled=disabled or {},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)harness = build_harness(session_factory)harness.gateway_app.state.service_broker = broker@@ -122,7 +119,20 @@ def _world(async def _connect(world: World, client: httpx.AsyncClient, user: User) -> None:- """Switch Console's side and the person's browser, through Core's callback."""+ state, secret, code = await _signed_in(world, client, user)+ completed = await client.post(+ f"{FLOWS}/{state}/complete",+ json={"completion_secret": secret, "code": code},+ cookies=cookies_for(user),+ )+ assert completed.status_code == 200, completed.text+++async def _signed_in(+ world: World, client: httpx.AsyncClient, user: User+) -> tuple[str, str, str]:+ """Switch Console's side and the person's browser, through Core's callback,+ up to Console holding the code: its state, completion secret and code."""state = secrets.token_urlsafe(32)secret = secrets.token_urlsafe(32)started = await client.post(@@ -139,30 +149,15 @@ async def _connect(world: World, client: httpx.AsyncClient, user: User) -> None:back = urlsplit(world.google.authorize(left.headers["location"]))assert f"{back.scheme}://{back.netloc}{back.path}" == f"{PUBLIC}{FLOWS}/callback"code = parse_qs(back.query)["code"][0]- page = await client.get(f"{back.path}?{back.query}", cookies=cookie)- assert page.status_code == 200- relayed = await client.post(- f"{FLOWS}/callback", data={"state": state, "code": code}, cookies=cookie- )- assert relayed.status_code == 303- listener = urlsplit(relayed.headers["location"])+ returned = await client.get(f"{back.path}?{back.query}", cookies=cookie)+ assert returned.status_code == 303+ listener = urlsplit(returned.headers["location"])assert (listener.netloc, listener.path) == (f"127.0.0.1:{PORT}",LOOPBACK_CALLBACK_PATH,)assert parse_qs(listener.query)["code"] == [code]- completed = await client.post(- f"{FLOWS}/{state}/complete",- json={"completion_secret": secret, "code": code},- cookies=cookies_for(user),- )- assert completed.status_code == 204, completed.text- confirmed = await client.post(- f"{FLOWS}/{state}/confirm",- json={"completion_secret": secret},- cookies=cookies_for(user),- )- assert confirmed.status_code == 200, confirmed.text+ return state, secret, codeasync def _connection(@@ -179,11 +174,82 @@ async def _connection(return connection+def _another_client(world: World, session_factory) -> OAuthAdapter:+ adapter = build_adapters(+ CATALOG,+ github_app=None,+ oauth_clients={+ SERVICE: OAuthClientCredentials("other-client-id", "example-secret-1111")+ },+ http=world.google.client(),+ registration=ClientRegistration(+ session_factory=session_factory,+ keyring=TEST_KEYRING,+ public_url=PUBLIC,+ server_name="switch.example.com",+ ),+ )[SERVICE]+ assert isinstance(adapter, OAuthAdapter)+ return adapter+++class TestTheClientSignedInThrough:+ async def test_the_connection_records_it(self, session_factory) -> None:+ world = _world(session_factory)+ ada = await add_member(session_factory, "ada")+ async with world.harness.client() as client:+ await _connect(world, client, ada)+ connection = await _connection(session_factory, ada.id)+ assert connection.oauth_client_id == STATIC_CLIENT_ID++ async def test_a_client_replaced_during_the_sign_in_is_refused(+ self, session_factory+ ) -> None:+ world = _world(session_factory)+ ada = await add_member(session_factory, "ada")+ async with world.harness.client() as client:+ state, secret, code = await _signed_in(world, client, ada)+ world.broker.replace_adapter(+ SERVICE, _another_client(world, session_factory)+ )+ completed = await client.post(+ f"{FLOWS}/{state}/complete",+ json={"completion_secret": secret, "code": code},+ cookies=cookies_for(ada),+ )+ assert completed.status_code == 400+ assert completed.json()["detail"] == (+ "This server's Google Workspace app changed during your sign-in. "+ "Start it again."+ )+ assert [+ request+ for request in world.google.token_requests+ if request.get("grant_type") == "authorization_code"+ ] == []++ async def test_a_replaced_client_shows_the_connection_as_needing_reconnecting(+ self, session_factory+ ) -> None:+ world = _world(session_factory)+ ada = await add_member(session_factory, "ada")+ async with world.harness.client() as client:+ await _connect(world, client, ada)+ world.broker.replace_adapter(+ SERVICE, _another_client(world, session_factory)+ )+ listed = await client.get(+ "/gateway/service-connections", cookies=cookies_for(ada)+ )+ [google] = [c for c in listed.json()["connections"] if c["slug"] == SERVICE]+ assert google["status"] == "needs_reauthorization"++class TestSignIn:async def test_signs_in_offline_through_core_and_keeps_the_refresh_token(- self, session_factory, tmp_path+ self, session_factory) -> None:- world = _world(session_factory, tmp_path)+ world = _world(session_factory)ada = await add_member(session_factory, "ada")async with world.harness.client() as client:await _connect(world, client, ada)@@ -209,9 +275,9 @@ class TestSignIn:assert secret["access_token"] in world.google.live_accessasync def test_a_sign_in_without_the_write_scopes_is_read_only(- self, session_factory, tmp_path+ self, session_factory) -> None:- world = _world(session_factory, tmp_path)+ world = _world(session_factory)world.google.unticked = set(WRITE_ONLY)ada = await add_member(session_factory, "ada")async with world.harness.client() as client:@@ -223,9 +289,9 @@ class TestSignIn:class TestAgents:async def test_a_granted_agent_gets_gws_and_the_owners_token(- self, session_factory, tmp_path+ self, session_factory) -> None:- world = _world(session_factory, tmp_path)+ world = _world(session_factory)ada = await add_member(session_factory, "ada")async with world.harness.client() as client:await _connect(world, client, ada)@@ -263,9 +329,9 @@ class TestAgents:assert issued.token in world.google.live_accessasync def test_a_refresh_keeps_googles_reusable_refresh_token(- self, session_factory, tmp_path+ self, session_factory) -> None:- world = _world(session_factory, tmp_path)+ world = _world(session_factory)ada = await add_member(session_factory, "ada")async with world.harness.client() as client:await _connect(world, client, ada)@@ -279,9 +345,9 @@ class TestAgents:class TestDisconnect:async def test_disconnecting_revokes_the_sign_in_at_google(- self, session_factory, tmp_path+ self, session_factory) -> None:- world = _world(session_factory, tmp_path)+ world = _world(session_factory)ada = await add_member(session_factory, "ada")async with world.harness.client() as client:await _connect(world, client, ada)@@ -304,8 +370,9 @@ class TestAvailability:(False,{},- "Not set up on this server. Its operator registers an internal "- "Google app; see the docs.",+ "Google Workspace is not set up on this server. Ask whoever runs "+ "your Switch server to add it under Connectors in the Switch "+ "dashboard.",),(True,@@ -316,11 +383,10 @@ class TestAvailability:ids=["no-client-settings", "switched-off"],)async def test_says_why_google_workspace_cannot_be_used_here(- self, session_factory, tmp_path, client_settings, disabled, reason+ self, session_factory, client_settings, disabled, reason) -> None:world = _world(session_factory,- tmp_path,client_settings=client_settings,disabled=disabled,)diff --git a/core/tests/switch_core/gateway/test_service_connections.py b/core/tests/switch_core/gateway/test_service_connections.pyindex 63f129b84..7f577fd97 100644--- a/core/tests/switch_core/gateway/test_service_connections.py+++ b/core/tests/switch_core/gateway/test_service_connections.py@@ -17,6 +17,7 @@ from switch_core.addressing import (AddressingPolicy,AddressingRule,owner_and_owner_agents_policy,+ owner_only_policy,)from switch_core.connections.adapters import ServiceAdapterErrorfrom switch_core.connections.broker import ServiceBroker@@ -26,9 +27,11 @@ from switch_core.db.models import (Agent,AuditEvent,ServiceConnection,+ TenantMember,)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.fake_vendor import FakeVendorfrom tests.switch_core.connections.service_harness import (@@ -38,6 +41,7 @@ from tests.switch_core.connections.service_harness import (bound_to,build_service_harness,connect,+ grant_directly,)from tests.switch_core.gateway.test_tenant_api_routes import (TENANT_A,@@ -64,7 +68,7 @@ def vendor() -> FakeVendor:def harness(session_factory: async_sessionmaker[AsyncSession], vendor: FakeVendor) -> Harness:- return build_service_harness(session_factory, vendor)[0]+ return build_service_harness(session_factory, vendor, workspace_gate=False)[0]async def _put(harness: Harness, owner, agent_id: str, body: dict, service="github"):@@ -208,18 +212,19 @@ class TestGrants:@pytest.mark.parametrize(("policy", "warned"),[- (owner_and_owner_agents_policy(), False),+ (owner_only_policy([]), False),+ (owner_and_owner_agents_policy(), True),(AddressingPolicy(rules=[- *owner_and_owner_agents_policy().rules,+ *owner_only_policy([]).rules,AddressingRule(rooms=["room-x"], users="*", agents=[]),]),True,),],- ids=["owner-and-their-agents", "anyone-in-one-room"],+ ids=["owner-alone", "owner-and-their-agents", "anyone-in-one-room"],)async def test_the_warning_follows_who_else_can_address_the_agent(self, harness: Harness, policy: AddressingPolicy, warned: bool@@ -442,6 +447,8 @@ class TestMemberRemoval:disabled={},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)token = _token(admin_id, "[email protected]", TENANT_A)@@ -459,3 +466,175 @@ class TestMemberRemoval:)assert event is not None and event.details is not Noneassert event.details["service_connections_deleted"] == 1+++def gated(+ session_factory: async_sessionmaker[AsyncSession], vendor: FakeVendor+) -> Harness:+ """The harness with the workspace switch applying, as the flag would."""+ return build_service_harness(session_factory, vendor, workspace_gate=True)[0]+++async def _switch_off(harness: Harness, service: str, admin_id: str) -> None:+ async with harness.session_factory() as session:+ await WorkspaceServiceStore().set_enabled(session, service, False, admin_id)+ await session.commit()+++async def _listed(harness: Harness, user) -> dict[str, dict]:+ async with harness.client() as client:+ response = await client.get(+ "/gateway/service-connections", cookies=cookies_for(user)+ )+ assert response.status_code == 200, response.text+ return {entry["slug"]: entry for entry in response.json()["connections"]}+++WORKSPACE_REFUSAL = (+ "GitHub is not enabled in this workspace. Ask a workspace admin; they "+ "switch it on under Connectors in Switch Console."+)+++class TestWorkspaceSwitch:+ async def test_the_list_says_which_services_the_workspace_has_on(+ self, gated: Harness+ ) -> None:+ owner = await add_member(gated.session_factory, "ada")+ await connect(gated.session_factory, owner.id, consent="read")+ await _switch_off(gated, "datadog", owner.id)++ entries = await _listed(gated, owner)++ assert entries["datadog"]["workspace_enabled"] is False+ assert {+ slug for slug, entry in entries.items() if not entry["workspace_enabled"]+ } == {"datadog"}+ assert entries["github"]["consent"] == "read"+ assert entries["atlassian"]["consent"] is None++ async def test_with_the_gate_off_every_service_reads_as_on(+ self, harness: Harness+ ) -> None:+ owner = await add_member(harness.session_factory, "ada")+ await _switch_off(harness, "datadog", owner.id)++ entries = await _listed(harness, owner)++ assert all(entry["workspace_enabled"] is True for entry in entries.values())++ async def test_a_running_sessions_grants_drop_the_service_and_its_token_is_refused(+ self, gated: Harness, vendor: FakeVendor+ ) -> None:+ owner = await add_member(gated.session_factory, "ada")+ agent_id, key = await agent_with_key(gated.session_factory, owner, "builder")+ await connect(gated.session_factory, owner.id)+ await grant_directly(gated.session_factory, agent_id, owner.id)+ await _switch_off(gated, "github", owner.id)++ async with gated.client() as client:+ grants = await client.get(+ f"/agents/{agent_id}/service-grants", headers=bearer(key)+ )+ token = await _token_for(gated, agent_id, key)++ assert grants.status_code == 200, grants.text+ assert grants.json()["grants"] == []+ assert token.status_code == 403+ assert token.json()["error"] == {+ "code": "forbidden",+ "message": WORKSPACE_REFUSAL,+ "retryable": False,+ }+ assert vendor.issued == [] and vendor.refreshes == 0+++async def _agents(harness: Harness, user, service: str = "github"):+ async with harness.client() as client:+ return await client.get(+ f"/gateway/service-connections/{service}/agents",+ cookies=cookies_for(user),+ )+++async def _set_policy(+ harness: Harness, agent_id: str, policy: AddressingPolicy+) -> None:+ async with harness.session_factory() as session:+ await session.execute(+ update(Agent)+ .where(Agent.id == agent_id)+ .values(addressing_policy=policy.model_dump())+ )+ await session.commit()+++class TestYourAgents:+ async def test_lists_only_the_callers_own_agents_in_this_workspace(+ self, harness: Harness, session_factory+ ) -> None:+ owner = await add_member(harness.session_factory, "ada")+ other = await add_member(harness.session_factory, "bob")+ granted_id, _ = await agent_with_key(harness.session_factory, owner, "builder")+ plain_id, _ = await agent_with_key(harness.session_factory, owner, "planner")+ await agent_with_key(harness.session_factory, other, "bobs-agent")+ await _make_tenant(session_factory, TENANT_A)+ elsewhere = bound_to(session_factory, TENANT_A)+ async with elsewhere() as session:+ session.add(+ TenantMember(tenant_id=TENANT_A, user_id=owner.id, role="member")+ )+ await session.commit()+ await agent_with_key(elsewhere, owner, "elsewhere")+ await connect(harness.session_factory, owner.id)+ await grant_directly(harness.session_factory, granted_id, owner.id)+ await _set_policy(harness, plain_id, owner_only_policy([]))++ response = await _agents(harness, owner)++ assert response.status_code == 200, response.text+ assert response.json() == [+ {+ "agent_id": granted_id,+ "name": "builder",+ "granted": True,+ "addressing_open": True,+ },+ {+ "agent_id": plain_id,+ "name": "planner",+ "granted": False,+ "addressing_open": False,+ },+ ]++ async def test_an_agent_its_owners_agents_can_address_is_open(+ self, harness: Harness+ ) -> None:+ owner = await add_member(harness.session_factory, "ada")+ agent_id, _ = await agent_with_key(harness.session_factory, owner, "builder")+ await _set_policy(harness, agent_id, owner_and_owner_agents_policy())++ response = await _agents(harness, owner)++ assert response.status_code == 200, response.text+ assert [(a["agent_id"], a["addressing_open"]) for a in response.json()] == [+ (agent_id, True)+ ]++ async def test_a_member_with_no_agents_gets_an_empty_list(+ self, harness: Harness+ ) -> None:+ member = await add_member(harness.session_factory, "cy")+ response = await _agents(harness, member)+ assert (response.status_code, response.json()) == (200, [])++ @pytest.mark.parametrize("service", ["nowhere", "asana"])+ async def test_an_unknown_or_placeholder_service_is_not_found(+ self, harness: Harness, service: str+ ) -> None:+ member = await add_member(harness.session_factory, "cy")+ response = await _agents(harness, member, service)+ assert response.status_code == 404+ assert response.json()["detail"] == f"No service named {service!r}."diff --git a/core/tests/switch_core/gateway/test_service_flows.py b/core/tests/switch_core/gateway/test_service_flows.pyindex f907906c9..610c760ce 100644--- a/core/tests/switch_core/gateway/test_service_flows.py+++ b/core/tests/switch_core/gateway/test_service_flows.py@@ -30,6 +30,7 @@ from switch_core.connections.oauth_clients import (from switch_core.connections.sign_in_flows import MAX_FLOWS, SignInFlowsfrom switch_core.db.models import ServiceConnection, SignInFlow, Userfrom switch_core.db.stores.service_connection_store import ServiceConnectionStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway.service_connections import (router as service_connections_router,)@@ -71,6 +72,7 @@ def _world(redirect: str = "[loopback, core]",public_url: str | None = None,disabled: dict[str, str] | None = None,+ workspace_gate: bool = False,) -> World:shutil.copytree(CATALOG_ROOT, root)# The vendor matches a loopback redirect's port, as Atlassian does.@@ -109,6 +111,8 @@ def _world(disabled=disabled or {},store=STORE,token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=workspace_gate,)harness = build_harness(session_factory)harness.gateway_app.state.service_broker = broker@@ -147,11 +151,9 @@ class Console:f"{FLOWS}/{self.state}", cookies=cookies_for(self.user))- async def confirm(self) -> httpx.Response:- return await self.client.post(- f"{FLOWS}/{self.state}/confirm",- json={"completion_secret": self.secret},- cookies=cookies_for(self.user),+ async def drop(self) -> httpx.Response:+ return await self.client.delete(+ f"{FLOWS}/{self.state}", cookies=cookies_for(self.user))@@ -170,6 +172,15 @@ async def _flow_ids(session_factory: async_sessionmaker[AsyncSession]) -> set[streturn set((await session.execute(select(SignInFlow.id))).scalars())+async def _flow_row(+ session_factory: async_sessionmaker[AsyncSession], state: str+) -> SignInFlow:+ async with session_factory() as session:+ row = await session.scalar(select(SignInFlow).where(SignInFlow.id == state))+ assert row is not None+ return row++async def _connection(session_factory: async_sessionmaker[AsyncSession], user_id: str) -> ServiceConnection | None:@@ -182,12 +193,17 @@ async def _connection()-async def _loopback_ready(world: World, console: Console) -> None:+async def _loopback_code(world: World, console: Console) -> str:+ """Start, sign in at the vendor, and take the code as Console's listener does."""started = await console.start()assert started.status_code == 200, started.text- code = _listener_code(world.vendor.authorize(started.json()["url"]), console.state)- completed = await console.complete(code)- assert completed.status_code == 204, completed.text+ return _listener_code(world.vendor.authorize(started.json()["url"]), console.state)+++async def _loopback_connect(world: World, console: Console) -> httpx.Response:+ completed = await console.complete(await _loopback_code(world, console))+ assert completed.status_code == 200, completed.text+ return completedclass TestLoopback:@@ -217,18 +233,27 @@ class TestLoopback:"status": "pending","account": None,"error": None,+ "warning": None,}- assert (await console.complete(code)).status_code == 204+ assert await _connection(session_factory, ada.id) is None+ completed = await console.complete(code)+ assert completed.status_code == 200, completed.text+ assert completed.json() == {+ "warning": None,+ "consent": "write",+ "account": "[email protected]",+ }+ # The outcome stays readable, without the token, until Console drops it.assert (await console.status()).json() == {- "status": "ready",+ "status": "connected","account": "[email protected]","error": None,+ "warning": None,}- # Nothing is written before the person confirms.- assert await _connection(session_factory, ada.id) is None- confirmed = await console.confirm()- assert confirmed.status_code == 200, confirmed.text- assert confirmed.json() == {"warning": None, "consent": "write"}+ flow = await _flow_row(session_factory, console.state)+ assert flow.encrypted_result is None+ assert (await console.drop()).status_code == 204+ assert (await console.status()).status_code == 410connection = await _connection(session_factory, ada.id)assert connection is not None@@ -251,7 +276,7 @@ class TestLoopback:code = _listener_code(world.vendor.authorize(started.json()["url"]), console.state)- assert (await console.complete(code)).status_code == 204+ assert (await console.complete(code)).status_code == 200replayed = await console.complete(code)assert replayed.status_code == 400assert len(world.vendor.token_requests) == 1@@ -270,8 +295,6 @@ class TestLoopback:refused = await console.complete(code, secret=secrets.token_urlsafe(32))assert refused.status_code == 400assert world.vendor.token_requests == []- confirmed_early = await console.confirm()- assert confirmed_early.status_code == 409async def test_a_state_is_used_once(self, session_factory, tmp_path) -> None:world = _world(session_factory, tmp_path / "catalog")@@ -347,8 +370,9 @@ class TestLoopback:ada = await add_member(session_factory, "ada")grace = await add_member(session_factory, "grace")async with world.harness.client() as client:- await _loopback_ready(world, Console(client, ada))- await _loopback_ready(world, Console(client, grace))+ # Registration happens as the first sign-in starts.+ await _loopback_code(world, Console(client, ada))+ await _loopback_code(world, Console(client, grace))assert len(world.vendor.registrations) == 1async def test_an_account_linked_to_someone_else_is_refused(@@ -358,14 +382,14 @@ class TestLoopback:ada = await add_member(session_factory, "ada")grace = await add_member(session_factory, "grace")async with world.harness.client() as client:- first = Console(client, ada)- await _loopback_ready(world, first)- assert (await first.confirm()).status_code == 200+ await _loopback_connect(world, Console(client, ada))second = Console(client, grace)- await _loopback_ready(world, second)- refused = await second.confirm()+ refused = await second.complete(await _loopback_code(world, second))assert refused.status_code == 409assert refused.json()["code"] == "account_linked_elsewhere"+ # The flow reads failed with the reason, for Console to show.+ assert (await second.status()).json()["status"] == "failed"+ assert "already linked" in (await second.status()).json()["error"]assert await _connection(session_factory, grace.id) is Noneasync def test_a_sign_in_granted_only_reading_connects_read_only(@@ -377,9 +401,8 @@ class TestLoopback:world.vendor.mint = lambda scopes: mint(["read:items"]) # type: ignore[method-assign]async with world.harness.client() as client:console = Console(client, ada)- await _loopback_ready(world, console)- confirmed = await console.confirm()- assert confirmed.json()["consent"] == "read"+ connected = await _loopback_connect(world, console)+ assert connected.json()["consent"] == "read"connection = await _connection(session_factory, ada.id)assert connection is not None and connection.consent == "read"@@ -400,10 +423,9 @@ class TestLongCodes:world.vendor.authorize(started.json()["url"]), console.state)assert len(code) == 2177- assert (await console.complete(code)).status_code == 204- assert (await console.confirm()).status_code == 200+ assert (await console.complete(code)).status_code == 200- async def test_a_long_code_is_relayed_through_core(+ async def test_a_long_code_comes_back_through_core(self, session_factory, tmp_path) -> None:world = _world(@@ -422,16 +444,10 @@ class TestLongCodes:}back = urlsplit(world.vendor.authorize(left.headers["location"]))code = parse_qs(back.query)["code"][0]- assert (- await client.get(f"{back.path}?{back.query}", cookies=cookie)- ).status_code == 200- relayed = await client.post(- f"{FLOWS}/callback",- data={"state": console.state, "code": code},- cookies=cookie,- )- assert relayed.status_code == 303- assert (await console.complete(code)).status_code == 204+ returned = await client.get(f"{back.path}?{back.query}", cookies=cookie)+ assert returned.status_code == 303+ assert _listener_code(returned.headers["location"], console.state) == code+ assert (await console.complete(code)).status_code == 200class TestLoopbackPorts:@@ -449,8 +465,7 @@ class TestLoopbackPorts:f"http://127.0.0.1:43124{LOOPBACK_CALLBACK_PATH}")code = parse_qs(back.query)["code"][0]- assert (await console.complete(code)).status_code == 204- assert (await console.confirm()).status_code == 200+ assert (await console.complete(code)).status_code == 200async def test_refuses_a_port_the_vendor_would_not_take(self, session_factory, tmp_path@@ -465,7 +480,7 @@ class TestLoopbackPorts:class TestCoreCallback:- async def test_returns_through_core_then_relays_the_code_to_console(+ async def test_returns_through_core_straight_to_console(self, session_factory, tmp_path) -> None:world = _world(@@ -500,25 +515,22 @@ class TestCoreCallback:code = query["code"][0]path = f"{back.path}?{back.query}"+ # Only the browser that left through Core may bring the code back,+ # and it is sent straight on to Console's listener, once.stranger = await client.get(path)assert stranger.status_code == 400- page = await client.get(+ returned = await client.get(path, cookies={f"switch_service_{console.state}": cookie})- assert page.status_code == 200- assert "ada ([email protected])" in page.text- assert f"http://127.0.0.1:{PORT}" in page.headers["content-security-policy"]-- relayed = await client.post(- f"{FLOWS}/callback",- data={"state": console.state, "code": code},- cookies={f"switch_service_{console.state}": cookie},+ assert returned.status_code == 303+ assert _listener_code(returned.headers["location"], console.state) == code+ assert "max-age=0" in returned.headers["set-cookie"].lower()+ again = await client.get(+ path, cookies={f"switch_service_{console.state}": cookie})- assert relayed.status_code == 303- assert _listener_code(relayed.headers["location"], console.state) == code+ assert again.status_code == 400- assert (await console.complete(code)).status_code == 204- assert (await console.confirm()).status_code == 200+ assert (await console.complete(code)).status_code == 200connection = await _connection(session_factory, ada.id)assert connection is not None and connection.account_id == "acct-1"[exchange] = [@@ -528,9 +540,7 @@ class TestCoreCallback:]assert exchange["redirect_uri"] == f"{PUBLIC}{FLOWS}/callback"- async def test_a_code_cannot_skip_core_and_the_person(- self, session_factory, tmp_path- ) -> None:+ async def test_a_code_cannot_skip_core(self, session_factory, tmp_path) -> None:world = _world(session_factory, tmp_path / "catalog", redirect="[core]", public_url=PUBLIC)@@ -580,3 +590,105 @@ class TestRefusals:refused = await Console(client, ada).start("github")assert refused.status_code == 404assert "its own sign-in" in refused.json()["detail"]+++WORKSPACE_REFUSAL = {+ "detail": (+ "Example is not enabled in this workspace. Ask a workspace admin; they "+ "switch it on under Connectors in Switch Console."+ ),+ "code": "forbidden",+ "retryable": False,+}+++async def _switch(+ session_factory: async_sessionmaker[AsyncSession], enabled: bool, admin: User+) -> None:+ async with session_factory() as session:+ await WorkspaceServiceStore().set_enabled(session, "example", enabled, admin.id)+ await session.commit()+++class TestWorkspaceSwitch:+ async def test_a_service_the_workspace_switched_off_is_refused_before_the_vendor(+ self, session_factory, tmp_path+ ) -> None:+ world = _world(session_factory, tmp_path / "catalog", workspace_gate=True)+ ada = await add_member(session_factory, "ada")+ await _switch(session_factory, False, ada)+ async with world.harness.client() as client:+ refused = await Console(client, ada).start()+ assert refused.status_code == 403+ assert refused.json() == WORKSPACE_REFUSAL+ assert world.vendor.paths == []+ assert world.vendor.registrations == []+ assert await _flow_ids(session_factory) == set()++ async def test_switched_back_on_it_proceeds(+ self, session_factory, tmp_path+ ) -> None:+ world = _world(session_factory, tmp_path / "catalog", workspace_gate=True)+ ada = await add_member(session_factory, "ada")+ await _switch(session_factory, False, ada)+ await _switch(session_factory, True, ada)+ async with world.harness.client() as client:+ started = await Console(client, ada).start()+ assert started.status_code == 200, started.text++ async def test_with_the_gate_off_the_switch_is_ignored(+ self, session_factory, tmp_path+ ) -> None:+ world = _world(session_factory, tmp_path / "catalog", workspace_gate=False)+ ada = await add_member(session_factory, "ada")+ await _switch(session_factory, False, ada)+ async with world.harness.client() as client:+ started = await Console(client, ada).start()+ assert started.status_code == 200, started.text++ async def test_switched_off_mid_sign_in_the_issued_sign_in_is_revoked(+ self, session_factory, tmp_path+ ) -> None:+ # Revoking at the endpoint the vendor advertises, as Atlassian does.+ world = _world(+ session_factory,+ tmp_path / "catalog",+ redirect="[loopback, core]\n revocation_discovered: true",+ workspace_gate=True,+ )+ ada = await add_member(session_factory, "ada")+ async with world.harness.client() as client:+ console = Console(client, ada)+ code = await _loopback_code(world, console)+ await _switch(session_factory, False, ada)+ refused = await console.complete(code)+ assert refused.status_code == 403+ assert refused.json() == WORKSPACE_REFUSAL+ assert await _connection(session_factory, ada.id) is None+ # The one refresh token the vendor issued for this sign-in is revoked.+ assert [form["token_type_hint"] for form in world.vendor.revoked] == [+ "refresh_token"+ ]+ assert world.vendor.live_refresh == {}+ flow = await _flow_row(session_factory, console.state)+ assert (flow.status, flow.encrypted_result) == ("failed", None)+ assert flow.error == WORKSPACE_REFUSAL["detail"]++ async def test_a_sign_in_that_cannot_be_revoked_says_what_to_do(+ self, session_factory, tmp_path+ ) -> None:+ world = _world(session_factory, tmp_path / "catalog", workspace_gate=True)+ ada = await add_member(session_factory, "ada")+ async with world.harness.client() as client:+ console = Console(client, ada)+ code = await _loopback_code(world, console)+ await _switch(session_factory, False, ada)+ refused = await console.complete(code)+ assert refused.status_code == 403+ assert refused.json() == {+ **WORKSPACE_REFUSAL,+ "detail": WORKSPACE_REFUSAL["detail"]+ + " Switch could not revoke the sign-in Example just issued. Remove "+ "Switch from your Example account's connected apps.",+ }+ assert await _connection(session_factory, ada.id) is Nonediff --git a/core/tests/switch_core/gateway/test_service_keys.py b/core/tests/switch_core/gateway/test_service_keys.pyindex ccddc4980..f6612f2bd 100644--- a/core/tests/switch_core/gateway/test_service_keys.py+++ b/core/tests/switch_core/gateway/test_service_keys.py@@ -20,6 +20,7 @@ from switch_core.connections.adapters.api_key import ApiKeyAdapterfrom switch_core.connections.broker import ServiceBrokerfrom switch_core.connections.loader import CATALOGfrom switch_core.db.models import ServiceConnection+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom tests.conftest import TEST_KEYRINGfrom tests.switch_core.connections.fake_vendor import FakeVendorfrom tests.switch_core.connections.service_harness import (@@ -65,7 +66,9 @@ def datadog() -> DatadogStandIn:def service(session_factory: async_sessionmaker[AsyncSession], datadog: DatadogStandIn) -> tuple[Harness, ServiceBroker]:- harness, broker = build_service_harness(session_factory, FakeVendor())+ harness, broker = build_service_harness(+ session_factory, FakeVendor(), workspace_gate=False+ )broker._adapters["datadog"] = ApiKeyAdapter(CATALOG["datadog"].definition,httpx.AsyncClient(transport=httpx.MockTransport(datadog)),@@ -240,3 +243,36 @@ class TestUse:},}]+++class TestWorkspaceSwitch:+ async def test_a_key_for_a_service_the_workspace_switched_off_is_never_checked(+ self, session_factory, datadog: DatadogStandIn+ ) -> None:+ harness, broker = build_service_harness(+ session_factory, FakeVendor(), workspace_gate=True+ )+ broker._adapters["datadog"] = ApiKeyAdapter(+ CATALOG["datadog"].definition,+ httpx.AsyncClient(transport=httpx.MockTransport(datadog)),+ )+ owner = await add_member(harness.session_factory, "ada")+ async with harness.session_factory() as session:+ await WorkspaceServiceStore().set_enabled(+ session, "datadog", False, owner.id+ )+ await session.commit()++ response = await _connect(harness, owner, KEYS)++ assert response.status_code == 403+ assert response.json() == {+ "detail": (+ "Datadog is not enabled in this workspace. Ask a workspace admin; "+ "they switch it on under Connectors in Switch Console."+ ),+ "code": "forbidden",+ "retryable": False,+ }+ assert datadog.requests == []+ assert await _connections(harness) == []diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.pyindex c32accb51..cfd7d3858 100644--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py@@ -76,14 +76,13 @@ _ROUTES_WITH_NO_TENANT_BOUND = {# than a route nobody counted. `_ROUTES_WITH_NO_TENANT_BOUND` is a strict subset._ROUTES_THAT_NEVER_BIND_A_TENANT = {# Browser handoff uses a short-lived flow, browser cookie and PKCE; saving- # credentials requires the initiating user to confirm via the authenticated API.+ # credentials requires the initiating user to hand the code back through+ # the authenticated API.("GET", "/provider-connections/github/authorize"),("GET", "/provider-connections/github/callback"),- ("POST", "/provider-connections/github/callback"),# The same handoff for every other service's sign-in (`connections/flows.py`).("GET", "/service-connections/{service}/flows/authorize"),("GET", "/service-connections/{service}/flows/callback"),- ("POST", "/service-connections/{service}/flows/callback"),# No caller yet: the sign-in surface and what it hands back.("GET", "/auth/config"),("GET", "/auth/oidc/login"),diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex c3bb10ada..e5936bdff 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -57,6 +57,7 @@ from switch_core.db.stores.service_connection_store import ServiceConnectionStorfrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway import dependencies as gw_depsfrom switch_core.gateway.auth import create_jwt, decode_jwtfrom switch_core.gateway.invite_mail import (@@ -161,6 +162,8 @@ def _app(disabled={},store=ServiceConnectionStore(),token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(keyring=_KEYRING,@@ -1491,6 +1494,7 @@ class TestMemberRoutes:encrypted_secret=_KEYRING.encrypt(json.dumps({"access_token": "SYNTHETIC-USER-TOKEN"})),+ oauth_client_id=None,)session.add(ServiceTokenIssuance(@@ -1540,6 +1544,8 @@ class TestMemberRoutes:disabled={},store=ServiceConnectionStore(),token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,)async with _client(app, token) as client:response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")diff --git a/core/tests/switch_core/gateway/test_workspace_services.py b/core/tests/switch_core/gateway/test_workspace_services.pynew file mode 100644index 000000000..4b421fc8a--- /dev/null+++ b/core/tests/switch_core/gateway/test_workspace_services.py@@ -0,0 +1,385 @@+"""A workspace admin's switch per service, through the real gateway on Postgres.++Signed in with real session cookies. Switching off reaches other people's+running sessions, so the list says who it touches, and GitHub's live tokens are+revoked before the switch answers. That the routes are absent without the+`service_connections` flag is checked in `test_app_route_mounting.py`.+"""++from __future__ import annotations++import hashlib+import uuid+from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.connections.adapters import ServiceAdapterError+from switch_core.db.audit import AuditAction+from switch_core.db.models import (+ TENANT_ZERO_ID,+ AuditEvent,+ ServiceGrant,+ ServiceTokenIssuance,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from tests.conftest import TEST_KEYRING+from tests.switch_core.connections.fake_vendor import FakeVendor+from tests.switch_core.connections.service_harness import (+ STORE,+ agent_with_key,+ build_service_harness,+ connect,+ grant_directly,+)+from tests.switch_core.gateway.test_tenant_api_routes import TENANT_A, _make_tenant+from tests.switch_core.management.harness import Harness, add_member, cookies_for++SERVICES = "/gateway/workspace/services"+++def vendor() -> FakeVendor:+ return FakeVendor()+++def harness(+ session_factory: async_sessionmaker[AsyncSession], vendor: FakeVendor+) -> Harness:+ return build_service_harness(session_factory, vendor, workspace_gate=True)[0]+++async def _person(+ session_factory: async_sessionmaker[AsyncSession],+ name: str,+ *,+ member_role: str | None,+ user_role: str = "user",+) -> User:+ """A user, a member of tenant zero in `member_role` (None: not a member)."""+ async with session_factory() as session:+ user = User(name=name, email=f"{name}@example.invalid", role=user_role)+ session.add(user)+ await session.flush()+ if member_role is not None:+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID, user_id=user.id, role=member_role+ )+ )+ await session.commit()+ return user+++async def _put(harness: Harness, user: User | None, service: str, body: object):+ async with harness.client() as client:+ return await client.put(+ f"{SERVICES}/{service}",+ json=body,+ cookies={} if user is None else cookies_for(user),+ )+++async def _get(harness: Harness, user: User | None):+ async with harness.client() as client:+ return await client.get(+ SERVICES, cookies={} if user is None else cookies_for(user)+ )+++def _by_slug(response) -> dict[str, dict]:+ assert response.status_code == 200, response.text+ return {service["slug"]: service for service in response.json()["services"]}+++async def _granted(+ session_factory: async_sessionmaker[AsyncSession],+ owner: User,+ agent_id: str,+ service: str,+) -> ServiceGrant:+ """A connection to `service` and a grant on it, so a token issued under it+ is live rather than orphaned."""+ async with session_factory() as session:+ await STORE.save_connection(+ session,+ user_id=owner.id,+ service=service,+ consent="write",+ granted_scopes=[],+ account_id=f"{service}-account",+ external_identity=owner.name,+ encrypted_secret=TEST_KEYRING.encrypt("{}"),+ oauth_client_id=None,+ )+ grant = await STORE.save_grant(+ session,+ agent_id=agent_id,+ owner_id=owner.id,+ service=service,+ access="write",+ tool_mode="deny",+ tools=[],+ resources={},+ account_id=f"{service}-account",+ created_by=owner.id,+ )+ await session.commit()+ return grant+++def _issuance(+ grant: ServiceGrant | None,+ owner_id: str,+ service: str,+ token: str,+ *,+ tenant_id: str = TENANT_ZERO_ID,+) -> ServiceTokenIssuance:+ return ServiceTokenIssuance(+ tenant_id=tenant_id,+ grant_id=str(uuid.uuid4()) if grant is None else grant.id,+ agent_id=str(uuid.uuid4()) if grant is None else grant.agent_id,+ owner_id=owner_id,+ service=service,+ principal="agent_key",+ controller_id=None,+ permissions={},+ resources={},+ expires_at=datetime.now(UTC) + timedelta(minutes=50),+ token_sha256=hashlib.sha256(token.encode()).hexdigest(),+ encrypted_token=TEST_KEYRING.encrypt(token),+ revoke_requested=False,+ attempts=0,+ )+++async def _issuances(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> dict[str, ServiceTokenIssuance]:+ async with tenant_session(session_factory, tenant_id) as session:+ rows = await session.scalars(select(ServiceTokenIssuance))+ by_hash = {row.token_sha256: row for row in rows}+ return {+ token: by_hash[hashlib.sha256(token.encode()).hexdigest()]+ for token in ("ghs_here", "other_service", "ghs_elsewhere")+ if hashlib.sha256(token.encode()).hexdigest() in by_hash+ }+++class TestWhoMayCall:+ @pytest.mark.parametrize(+ ("member_role", "user_role", "expected"),+ [+ ("member", "user", 403),+ ("admin", "user", 200),+ ("owner", "user", 200),+ ("member", "admin", 200),+ # The gateway binds only a workspace the caller belongs to, the+ # operator included: the operator bit lifts a member, it does not+ # reach into a workspace from outside.+ (None, "admin", 403),+ ],+ ids=["member", "admin", "owner", "operator-as-member", "operator-not-a-member"],+ )+ async def test_only_admins_owners_and_the_operator(+ self, harness: Harness, member_role, user_role, expected+ ) -> None:+ user = await _person(+ harness.session_factory,+ f"caller-{uuid.uuid4().hex[:6]}",+ member_role=member_role,+ user_role=user_role,+ )+ listed = await _get(harness, user)+ switched = await _put(harness, user, "datadog", {"enabled": False})+ assert (listed.status_code, switched.status_code) == (expected, expected)++ async def test_signed_out_is_unauthorized(self, harness: Harness) -> None:+ assert (await _get(harness, None)).status_code == 401+ assert (+ await _put(harness, None, "datadog", {"enabled": False})+ ).status_code == 401+++class TestRequests:+ @pytest.mark.parametrize("service", ["nowhere", "asana"])+ async def test_an_unknown_or_placeholder_service_is_not_found(+ self, harness: Harness, service: str+ ) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ response = await _put(harness, admin, service, {"enabled": False})+ assert response.status_code == 404+ assert response.json()["detail"] == f"No service named {service!r}."++ @pytest.mark.parametrize(+ "body", [{}, {"enabled": "no"}, {"enabled": False, "extra": 1}]+ )+ async def test_a_bad_body_is_refused(self, harness: Harness, body) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ assert (await _put(harness, admin, "datadog", body)).status_code == 422++ async def test_the_same_switch_twice_is_no_error(self, harness: Harness) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ for _ in range(2):+ response = await _put(harness, admin, "datadog", {"enabled": False})+ assert response.status_code == 200, response.text+++class TestResults:+ async def test_untouched_services_read_on_with_nobody_named(+ self, harness: Harness+ ) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ services = _by_slug(await _get(harness, admin))+ assert set(services) == {"atlassian", "datadog", "github", "google-workspace"}+ assert services["datadog"] == {+ "slug": "datadog",+ "name": "Datadog",+ "enabled": True,+ "updated_by_name": None,+ "updated_at": None,+ "connected_members": 0,+ "granted_agents": 0,+ }++ async def test_a_switch_round_trips_naming_the_admin_with_one_audit_row_each(+ self, harness: Harness+ ) -> None:+ admin = await _person(harness.session_factory, "ines", member_role="admin")+ off = await _put(harness, admin, "datadog", {"enabled": False})+ assert off.json() == {"slug": "datadog", "enabled": False, "warning": None}+ datadog = _by_slug(await _get(harness, admin))["datadog"]+ assert (datadog["enabled"], datadog["updated_by_name"]) == (False, "ines")+ assert datadog["updated_at"] is not None++ await _put(harness, admin, "datadog", {"enabled": True})+ assert _by_slug(await _get(harness, admin))["datadog"]["enabled"] is True++ async with harness.session_factory() as session:+ events = list(+ await session.scalars(+ select(AuditEvent).order_by(AuditEvent.occurred_at, AuditEvent.id)+ )+ )+ assert [+ (event.action, event.actor_user_id, event.target_id, event.details)+ for event in events+ ] == [+ (+ AuditAction.WORKSPACE_SERVICE_DISABLED.value,+ admin.id,+ "datadog",+ {"service": "datadog"},+ ),+ (+ AuditAction.WORKSPACE_SERVICE_ENABLED.value,+ admin.id,+ "datadog",+ {"service": "datadog"},+ ),+ ]++ async def test_the_counts_say_who_switching_off_reaches(+ self, harness: Harness+ ) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ ada = await add_member(harness.session_factory, "ada")+ bob = await add_member(harness.session_factory, "bob")+ await connect(harness.session_factory, ada.id, account_id="1001")+ await connect(harness.session_factory, bob.id, account_id="1002")+ agent_id, _ = await agent_with_key(harness.session_factory, ada, "builder")+ await grant_directly(harness.session_factory, agent_id, ada.id)++ services = _by_slug(await _get(harness, admin))++ assert (+ services["github"]["connected_members"],+ services["github"]["granted_agents"],+ ) == (2, 1)+ assert (+ services["atlassian"]["connected_members"],+ services["atlassian"]["granted_agents"],+ ) == (0, 0)+++class TestSwitchingOff:+ async def test_revokes_only_this_workspaces_tokens_for_it_before_answering(+ self, harness: Harness, vendor: FakeVendor, session_factory+ ) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ ada = await add_member(harness.session_factory, "ada")+ agent_id, _ = await agent_with_key(harness.session_factory, ada, "builder")+ github = await _granted(harness.session_factory, ada, agent_id, "github")+ atlassian = await _granted(harness.session_factory, ada, agent_id, "atlassian")+ await _make_tenant(session_factory, TENANT_A)+ async with harness.session_factory() as session:+ session.add_all(+ [+ _issuance(github, ada.id, "github", "ghs_here"),+ _issuance(atlassian, ada.id, "atlassian", "other_service"),+ ]+ )+ await session.commit()+ # Another workspace's token for the same service, which its own+ # revocation pass would leave alone just as this one must.+ async with tenant_session(session_factory, TENANT_A) as session:+ session.add(+ _issuance(None, ada.id, "github", "ghs_elsewhere", tenant_id=TENANT_A)+ )+ await session.commit()++ response = await _put(harness, admin, "github", {"enabled": False})++ assert response.json()["warning"] is None+ assert vendor.revoked == ["ghs_here"]+ here = await _issuances(session_factory, TENANT_ZERO_ID)+ assert here["ghs_here"].encrypted_token is None+ assert here["other_service"].revoke_requested is False+ elsewhere = await _issuances(session_factory, TENANT_A)+ assert elsewhere["ghs_elsewhere"].revoke_requested is False++ async def test_a_revoke_the_vendor_refuses_stays_queued_with_a_warning(+ self, harness: Harness, vendor: FakeVendor, session_factory+ ) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ ada = await add_member(harness.session_factory, "ada")+ agent_id, _ = await agent_with_key(harness.session_factory, ada, "builder")+ github = await _granted(harness.session_factory, ada, agent_id, "github")+ async with harness.session_factory() as session:+ session.add(_issuance(github, ada.id, "github", "ghs_here"))+ await session.commit()++ async def unreachable(token: str) -> None:+ raise ServiceAdapterError("GitHub is unreachable.")++ vendor.revoke_issued = unreachable # type: ignore[method-assign]+ response = await _put(harness, admin, "github", {"enabled": False})++ assert response.status_code == 200, response.text+ assert response.json()["warning"] == (+ "Some access already given out may remain for up to 1 hour."+ )+ record = (await _issuances(session_factory, TENANT_ZERO_ID))["ghs_here"]+ assert record.revoke_requested is True+ assert record.encrypted_token is not None++ async def test_keeps_the_grants(self, harness: Harness) -> None:+ admin = await _person(harness.session_factory, "admin", member_role="admin")+ ada = await add_member(harness.session_factory, "ada")+ await connect(harness.session_factory, ada.id)+ agent_id, _ = await agent_with_key(harness.session_factory, ada, "builder")+ grant = await grant_directly(harness.session_factory, agent_id, ada.id)++ await _put(harness, admin, "github", {"enabled": False})++ async with harness.session_factory() as session:+ kept = await session.scalar(+ select(ServiceGrant).where(ServiceGrant.id == grant.id)+ )+ assert kept is not None and kept.revision == grant.revisiondiff --git a/core/tests/switch_core/providers/test_github_installation.py b/core/tests/switch_core/providers/test_github_installation.pyindex ffa0f3a1b..f0de8a45a 100644--- a/core/tests/switch_core/providers/test_github_installation.py+++ b/core/tests/switch_core/providers/test_github_installation.py@@ -28,7 +28,7 @@ def signing(tmp_path, monkeypatch):))path.chmod(0o600)- return GitHubInstallationCredentials("example-client", str(path)), key+ return GitHubInstallationCredentials.from_file("example-client", str(path)), keydef response_body():@@ -152,7 +152,7 @@ def test_invalid_key_fails_without_key_material(tmp_path):path = tmp_path / "invalid.pem"path.write_text("SYNTHETIC-INVALID-KEY")with pytest.raises(ValueError, match="could not be loaded"):- GitHubInstallationCredentials("example-client", str(path))+ GitHubInstallationCredentials.from_file("example-client", str(path))@pytest.mark.parametrize(diff --git a/core/tests/switch_core/providers/test_github_repositories.py b/core/tests/switch_core/providers/test_github_repositories.pyindex 15abd0c82..55eed8b77 100644--- a/core/tests/switch_core/providers/test_github_repositories.py+++ b/core/tests/switch_core/providers/test_github_repositories.py@@ -35,7 +35,7 @@ def github(tmp_path) -> GitHubConnections:}))- return GitHubConnections(str(config))+ return GitHubConnections.from_file(str(config))def _repo(repo_id: int) -> dict:diff --git a/core/tests/switch_core/test_addressing.py b/core/tests/switch_core/test_addressing.pyindex 089fea857..583b5cb06 100644--- a/core/tests/switch_core/test_addressing.py+++ b/core/tests/switch_core/test_addressing.py@@ -610,22 +610,35 @@ class TestRequiresOwnerIdentity:class TestAdmitsOthers:- """Whether anyone but the owner and their own agents can address the agent."""+ """Whether anyone but the owner can address the agent."""- OWN = {"owner_identity_ids": {"ext-owner"}, "owner_agent_ids": {"own-agent"}}+ OWN = {"owner_identity_ids": {"ext-owner"}}def test_open_policy_admits_others(self) -> None:assert AddressingPolicy().admits_others(**self.OWN) is True- def test_owner_and_owner_agents_do_not(self) -> None:- assert owner_and_owner_agents_policy().admits_others(**self.OWN) is False+ def test_the_owner_alone_does_not(self) -> None:assert owner_only_policy([]).admits_others(**self.OWN) is False- assert owner_only_policy(["own-agent"]).admits_others(**self.OWN) is False++ def test_the_owners_agents_do(self) -> None:+ assert owner_and_owner_agents_policy().admits_others(**self.OWN) is True+ assert owner_only_policy(["own-agent"]).admits_others(**self.OWN) is True++ def test_the_owners_agents_are_still_allowed_to_address_it(self) -> None:+ assert owner_and_owner_agents_policy().allows(+ room_id="room-x",+ group_id=None,+ sender_kind="agent",+ sender_id="own-agent",+ sender_user_ids=[],+ sender_owner_user_id="owner",+ owner_user_id="owner",+ )def test_anyone_in_one_room_does(self) -> None:policy = AddressingPolicy(rules=[- *owner_and_owner_agents_policy().rules,+ *owner_only_policy([]).rules,AddressingRule(rooms=["room-x"], users="*", agents=[]),])@@ -649,7 +662,7 @@ class TestAdmitsOthers:def test_a_platform_rule_does_not(self) -> None:policy = AddressingPolicy(rules=[- *owner_and_owner_agents_policy().rules,+ *owner_only_policy([]).rules,*platform_allowed_policy().rules,])diff --git a/core/tests/switch_core/test_migration_connector_app_credentials.py b/core/tests/switch_core/test_migration_connector_app_credentials.pynew file mode 100644index 000000000..bf9658666--- /dev/null+++ b/core/tests/switch_core/test_migration_connector_app_credentials.py@@ -0,0 +1,111 @@+"""`c7715ebb95c9` adds the operator's connector apps, the server audit log and+each connection's OAuth client, and its downgrade takes them away again."""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest+from alembic.config import Config+from alembic.runtime.environment import EnvironmentContext+from alembic.script import ScriptDirectory+from sqlalchemy import Connection, text+from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine++_CORE = Path(__file__).resolve().parents[2]+_DB = "migration_connector_app_credentials"++_BEFORE = "98c28a6e7c55"+_UNDER_TEST = "c7715ebb95c9"+++def _script_directory(config: Config) -> ScriptDirectory:+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))+ return ScriptDirectory.from_config(config)+++def _migrate(revision: str, *, downgrade: bool) -> Any:+ def migrate(connection: Connection) -> None:+ config = Config(str(_CORE / "alembic.ini"))+ script = _script_directory(config)++ def revisions(current_revision: str, context: Any) -> Any:+ if downgrade:+ return script._downgrade_revs(revision, current_revision)+ return script._upgrade_revs(revision, current_revision)++ with EnvironmentContext(config, script, fn=revisions) as environment:+ environment.configure(connection=connection)+ with environment.begin_transaction():+ environment.run_migrations()++ return migrate+++async def database_url(postgres_url: str) -> Any:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))+ await connection.execute(text(f'CREATE DATABASE "{_DB}"'))+ await admin.dispose()++ base, _, _ = postgres_url.rpartition("/")+ try:+ yield f"{base}/{_DB}"+ finally:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))+ await admin.dispose()+++async def _shape(connection: AsyncConnection) -> tuple[set[str], bool]:+ tables = {+ row[0]+ for row in await connection.execute(+ text(+ "SELECT table_name FROM information_schema.tables WHERE table_name "+ "IN ('service_app_credentials', 'server_audit_events')"+ )+ )+ }+ column = await connection.scalar(+ text(+ "SELECT count(*) FROM information_schema.columns WHERE table_name = "+ "'service_connections' AND column_name = 'oauth_client_id'"+ )+ )+ return tables, column == 1+++async def test_upgrades_and_downgrades(database_url: str) -> None:+ engine = create_async_engine(database_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_migrate(_BEFORE, downgrade=False))+ async with engine.connect() as connection:+ assert await _shape(connection) == (set(), False)++ async with engine.begin() as connection:+ await connection.run_sync(_migrate(_UNDER_TEST, downgrade=False))+ async with engine.connect() as connection:+ assert await _shape(connection) == (+ {"service_app_credentials", "server_audit_events"},+ True,+ )+ protected = await connection.scalar(+ text(+ "SELECT bool_or(relrowsecurity) FROM pg_class WHERE relname IN "+ "('service_app_credentials', 'server_audit_events')"+ )+ )+ assert protected is False++ async with engine.begin() as connection:+ await connection.run_sync(_migrate(_BEFORE, downgrade=True))+ async with engine.connect() as connection:+ assert await _shape(connection) == (set(), False)+ finally:+ await engine.dispose()diff --git a/deploy/hosted/README.md b/deploy/hosted/README.mdindex 13016106a..82d6e306b 100644--- a/deploy/hosted/README.md+++ b/deploy/hosted/README.md@@ -208,10 +208,11 @@ Before upgrading an installation that has cloud machines:## GitHub connectionsGitHub connections are not part of cloud machines. To let users link their-GitHub account, set `HOSTED_GITHUB_CONFIG_PATH` to a private JSON file with-`client_id`, `client_secret`, `slug` and the public HTTPS Switch `origin`-(chart: `switchCore.githubConnectionsSecret`, key `github.json`), and register-`<origin>/gateway/provider-connections/github/callback` as the GitHub App-callback with expiring user tokens. Sign-in flows live in the Switch API-process, so run it with one replica. Keep query strings out of every access-log in front of the callback: its URL carries a single-use OAuth code.+GitHub account and grant agents repositories, set up the GitHub App under+Connectors in the Switch dashboard, or in the chart with+`switchCore.githubConnectionsSecret` and `switchCore.githubAppPrivateKeyPath`+([GitHub App setup](../../docs/old/github-app-setup.md)). Register+`<GATEWAY_PUBLIC_URL>/gateway/provider-connections/github/callback` as the+App's callback, with expiring user tokens. Sign-in flows live in the Switch+API process, so run it with one replica. Keep query strings out of every+access log in front of the callback: its URL carries a single-use OAuth code.diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 348063575..bd618cd45 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -189,6 +189,10 @@ secrets:# ── Switch Core (FastAPI) ─────────────────────────────────────────────────────switchCore:+ # The GitHub App and Google's client below are optional: the server's+ # operator can set them up under Connectors in the dashboard instead+ # (docs/old/github-app-setup.md, docs/old/google-workspace-setup.md). Set+ # here, they win over what is saved there.# Existing Secret with github.json (client_id, client_secret, slug, origin).githubConnectionsSecret: ""# Absolute path to the GitHub App's signing key inside a Secret this chart@@ -201,7 +205,8 @@ switchCore:# Existing Secret with client.json ({"client_id", "client_secret"}): the# Web OAuth client of an internal Google app, for the Google Workspace# connection. Register <gatewayPublicUrl>/gateway/service-connections/google-workspace/flows/callback- # as its redirect URI. Without it, Google Workspace shows as not set up.+ # as its redirect URI. Without it or one saved under Connectors, Google+ # Workspace shows as not set up.googleWorkspaceClientSecret: ""hostedControllerSecret: ""# How many cloud machines may run at once; 0 means this server cannot rundiff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex 74f976979..7fccd2425 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -116,7 +116,7 @@ id, no IP field, no Switch identity.| Event | Fields, with example values ||---|---|-| `view_opened` | `view_id`, one of exactly 10: `home`, `location`, `session`, `room`, `settings`, `server`, `serverAgents`, `serverRooms`, `remoteHosts`, `remoteHost` |+| `view_opened` | `view_id`, one of exactly 18: `home`, `location`, `session`, `managedAgent`, `room`, `settings`, `server`, `managedServer`, `serverAgents`, `connectors`, `serverRooms`, `remoteHosts`, `remoteHost`, `templateImport`, `templates`, `templateDetail`, `templateUse`, `templateCapture` || `command_executed` | `command_id`, one of 28 known commands: `app.settings`, `app.newSession`, `app.addServer`, `app.toggleTheme`, `session.newTerminal`, `session.gitPush`, … · `invoked_by`: `palette` / `shortcut` || `deeplink_opened` | `resolved`: `true` / `false` · `cold_start`: `true` / `false`. **The URL is never sent.** || `onboarding_step_started` | `step_id`, one of exactly 4: `addServer`, `agentProviders`, `onboardAgents`, `createRoom` |diff --git a/docs/design/service-connections-v2.md b/docs/design/service-connections-v2.mdindex 9e71e5524..d6f6fe51b 100644--- a/docs/design/service-connections-v2.md+++ b/docs/design/service-connections-v2.md@@ -32,7 +32,8 @@ auth:refresh: rotating # rotating | reusableoauth:registration: dynamic # dynamic: Core registers its own client- # static: client_settings names <PREFIX>_CLIENT_CONFIG_PATH+ # static: the operator's, saved in the dashboard or named+ # by <PREFIX>_CLIENT_CONFIG_PATH (client_settings)redirect: [loopback] # loopback (Switch Console) and/or core (Core's callback)loopback_ports: [39231, 39232, 39233, 39234, 39235]prompt: consent # sent with every authorization@@ -91,10 +92,19 @@ An entry with a `cli` has no MCP server to discover from, so it names itsone), and its client is the operator's (`registration: static`). No twoentries may give a session a server of the same name.-`<PREFIX>_CLIENT_CONFIG_PATH` names a static client's settings, a JSON file-holding `client_id` and `client_secret` and nothing else. Unset, the service is-shown as not set up on this server, with the entry's `setup_note`; set but-unusable, the server does not start.+A static client is the server operator's, and comes from one of two places+(`connections/app_credentials.py`): a row saved from the dashboard's Connector+apps page (`service_app_credentials`, its secret encrypted with the keyring),+or the JSON file `<PREFIX>_CLIENT_CONFIG_PATH` names, holding `client_id` and+`client_secret` and nothing else. Configuration wins where both are set. With+neither, the service is shown as not set up on this server, and people are told+to ask whoever runs it; a file set but unusable stops the server, and a saved+row that cannot be used leaves the service not set up, with the reason on the+operator's page. A saved client is checked with the vendor before it is stored+and is in use at once. Each connection records the client it signed in through+(`service_connections.oauth_client_id`), so one made through a client the+operator has since replaced is told to reconnect rather than refused by the+vendor.## Tokens@@ -122,7 +132,7 @@ hour. A token already handed out stays valid at the vendor until it expires.## ConnectingRoutes under `/gateway/service-connections/{service}/flows`: start, authorize,-callback (GET, then the POST relay), complete, status, confirm and cancel.+callback, complete, status and drop.Switch Console starts a flow with a one-time state, its listener's port and acompletion secret. Core keeps the PKCE verifier and exchanges the code, soneither Console nor the browser holds a token. The browser comes back the first@@ -130,16 +140,23 @@ way the catalog allows that this server can offer:- **loopback**: straight to Console's listener on 127.0.0.1. With`loopback_ports`, only on one of them; Console listens on the first free one.-- **core**: to Core's callback (needs `GATEWAY_PUBLIC_URL`), which shows whose- Switch account the sign-in will join and relays the code to Console's- listener. A cookie set as the browser left through Core ties it to that- browser.--Console posts the code back with its completion secret; Core exchanges it and-reads the account; the connection is written through `broker.connect()` only-when Console confirms. The consent recorded is what the vendor granted: write-where every write scope was granted, else read. Flows live in memory: ten-minutes each, at most 256, one per person.+- **core**: to Core's callback (needs `GATEWAY_PUBLIC_URL`), which sends the+ browser straight on to Console's listener with the code. A cookie set as the+ browser left through Core ties it to that browser, and the callback takes a+ flow's code once; a page is shown only when the return cannot be verified+ or the consent was cancelled.++Console's listener brings Console to the front as the code arrives, and+posts it back with the completion secret; in that one step Core exchanges+it, reads the account, refuses an account already linked to another person+in the workspace, and writes the connection through `broker.connect()`.+There is no confirm step: the person chose the account at the vendor. The+flow then reads `connected` (with the account and any warning) or `failed`+(with the reason), holding no token, until Console drops it or it expires.+The consent recorded is what the vendor granted: write where every write+scope was granted, else read. Flows are rows in `sign_in_flows`, so any+process can take any step: ten minutes each, at most 256 per workspace, one+per person.A dynamically registered client is the deployment's own, kept in`service_oauth_clients` (one row per service, encrypted with the keyring,@@ -223,6 +240,23 @@ as its owner there, that off stops its sessions within a minute, and, for atoken that lives longer, that a token already handed out stays valid until itexpires or the owner disconnects.+`GET /gateway/service-connections/{service}/agents` lists the caller's own+agents in the workspace, each with whether it holds a grant on the service and+whether others can address it, for the "used by" list and the checklist+Console offers after connecting. Another member's agents never appear; an+unknown or placeholder slug is 404.++"Others can address it" (`addressing_open`, here and on the agent's grants+list) is false only for owner-only in its strict sense: the owner alone, in+person. Any agent sender counts as someone else, the owner's own agents+included, so "you and your agents" (`owner_agents`) and any named agent make it+true. An agent is not the person: whoever addressed the owner's other agent can+have it pass the request on, and the grant is then used for them. This is what+Console reports and warns about; it does not refuse the agent-to-agent path,+which an `owner_agents` rule still admits. Carrying the originating person on+agent-to-agent messages, so that "you and your agents" can be safe for an agent+with grants, is a later follow-up.+## Switching connections onThe whole feature is behind the `service_connections` feature flag@@ -240,6 +274,35 @@ the boot-time GitHub move and the token upkeep run either way.reason and cannot be connected, granted or issued a token (403 `forbidden`);disconnecting still works. A slug outside the catalog stops the server.+## Switching a service on for a workspace++A workspace admin switches each catalog service on or off for the workspace+(`GET` and `PUT /gateway/workspace/services[/{service}]`, admins and owners,+and the operator in a workspace they belong to). A service with no setting is+on, so an upgraded server behaves as before; a row is written only when an+admin touches the switch, and each change is audited+(`workspace_service.enabled` / `.disabled`). The switch applies only with the+`service_connections` flag on; with it off, GitHub works as it always has.+The list carries `connected_members` and `granted_agents`, what Console shows+before an admin confirms switching off.++Off, nobody in the workspace can start a sign-in, paste a key, connect, grant+or be issued a token for the service: 403 `forbidden`, "Datadog is not enabled+in this workspace. Ask a workspace admin; they switch it on under Connectors in+Switch Console." The server's own `DISABLED_SERVICES` reason is checked first.+A sign-in that completes after the switch is refused and revoked at the+vendor. Grants are kept, but the grants list a session reads leaves the+service out, so a running session loses the service within half a minute, as+it does a removed grant: its host restarts it without the service. A token+already handed out may be used until that restart, except GitHub's, which the+switch queues and revokes before it answers (`warning` when some could not be+yet; the five-minute tick keeps trying). On again, the grants come back with+no re-grant.++The service list (`GET /gateway/service-connections`) carries+`workspace_enabled` per service, `true` for every service when the flag is+off.+## KeysFor a vendor whose people connect with a key rather than a sign-in (Datadog,@@ -319,8 +382,8 @@ one of three shapes. Pick the first that fits:1. **A remote MCP server with OAuth** (Atlassian): `adapter: oauth` with `mcp`.Where the vendor offers dynamic client registration, nothing is set up onthe server (`registration: dynamic`); otherwise each server's operator- registers an OAuth app and names it in `<PREFIX>_CLIENT_CONFIG_PATH`- (`registration: static`).+ registers an OAuth app and saves it under Connectors in the dashboard,+ or names it in `<PREFIX>_CLIENT_CONFIG_PATH` (`registration: static`).2. **A command-line tool with OAuth** (Google Workspace): `adapter: oauth` with`cli`, a pinned release per platform with its SHA-256, and the allow anddeny lists that keep it to the vendor's own commands.@@ -390,9 +453,10 @@ Built from a spike against a test Workspace with an Internal app:- **Its own client per server.** Each server's operator registers an internalGoogle app, a Web client whose redirect is Core's callback,`<GATEWAY_PUBLIC_URL>/gateway/service-connections/google-workspace/flows/callback`,- and names its settings in `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`- ([operator setup](../old/google-workspace-setup.md)). Unset, Google Workspace- is listed as not set up on this server.+ and saves it under Connectors in the dashboard, or names its settings in+ `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`+ ([operator setup](../old/google-workspace-setup.md)). Without either, Google+ Workspace is listed as not set up on this server.- **Offline access.** Google returns a refresh token only for`access_type=offline`, and on a later sign-in only with `prompt=consent`;both go with every authorization. Refresh tokens are reusable.@@ -433,11 +497,16 @@ as unavailable through its own deployment settings, not this repository:`DISABLED_SERVICES` `{"google-workspace": "<the reason people see>"}`.To roll back: add `google-workspace` to `DISABLED_SERVICES`, set the entry's-`enabled: false`, or unset `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`. Each lists+`enabled: false`, or remove its client (under Connectors, or by unsetting+`GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`). Each listsit as unavailable, with its reason, and the next token request fails.## Not yet+- Shared workspace connections, and a per-workspace OAuth client: every+ connection is a person's own, and every workspace signs in through the+ deployment's one client per vendor. A workspace's switch only turns a+ service on or off.- `grants.changed` on the agent and controller streams: a grant change reachesa running session within half a minute, by the host reading the grantsagain, not at once.diff --git a/docs/old/github-app-setup.md b/docs/old/github-app-setup.mdnew file mode 100644index 000000000..fcefebd10--- /dev/null+++ b/docs/old/github-app-setup.md@@ -0,0 +1,120 @@+# GitHub on a self-hosted server++People connect their GitHub account through a GitHub App the server's+operator creates, and grant agents repositories of the App's installations.+An agent's token is an installation token for exactly the repositories+granted, acting as the App, and lasts at most an hour. How it works is in+[`docs/design/service-connections-v2.md`](../design/service-connections-v2.md).++Without the App, GitHub is listed on the server as "GitHub is not set up on+this server. Ask whoever runs your Switch server to add it under Connector+apps in the Switch dashboard."++## What you need++- The server's **`GATEWAY_PUBLIC_URL`**, an `https://` address: GitHub sends+ each sign-in back to it.+- A GitHub account or organization to own the App. An App owned by an+ organization keeps working when the person who created it leaves.++## Create the App++In GitHub: Settings, Developer settings, GitHub Apps, **New GitHub App** (for+an organization, under the organization's settings).++1. **Callback URL**:+ ```+ <GATEWAY_PUBLIC_URL>/gateway/provider-connections/github/callback+ ```+ for example+ `https://switch.example.com/gateway/provider-connections/github/callback`.+2. Turn on **Expire user authorization tokens**. Switch keeps each person's+ sign-in fresh with its refresh token, and refuses a sign-in that does not+ expire.+3. Under **Repository permissions**, set **Contents** and **Pull requests** to+ **Read and write** (Metadata is read-only, and always on). These are the+ most an agent's token can carry, as the catalog's `github` entry lists them;+ a read grant asks for read only.+4. Choose who can install it: only this account, or any account if people+ will install it on their own organizations.+5. Create the App. On its settings page, **generate a client secret** and+ **generate a private key** (a `.pem` file, downloaded once).++## Give Switch the App++In Switch Console, open **Admin** in the sidebar and **Connector apps** under+Server, or in the Switch dashboard open **Connectors** beside Users. Both are+shown to the server's operator only, and only with the server's+`service_connections` flag on. Choose **Set up GitHub**. The dialog shows the+callback URL to register, with a copy button. Paste the App's **Client ID**+and **Client secret**, and choose the **Private key** file; it is read in your+browser and never shown. Then choose **Check and save**.++Switch asks GitHub first: it signs a request with the private key as the App+named by the client ID, which proves the two belong to one App and tells+Switch the App's name, so you never type it; and it tells a right client+secret from a wrong one. Nothing is saved unless GitHub accepts all three.+The secret and the key are stored encrypted, like every other stored+credential (see [key rotation](key-rotation.md)), and the App is in use at+once: nobody needs to restart anything. The card then shows the key's+fingerprint, which matches the one GitHub lists under the App's private keys,+and the App's install link to share.++People install the App on the accounts and repositories it may reach, then+connect GitHub from Switch Console.++## Rotating the secret or the key++Generate a new client secret or private key in the App's settings, then choose+**Update secret or private key** on the card and enter only what changed.+Nobody is disconnected: sign-ins belong to the App, not to its secret, and+tokens already issued stay valid until they expire, within the hour. Once the+card shows the new key's fingerprint, delete the old key at GitHub.++## Replacing the App++**Use a different app** sets up another App, with another client ID. Everyone+connected through the current App must connect again, and choose their+repositories again too, since a grant names the old App's installations. The+dialog says how many people in how many workspaces that is before anything+changes, and their connections show as needing reconnection. Tokens already+handed to agents stay valid at GitHub for up to an hour; if the old App's+secret or key leaked, delete it at GitHub as well.++**Remove** leaves GitHub not set up: nobody can connect it, and the people+connected lose it until an App is set up again. They can still disconnect.++## Or, from configuration++The App can be set in the server's configuration instead:++- `GITHUB_APP_CONFIG_PATH`: a JSON file with `client_id`, `client_secret`,+ `slug` (the App's name in its URL) and `origin` (the HTTPS address GitHub+ calls back; normally `GATEWAY_PUBLIC_URL`);+- `GITHUB_APP_PRIVATE_KEY_PATH`: the private key's `.pem`, by absolute path.++With Helm, `switchCore.githubConnectionsSecret` holds `github.json`, and+`switchCore.githubAppPrivateKeyPath` names the key inside a mounted Secret.+The two are set together or not at all, and set but unusable, switch-core+does not start.++**Configuration wins**: while it is set, Switch uses it, an App saved in the+dashboard is ignored (switch-core says so at startup, and so does the card),+and saving from the dashboard is refused. The deprecated+`HOSTED_GITHUB_CONFIG_PATH` counts as configuration too; it names no private+key, so GitHub can be connected but not granted, and it can't be copied into+Switch. Unset it, restart, and set the App up from the dashboard instead.++To move a configured App into the dashboard, choose **Manage it here+instead** on its card: **Copy into Switch** saves the configured values with+nothing retyped, then remove the two variables (or the two Helm values) and+restart switch-core. It is the same App, so nobody reconnects. Copying is+refused while the file's `origin` differs from `GATEWAY_PUBLIC_URL`, since a+saved App is called back at `GATEWAY_PUBLIC_URL`.++## Several replicas++Sign-ins in progress are kept in the database, and a change to the App+reaches every switch-core replica within seconds; one that misses the news+finds it within half a minute. Keep query strings out of every access log+in front of the callback: its URL carries a single-use OAuth code.diff --git a/docs/old/google-workspace-setup.md b/docs/old/google-workspace-setup.mdindex 74df36449..10ae6591d 100644--- a/docs/old/google-workspace-setup.md+++ b/docs/old/google-workspace-setup.md@@ -8,13 +8,15 @@ offered. How it works is in[`docs/design/service-connections-v2.md`](../design/service-connections-v2.md),under Google Workspace.-Without the app, Google Workspace is listed on the server as "Not set up on-this server. Its operator registers an internal Google app; see the docs."+Without the app, Google Workspace is listed on the server as "Google+Workspace is not set up on this server. Ask whoever runs your Switch server to+add it under Connectors in the Switch dashboard."## What you need- A **Google Workspace organization**, and an account in it that can create- Cloud projects. A personal Gmail account cannot make an Internal app.+ Cloud projects. A personal Gmail account cannot make an Internal app (see+ [Internal or External](#internal-or-external)).- The server's **`GATEWAY_PUBLIC_URL`**: the address people reach Switch at.Google sends each sign-in back to it. It must be `https://`, or`http://localhost:<port>` for a server on your own computer, which Google@@ -36,9 +38,8 @@ available APIs.```3. **Set up the consent screen** under Google Auth Platform: give the app aname people will recognise (it is what Google's consent page shows), and set- the audience to **Internal**. An Internal app is used only within your- organization, needs no Google verification, and keeps refresh tokens alive- beyond the seven days an External app in Testing gets.+ the audience to **Internal**, unless people outside your organization will+ connect (see [Internal or External](#internal-or-external)).4. **Create a client** under Google Auth Platform, Clients: type **Webapplication**, with one authorized redirect URI:```@@ -50,8 +51,56 @@ available APIs.control, API controls. Depending on your organization's settings, aninternal app may need to be marked trusted there.+## Internal or External++The consent screen's audience decides who can connect, and what Google asks of+the app first. Switch cannot tell which a client is, and works with either.++- **Internal**: only people in your Google organization can connect. Google+ does not review the app, and refresh tokens last as long as your+ organization's policies let them. This is the one to choose when everyone+ who will connect is in the organization.+- **External**: anyone with a Google account can connect, but only once Google+ has verified the app. Switch asks to read and change Drive files, which+ Google counts as restricted, so verification includes a security assessment+ renewed every year. Until the app is verified it stays in Testing: only the+ test users you list can connect, and their sign-ins lapse after seven days,+ so they reconnect every week.+## Give Switch the client+In Switch Console, open **Admin** in the sidebar and **Connector apps** under+Server, or in the Switch dashboard open **Connectors** beside Users. Both are+shown to the server's operator only, and only with the server's+`service_connections` flag on. Choose **Set up Google Workspace**. The dialog+shows the redirect URI to register, with a copy button; paste the client's+**Client ID** and **Client secret** as Google Cloud labels them, and choose+**Check and save**. Switch first asks Google whether the two belong together+(and, where Google says so, whether the redirect URI is registered), and+saves only if they do. The secret is stored encrypted, like every other+stored credential (see [key rotation](key-rotation.md)), and is in use at+once: nobody needs to restart anything.++From then on the card offers:++- **Check it works**: asks Google again, and stores nothing.+- **Update secret**: a new secret for the same client, after rotating it in+ Google Cloud. Nobody is disconnected.+- **Use a different app**: a client with another id. Everyone connected+ through the current client must reconnect, and the dialog says how many+ people in how many workspaces that is before anything changes. Tokens+ already handed to agents stay valid at Google for up to an hour; if the old+ client's secret leaked, delete it in Google Cloud too.+- **Remove**: nobody can connect Google Workspace, and the people connected+ lose it until a client is set up again. They can still disconnect.++### Or, from configuration++The client can be set in the server's configuration instead, as before.+**Configuration wins**: while it is set, Switch uses it, a client saved in the+dashboard is ignored (switch-core says so at startup, and so does the card),+and saving from the dashboard is refused.+Write the client's id and secret to a JSON file on the server, readable byswitch-core alone and never committed anywhere:@@ -70,6 +119,12 @@ GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH=/etc/switch/google-workspace-client.jsonIf the variable is set but the file cannot be read or holds anything else,switch-core does not start, and says why.+To move a configured client into the dashboard, choose **Manage it here+instead** on its card: **Copy into Switch** saves the configured values with+nothing retyped, then remove `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH` (with Helm,+`switchCore.googleWorkspaceClientSecret`) and restart switch-core. It is the+same client, so nobody reconnects.+## What people do1. In Switch Console: Settings, Connections, Google Workspace, Connect. The@@ -100,7 +155,9 @@ agents' next token requests:- add it to `DISABLED_SERVICES`, e.g.`DISABLED_SERVICES='{"google-workspace": "Paused while we review access."}'`;-- unset `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`.+- remove its client under Connectors in the dashboard;+- unset `GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH`, where it is set from+ configuration.Switch's own hosted service does the first in its deployment settings untilits app has passed Google's review.diff --git a/docs/old/key-rotation.md b/docs/old/key-rotation.mdindex 9c9f7b12a..f9d6d1e96 100644--- a/docs/old/key-rotation.md+++ b/docs/old/key-rotation.md@@ -18,7 +18,7 @@ the purpose, so a key that leaks from one use does not open another.| OIDC login cookie | signed cookie | one login round trip (10 minutes) | current key only; a login in progress at the moment of rotation starts again || Messaging install state | signed token | one install round trip | verified with any key in `SECRET_KEYS` || Mattermost card buttons | signed context in posted messages | as long as the post | verified with any key in `SECRET_KEYS` |-| Stored credentials: API keys, hosted-install bot tokens, bridge and connector configs | encrypted, value names its key | until changed | re-encrypted under the current key at boot |+| Stored credentials: API keys, hosted-install bot tokens, bridge and connector configs, connector app credentials | encrypted, value names its key | until changed | re-encrypted under the current key at boot |The first key is used for everything new. Older keys only verify and decrypt.diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsxindex 774753feb..dbb8d490c 100644--- a/gateway/src/App.test.tsx+++ b/gateway/src/App.test.tsx@@ -106,6 +106,26 @@ describe("AppRoutes", () => {expect(await screen.findByRole("heading", { name: "Acme" })).toBeTruthy();expect(screen.getByRole("link", { name: /Workspace/ })).toBeTruthy();expect(screen.queryByRole("link", { name: /Users/ })).toBeNull();+ expect(screen.queryByRole("link", { name: /Connectors/ })).toBeNull();+ });++ 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 },+ }),+ ],+ "/connector-apps": [200, { public_url: "https://switch.example.test", apps: [] }],+ });+ renderAt("/connectors");+ expect(await screen.findByRole("heading", { name: "Connectors" })).toBeTruthy();+ expect(screen.getByRole("link", { name: /Users/ })).toBeTruthy();+ expect(screen.getByRole("link", { name: /Connectors/ })).toBeTruthy();});it("puts a pending invite before everything else", async () => {diff --git a/gateway/src/App.tsx b/gateway/src/App.tsxindex 328a38431..bb4c3d863 100644--- a/gateway/src/App.tsx+++ b/gateway/src/App.tsx@@ -7,6 +7,7 @@ import AgentDetailPage from "./pages/agents/AgentDetailPage";import AgentsPage from "./pages/agents/AgentsPage";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";@@ -141,6 +142,7 @@ export function AppRoutes() {<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><Route path="/invite" element={<InviteCapture />} />diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 336d892d4..8603e8ec5 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -2208,6 +2208,8 @@ export interface ServiceConnection {connectable: boolean;/** Why the service cannot be granted to agents on this server; null when it can. */unavailable_reason: string | null;+ /** Whether it waits on the server's operator setting up its app under Connectors. */+ server_setup_needed: boolean;status: "not_connected" | "active" | "needs_reauthorization" | "error";/** Whether a grant hands the agent the owner's own token: on or off, at the connection's level. */pass_through: boolean;@@ -2288,3 +2290,141 @@ export const OWNER_ONLY_POLICY: AddressingPolicy = {},],};++// ── Connector app credentials (the server's operator only) ───────────────++export type ConnectorAppKind = "github_app" | "oauth_client";+export type ConnectorAppField = "client_id" | "client_secret" | "private_key";++/** Whether a secret is set, and how the operator recognises it; never the secret. */+export interface ConnectorAppSecret {+ set: boolean;+ /** A client secret's last four characters. */+ last4?: string | null;+ /** A private key's SHA-256 fingerprint, as GitHub lists it. */+ fingerprint?: string | null;+}++/** The app one connector signs in through, and where it comes from. */+export interface ConnectorApp {+ slug: string;+ name: string;+ kind: ConnectorAppKind;+ source: "configuration" | "saved" | "none";+ /** The variables that set it from configuration. */+ configuration_variables: string[];+ /** GitHub's HOSTED_GITHUB_CONFIG_PATH: no private key, so it can't be copied. */+ deprecated: boolean;+ client_id: string | null;+ /** The client saved here, when there is one. */+ saved_client_id: string | null;+ fields: { slug?: string | null };+ secrets: Record<string, ConnectorAppSecret>;+ /** Saved here, but configuration is set, so Switch uses that. */+ saved_ignored: boolean;+ /** Saved here under a key the server no longer has. */+ unreadable: boolean;+ /** Why the app saved here can't be used. */+ load_error: string | null;+ /** Where the vendor sends people back to Switch; null without a GATEWAY_PUBLIC_URL it accepts. */+ redirect_uri: string | null;+ /** Why it can't be set up here, before any vendor is asked; null when nothing stops it. */+ setup_blocked: string | null;+ install_url: string | null;+ updated_by_name: string | null;+ updated_at: string | null;+ connected_members: number;+ workspaces: number;+ /** Connections made through an app this server no longer uses. */+ stale_connections: number;+}++/** The server's connector apps; a service that needs no app of the operator's is not listed. */+export interface ConnectorApps {+ public_url: string | null;+ apps: ConnectorApp[];+}++export interface ConnectorAppCheck {+ name: string;+ ok: boolean;+ message: string;+ field: ConnectorAppField | null;+}++export interface SaveConnectorAppInput {+ client_id: string;+ client_secret?: string;+ private_key?: string;+ /** Switching to another app on purpose: everyone connected must reconnect. */+ replace: boolean;+}++export interface ConnectorAppImpact {+ connected_members: number;+ workspaces: number;+}++/** A save the vendor refused: what it said, and the value to look at again. */+export class ConnectorAppRefusal extends ApiError {+ readonly field: ConnectorAppField | null;++ constructor(status: number, message: string, field: ConnectorAppField | null) {+ super(status, message, message);+ this.name = "ConnectorAppRefusal";+ this.field = field;+ }+}++/** 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.";++export async function fetchConnectorApps(): Promise<ConnectorApps> {+ return jsonRequest<ConnectorApps>("/connector-apps", "GET");+}++export async function saveConnectorApp(+ service: string,+ input: SaveConnectorAppInput,+): Promise<ConnectorApp> {+ const res = await fetch(`${BASE}/connector-apps/${service}`, {+ method: "PUT",+ credentials: "include",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ });+ const payload = await res.json().catch(() => null);+ if (!res.ok) {+ const detail = payload?.detail ?? null;+ const message = errorText(detail, `${res.status} ${res.statusText}`);+ if (res.status === 422 && payload && "checks" in payload) {+ throw new ConnectorAppRefusal(res.status, message, payload.field ?? null);+ }+ throw new ApiError(res.status, detail, message);+ }+ return payload as ConnectorApp;+}++export async function importConnectorApp(service: string): Promise<ConnectorApp> {+ return jsonRequest<ConnectorApp>(`/connector-apps/${service}/import`, "POST");+}++export async function checkConnectorApp(+ service: string,+): Promise<{ ok: boolean; checks: ConnectorAppCheck[] }> {+ return jsonRequest(`/connector-apps/${service}/check`, "POST");+}++export async function fetchConnectorAppImpact(+ service: string,+ clientId: string,+): Promise<ConnectorAppImpact> {+ const params = new URLSearchParams({ client_id: clientId });+ return jsonRequest<ConnectorAppImpact>(`/connector-apps/${service}/impact?${params}`, "GET");+}++export async function removeConnectorApp(service: string): Promise<ConnectorAppImpact> {+ return jsonRequest<ConnectorAppImpact>(`/connector-apps/${service}`, "DELETE");+}diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex ee28d38e2..a652b1bdc 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -1,5 +1,9 @@import { useCallback, useEffect, useState } from "react";import {+ ApiError,+ CONNECTORS_NOT_ENABLED,+ type ConnectorApps,+ fetchConnectorApps,type AgentDetail,type AgentSummary,type Budget,@@ -181,6 +185,44 @@ export function useKnownAgentTypes(): UseQueryResult<KnownAgentType[]> {return useQuery(fetchKnownAgentTypes);}+/** The server's connector apps; the operator's only, so call it only for them. */+export function useConnectorApps(): UseQueryResult<ConnectorApps> {+ const [data, setData] = useState<ConnectorApps | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [tick, setTick] = useState(0);+ const refetch = useCallback(() => setTick((t) => t + 1), []);++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ fetchConnectorApps().then(+ (result) => {+ if (cancelled) return;+ setData(result);+ setError(null);+ setLoading(false);+ },+ (err: unknown) => {+ if (cancelled) return;+ setError(+ err instanceof ApiError && err.status === 404+ ? CONNECTORS_NOT_ENABLED+ : err instanceof Error+ ? err.message+ : String(err),+ );+ setLoading(false);+ },+ );+ return () => {+ cancelled = true;+ };+ }, [tick]);++ return { data, loading, error, refetch };+}+export function useUsers(): UseQueryResult<UserInfo[]> {return useQuery(fetchUsers);}diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsxindex 9458bd82e..1a603187e 100644--- a/gateway/src/layout/NavRail.tsx+++ b/gateway/src/layout/NavRail.tsx@@ -3,6 +3,7 @@ import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";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";@@ -60,12 +61,21 @@ const WORKSPACE_ADMIN_ITEMS: NavItem[] = [{ label: "Usage", path: "/usage", icon: DataUsageOutlined },];-const ADMIN_ITEMS: NavItem[] = [{ label: "Users", path: "/users", icon: PeopleOutlined }];+const ADMIN_ITEMS: NavItem[] = [+ { label: "Users", path: "/users", icon: PeopleOutlined },+ { label: "Connectors", path: "/connectors", icon: PowerOutlined },+];-const TARGET = 44;+// 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.+const TARGET = "clamp(36px, 4vh, 44px)";+const ICON = "clamp(20px, 2.2vh, 22px)";+const ITEM_GAP = "clamp(4px, 1.4vh, 16px)";+const LABEL = "clamp(0.6875rem, 1.05vh, 0.75rem)";// The logo sits slightly inside the nav button footprint: it is a solid mark// against thin-stroke icons, so matching the container would read as heavier.-const LOGO = 28;+const LOGO = "clamp(24px, 2.6vh, 28px)";function RailItem({ item, active }: { item: NavItem; active: boolean }) {return (@@ -77,7 +87,7 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {display: "flex",flexDirection: "column",alignItems: "center",- gap: 0.5,+ gap: 0.25,textDecoration: "none",color: "text.primary",opacity: active ? 1 : 0.75,@@ -94,7 +104,7 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {justifyContent: "center",width: TARGET,height: TARGET,- borderRadius: "16px",+ borderRadius: "12px",// The active indicator is a subtle vertical gradient pill with a// whisper of lift — never a filled accent....(active && {@@ -104,10 +114,10 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {}),}}>- <item.icon sx={{ fontSize: 22, strokeWidth: 1.5 }} />+ <item.icon sx={{ fontSize: ICON, strokeWidth: 1.5 }} /></Box><Typography- sx={{ fontSize: "0.75rem", lineHeight: 1, fontWeight: 500, letterSpacing: "-0.01em" }}+ sx={{ fontSize: LABEL, lineHeight: 1, fontWeight: 500, letterSpacing: "-0.01em" }}>{item.label}</Typography>@@ -165,8 +175,9 @@ export default memo(function NavRail() {sx={{width: "var(--nav-rail-width)",flexShrink: 0,+ minHeight: 0,alignItems: "center",- py: 2,+ py: 1.5,color: "text.primary",}}>@@ -209,9 +220,23 @@ export default memo(function NavRail() {</Box></Tooltip>- <Divider sx={{ my: 2, width: 29 }} />+ <Divider sx={{ my: 1.5, width: 29 }} />- <Stack sx={{ width: "100%", alignItems: "center", gap: 2 }}>+ <Stack+ sx={{+ width: "100%",+ alignItems: "center",+ gap: ITEM_GAP,+ // On a window shorter still, the items scroll and the account+ // button stays put; the rail is too narrow for a scrollbar.+ flex: 1,+ minHeight: 0,+ overflowY: "auto",+ overflowX: "hidden",+ scrollbarWidth: "none",+ "&::-webkit-scrollbar": { display: "none" },+ }}+ >{items.map((item) => (<RailItemkey={item.path}@@ -221,7 +246,7 @@ export default memo(function NavRail() {))}</Stack>- <Stack sx={{ mt: "auto", width: "100%", alignItems: "center", gap: 2, pt: 2 }}>+ <Stack sx={{ width: "100%", alignItems: "center", gap: 2, pt: 2 }}><Boxcomponent="button"onClick={(e: MouseEvent<HTMLElement>) => setAnchor(e.currentTarget)}diff --git a/gateway/src/pages/agents/ServiceAccessSection.test.tsx b/gateway/src/pages/agents/ServiceAccessSection.test.tsxindex 52b82b8fe..b01a90d41 100644--- a/gateway/src/pages/agents/ServiceAccessSection.test.tsx+++ b/gateway/src/pages/agents/ServiceAccessSection.test.tsx@@ -1,4 +1,5 @@import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { MemoryRouter } from "react-router";import { afterEach, describe, expect, it, vi } from "vitest";import {type AgentDetail,@@ -6,8 +7,13 @@ import {type ServiceConnection,type ServiceGrants,} from "../../data/api";+import { useAuth } from "../../data/AuthContext";import ServiceAccessSection from "./ServiceAccessSection";+vi.mock("../../data/AuthContext", () => ({+ useAuth: vi.fn(() => ({ isOperator: false })),+}));+const agent: AgentDetail = {id: "a1",name: "helper",@@ -173,6 +179,7 @@ describe("ServiceAccessSection", () => {enabled: true,connectable: true,unavailable_reason: null,+ server_setup_needed: false,status,pass_through: true,token_lifetime: 3600,@@ -267,4 +274,45 @@ describe("ServiceAccessSection", () => {expect(screen.getByText("Coming to this server soon.")).toBeTruthy();expect((screen.getByLabelText("Other for helper") as HTMLInputElement).disabled).toBe(true);});++ 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.";++ 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()} />);+ 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>);+ });++ 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.";+ mockServer(NONE, [+ onOff("not_connected", {+ slug: "github",+ name: "GitHub",+ pass_through: false,+ unavailable_reason: reason,+ server_setup_needed: true,+ }),+ ]);+ render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);+ expect(await screen.findByText(reason)).toBeTruthy();+ });});diff --git a/gateway/src/pages/agents/ServiceAccessSection.tsx b/gateway/src/pages/agents/ServiceAccessSection.tsxindex 9425bf969..73e0fbace 100644--- a/gateway/src/pages/agents/ServiceAccessSection.tsx+++ b/gateway/src/pages/agents/ServiceAccessSection.tsx@@ -16,6 +16,7 @@ import {Typography,} from "@mui/material";import { useCallback, useEffect, useState } from "react";+import { Link as RouterLink } from "react-router";import {type AgentDetail,ApiError,@@ -32,6 +33,7 @@ import {setServiceGrant,updateAgentAddressingPolicy,} from "../../data/api";+import { useAuth } from "../../data/AuthContext";type Access = "read" | "write";@@ -86,6 +88,7 @@ export default function ServiceAccessSection({const [notice, setNotice] = useState<string | null>(null);const [editing, setEditing] = useState(false);const [busy, setBusy] = useState(false);+ const { isOperator } = useAuth();const load = useCallback(async () => {try {@@ -132,6 +135,7 @@ export default function ServiceAccessSection({// Services whose agents use the owner's own token: on or off, nothing to choose.const onOff = services.filter((service) => service.enabled && service.pass_through);const onOffSlugs = new Set(onOff.map((service) => service.slug));+ const githubService = services.find((service) => service.slug === "github") ?? null;return (<>@@ -225,6 +229,7 @@ export default function ServiceAccessSection({grant={grants.grants.find((grant) => grant.service === service.slug) ?? null}agentName={agent.name}busy={busy}+ canSetUp={isOperator}onTurnOn={() =>void act(() => setServiceGrant(agent.id, service.slug, { access: null, resources: {} }))}@@ -236,6 +241,8 @@ export default function ServiceAccessSection({<GitHubGrantFormgithub={github}githubError={githubError}+ notSetUp={githubService?.server_setup_needed ? githubService.unavailable_reason : null}+ canSetUp={isOperator}current={githubGrant}busy={busy}onCancel={githubGrant ? () => setEditing(false) : null}@@ -276,12 +283,22 @@ export function onOffGrantNote(: note;}+/** The operator's way from a service that is not set up to where it is set up. */+function SetUpLink() {+ return (+ <Button component={RouterLink} to="/connectors" size="small" sx={{ ml: 1 }}>+ Set up+ </Button>+ );+}+/** A service whose agents use the owner's own token: on or off, at the connection's level. */function OnOffGrant({service,grant,agentName,busy,+ canSetUp,onTurnOn,onTurnOff,}: {@@ -289,6 +306,7 @@ function OnOffGrant({grant: ServiceGrant | null;agentName: string;busy: boolean;+ canSetUp: boolean;onTurnOn: () => void;onTurnOff: () => void;}) {@@ -317,6 +335,7 @@ function OnOffGrant({{service.unavailable_reason && (<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>{service.unavailable_reason}+ {canSetUp && service.server_setup_needed && <SetUpLink />}</Typography>)}{!grant && !connected && !service.unavailable_reason && (@@ -334,6 +353,8 @@ function OnOffGrant({function GitHubGrantForm({github,githubError,+ notSetUp,+ canSetUp,current,busy,onCancel,@@ -341,6 +362,9 @@ function GitHubGrantForm({}: {github: GitHubConnection | null;githubError: string | null;+ /** Why GitHub is not set up on this server, when its App is not. */+ notSetUp: string | null;+ canSetUp: boolean;current: ServiceGrant | null;busy: boolean;onCancel: (() => void) | null;@@ -356,6 +380,13 @@ function GitHubGrantForm({current ? repositoryIds(current.resources) : [],);+ if (notSetUp)+ return (+ <Typography variant="body2" color="text.secondary">+ {notSetUp}+ {canSetUp && <SetUpLink />}+ </Typography>+ );if (githubError) return <Alert severity="error">{githubError}</Alert>;if (github === null) return <CircularProgress size={20} />;if (github.status === "not_connected")diff --git a/gateway/src/pages/connector-apps/ConnectorAppCard.tsx b/gateway/src/pages/connector-apps/ConnectorAppCard.tsxnew file mode 100644index 000000000..8a8e52850--- /dev/null+++ b/gateway/src/pages/connector-apps/ConnectorAppCard.tsx@@ -0,0 +1,343 @@+import CheckBoxOutlineBlankOutlined from "@mui/icons-material/CheckBoxOutlineBlankOutlined";+import CheckBoxOutlined from "@mui/icons-material/CheckBoxOutlined";+import MoreHorizOutlined from "@mui/icons-material/MoreHorizOutlined";+import {+ Alert,+ Box,+ Button,+ Chip,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ IconButton,+ Menu,+ MenuItem,+ Paper,+ Stack,+ Typography,+} from "@mui/material";+import { useState } from "react";+import {+ type ConnectorApp,+ type ConnectorAppCheck,+ checkConnectorApp,+ importConnectorApp,+} from "../../data/api";+import { formatDate } from "../../theme/hootFormat";+import {+ actionLabel,+ attention,+ type CardAction,+ cardState,+ type CardState,+ configuredSentence,+ type MenuAction,+ menuActions,+ menuLabel,+ moveChecklist,+ notSetUpSentence,+ primaryAction,+ secretSummary,+ stateLabel,+ usedBy,+} from "./connectorApps";+import RemoveDialog from "./RemoveDialog";+import SetupDialog, { type SetupMode } from "./SetupDialog";+import UpdateSecretDialog from "./UpdateSecretDialog";++const CHIP_COLOR: Record<CardState, "success" | "default" | "warning"> = {+ ready: "success",+ not_set_up: "default",+ configured: "success",+ attention: "warning",+};++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++function Row({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <Stack direction="row" spacing={2}>+ <Typography variant="body2" color="text.secondary" sx={{ width: 90, flexShrink: 0 }}>+ {label}+ </Typography>+ <Typography variant="body2" sx={{ wordBreak: "break-all" }}>+ {children}+ </Typography>+ </Stack>+ );+}++/** Moving off configuration: copy in, remove the variable, restart. */+function ManageHereDialog({+ app,+ open,+ onClose,+ onImported,+}: {+ app: ConnectorApp;+ open: boolean;+ onClose: () => void;+ onImported: (imported: ConnectorApp) => void;+}) {+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const items = moveChecklist(app);++ const copy = async () => {+ setBusy(true);+ setError(null);+ try {+ onImported(await importConnectorApp(app.slug));+ } catch (err) {+ setError(errorText(err));+ } finally {+ setBusy(false);+ }+ };++ return (+ <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">+ <DialogTitle>Manage {app.name} here instead</DialogTitle>+ <DialogContent>+ <Stack spacing={1.5}>+ {items.map((item, index) => (+ <Stack key={item.text} direction="row" spacing={1} alignItems="flex-start">+ {item.done ? (+ <CheckBoxOutlined fontSize="small" color="success" aria-label="Done" />+ ) : (+ <CheckBoxOutlineBlankOutlined fontSize="small" aria-label="To do" />+ )}+ <Box sx={{ flexGrow: 1 }}>+ <Typography variant="body2">{item.text}</Typography>+ {index === 0 && !item.done && (+ <Button+ size="small"+ variant="outlined"+ sx={{ mt: 0.5 }}+ disabled={busy}+ onClick={() => void copy()}+ >+ Copy into Switch+ </Button>+ )}+ </Box>+ </Stack>+ ))}+ <Typography variant="body2" color="text.secondary">+ Nobody needs to reconnect: Switch keeps using the same app.+ </Typography>+ {error && <Alert severity="error">{error}</Alert>}+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={onClose}>Close</Button>+ </DialogActions>+ </Dialog>+ );+}++/**+ * One connector's app: is it working, and what to do next, with one obvious+ * button. Changes that disconnect people are apart from those that don't.+ */+export default function ConnectorAppCard({+ app,+ publicUrl,+ checkFailure,+ onCheckFailure,+ onChanged,+}: {+ app: ConnectorApp;+ /** GATEWAY_PUBLIC_URL; while it is unset the vendor has nowhere to send people back. */+ publicUrl: string | null;+ checkFailure: string | null;+ onCheckFailure: (message: string | null) => void;+ onChanged: (message: string) => void;+}) {+ const [menu, setMenu] = useState<HTMLElement | null>(null);+ const [setup, setSetup] = useState<SetupMode | null>(null);+ const [updating, setUpdating] = useState(false);+ const [removing, setRemoving] = useState(false);+ const [managing, setManaging] = useState(false);+ const [checks, setChecks] = useState<ConnectorAppCheck[] | null>(null);+ const [checking, setChecking] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const state = cardState(app, checkFailure);+ const needs = attention(app, checkFailure);+ const primary = primaryAction(app, checkFailure);+ const actions = menuActions(app);+ const summary = secretSummary(app);+ const blocked = publicUrl === null || app.setup_blocked !== null;++ const check = async () => {+ setChecking(true);+ setError(null);+ try {+ const result = await checkConnectorApp(app.slug);+ setChecks(result.checks);+ onCheckFailure(result.ok ? null : (result.checks.find((c) => !c.ok)?.message ?? null));+ } catch (err) {+ setError(errorText(err));+ } finally {+ setChecking(false);+ }+ };++ const run = (action: CardAction) => {+ if (action === "check") void check();+ else if (action === "set_up") setSetup("set_up");+ else if (action === "enter_again") setSetup("enter_again");+ else if (action === "manage_here") setManaging(true);+ else setUpdating(true);+ };++ const choose = (action: MenuAction) => {+ setMenu(null);+ if (action === "update_secret") setUpdating(true);+ else if (action === "switch_app") setSetup("switch");+ else setRemoving(true);+ };++ const saved = (message: string) => {+ setSetup(null);+ setUpdating(false);+ setChecks(null);+ onCheckFailure(null);+ onChanged(message);+ };++ return (+ <Paper variant="outlined" sx={{ p: 2 }} data-testid={`connector-app-${app.slug}`}>+ <Stack spacing={1.25}>+ <Stack direction="row" alignItems="center" spacing={1}>+ <Typography variant="subtitle1" sx={{ flexGrow: 1, fontWeight: 600 }}>+ {app.name}+ </Typography>+ <Chip size="small" color={CHIP_COLOR[state]} label={stateLabel(state)} />+ </Stack>++ {state === "not_set_up" && (+ <Typography variant="body2" color="text.secondary">+ {notSetUpSentence(app)}+ </Typography>+ )}+ {app.source === "configuration" && (+ <Typography variant="body2" color="text.secondary">+ {configuredSentence(app)}+ {app.setup_blocked ? ` ${app.setup_blocked}` : ""}+ </Typography>+ )}+ {needs && <Alert severity={needs.cause === "stale" ? "info" : "warning"}>{needs.sentence}</Alert>}+ {needs?.cause === "saved_ignored" && app.saved_client_id && (+ <Row label="Saved here">{app.saved_client_id}</Row>+ )}++ {app.client_id && <Row label="Client ID">{app.client_id}</Row>}+ {app.fields.slug && <Row label="App">{app.fields.slug}</Row>}+ {summary && (+ <Row label="Secret">+ {summary}+ {app.updated_by_name && app.updated_at+ ? ` · updated by ${app.updated_by_name}, ${formatDate(app.updated_at)}`+ : ""}+ </Row>+ )}+ {app.source !== "none" && (+ <Typography variant="body2" color="text.secondary">+ {usedBy(app)}+ </Typography>+ )}+ {app.install_url && state !== "not_set_up" && (+ <Typography variant="body2" color="text.secondary">+ People install the App at {app.install_url}+ </Typography>+ )}++ {checks && (+ <Stack spacing={0.5}>+ {checks.map((c) => (+ <Alert key={c.name} severity={c.ok ? "success" : "error"} variant="outlined">+ {c.message}+ </Alert>+ ))}+ </Stack>+ )}+ {error && <Alert severity="error">{error}</Alert>}++ <Stack direction="row" justifyContent="flex-end" spacing={1}>+ {primary && (+ <Button+ variant={primary === "check" ? "outlined" : "contained"}+ disabled={checking || (blocked && primary !== "check")}+ onClick={() => run(primary)}+ startIcon={checking ? <CircularProgress size={16} /> : undefined}+ >+ {actionLabel(app, primary)}+ </Button>+ )}+ {actions.length > 0 && (+ <IconButton aria-label={`More for ${app.name}`} onClick={(e) => setMenu(e.currentTarget)}>+ <MoreHorizOutlined />+ </IconButton>+ )}+ </Stack>+ </Stack>++ <Menu anchorEl={menu} open={menu !== null} onClose={() => setMenu(null)}>+ {actions.map((action) => (+ <MenuItem+ key={action}+ disabled={blocked && action !== "remove"}+ onClick={() => choose(action)}+ sx={action === "remove" ? { color: "error.main" } : undefined}+ >+ {menuLabel(app, action)}+ </MenuItem>+ ))}+ </Menu>++ {setup && (+ <SetupDialog+ app={app}+ publicUrl={publicUrl}+ mode={setup}+ open+ onClose={() => setSetup(null)}+ onSaved={() => saved(`${app.name} is ready.`)}+ />+ )}+ {updating && (+ <UpdateSecretDialog+ app={app}+ open+ onClose={() => setUpdating(false)}+ onSaved={() => saved(`${app.name}'s secret is updated. Nobody was disconnected.`)}+ />+ )}+ {removing && (+ <RemoveDialog+ app={app}+ open+ onClose={() => setRemoving(false)}+ onRemoved={() => {+ setRemoving(false);+ onChanged(`${app.name}'s app is removed.`);+ }}+ />+ )}+ {managing && (+ <ManageHereDialog+ app={app}+ open+ onClose={() => setManaging(false)}+ onImported={() => onChanged(`${app.name} is copied into Switch.`)}+ />+ )}+ </Paper>+ );+}diff --git a/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx b/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsxnew file mode 100644index 000000000..328a57e02--- /dev/null+++ b/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx@@ -0,0 +1,318 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+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 { app } from "./testFixtures";++vi.mock("../../data/AuthContext", () => ({ useAuth: vi.fn() }));++const NONE_GOOGLE = app({+ source: "none",+ client_id: null,+ saved_client_id: null,+ secrets: { client_secret: { set: false, last4: null } },+ connected_members: 0,+ workspaces: 0,+ updated_by_name: null,+ updated_at: null,+});++const GITHUB = app({+ slug: "github",+ name: "GitHub",+ kind: "github_app",+ configuration_variables: ["GITHUB_APP_CONFIG_PATH", "GITHUB_APP_PRIVATE_KEY_PATH"],+ fields: { slug: "example-app" },+ secrets: {+ client_secret: { set: true, last4: "cd34" },+ private_key: { set: true, fingerprint: "SHA256:example" },+ },+ redirect_uri: "https://switch.example.test/gateway/provider-connections/github/callback",+ install_url: "https://github.com/apps/example-app/installations/new",+});++const PEM = "-----BEGIN PRIVATE KEY-----\nexample-not-a-real-key-material\n-----END PRIVATE KEY-----\n";++type Call = { path: string; method: string; body: unknown };+type Answer = [number, unknown];++function serve(list: ConnectorApps, answers: Record<string, Answer | (() => Answer)> = {}) {+ const calls: Call[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = String(input);+ const method = init?.method ?? "GET";+ calls.push({ path, method, body: init?.body ? JSON.parse(String(init.body)) : null });+ const key = `${method} ${path.split("?")[0]}`;+ const answer = answers[key] ?? (key === "GET /gateway/connector-apps" ? [200, list] : null);+ const [status, body] =+ answer === null ? [404, { detail: `unmocked ${key}` }] : typeof answer === "function" ? answer() : answer;+ return new Response(JSON.stringify(body), { status });+ }),+ );+ return calls;+}++function listOf(...apps: ConnectorApp[]): ConnectorApps {+ return {+ public_url: "https://switch.example.test",+ apps,+ };+}++function operator(isOperator = true) {+ vi.mocked(useAuth).mockReturnValue({ isOperator } as ReturnType<typeof useAuth>);+}++function card(slug: string) {+ return within(screen.getByTestId(`connector-app-${slug}`));+}++describe("ConnectorAppsPage", () => {+ beforeEach(() => operator());+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("tells anyone but the operator whose page it is, and asks nothing of the server", () => {+ operator(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.queryAllByTestId(/connector-app-/)).toEqual([]);+ });++ it("lists every app, what needs setting up first, and who sets themselves up", async () => {+ serve(listOf(GITHUB, NONE_GOOGLE));+ render(<ConnectorAppsPage />);+ expect(await screen.findByText("Not set up")).toBeTruthy();+ const cards = screen.getAllByTestId(/connector-app-/);+ expect(cards.map((c) => c.dataset.testid)).toEqual([+ "connector-app-google-workspace",+ "connector-app-github",+ ]);+ expect(card("github").getByText("Ready")).toBeTruthy();+ expect(card("github").getByText(/Secret ends in cd34 · Key SHA256:example/)).toBeTruthy();+ expect(card("github").getByText("Used by 12 people in 3 workspaces")).toBeTruthy();+ expect(card("google-workspace").getByRole("button", { name: "Set up Google Workspace" })).toBeTruthy();+ expect(screen.queryByText(PUBLIC_URL_BANNER)).toBeNull();+ expect(screen.getByText(/People are sent back to https:\/\/switch\.example\.test\./)).toBeTruthy();+ });++ it("holds GitHub's set-up when the public URL is not https, saying why", async () => {+ const blocked = "GitHub needs GATEWAY_PUBLIC_URL to be an https address, to send people back to Switch.";+ serve({+ ...listOf(+ {+ ...GITHUB,+ source: "none",+ client_id: null,+ saved_client_id: null,+ secrets: { client_secret: { set: false, last4: null }, private_key: { set: false, fingerprint: null } },+ redirect_uri: null,+ install_url: null,+ setup_blocked: blocked,+ },+ NONE_GOOGLE,+ ),+ public_url: "http://switch.example.test",+ });+ render(<ConnectorAppsPage />);+ expect(await screen.findByText(/People are sent back to http:\/\/switch\.example\.test\./)).toBeTruthy();+ expect(card("github").getByText(blocked)).toBeTruthy();+ expect(card("github").getByText("Needs attention")).toBeTruthy();+ const github = card("github").getByRole("button", { name: "Set up GitHub" });+ expect((github as HTMLButtonElement).disabled).toBe(true);+ const google = card("google-workspace").getByRole("button", { name: "Set up Google Workspace" });+ expect((google as HTMLButtonElement).disabled).toBe(false);+ });++ it("asks for GATEWAY_PUBLIC_URL first, and holds set-up until it is there", async () => {+ serve({ ...listOf(NONE_GOOGLE), public_url: null });+ render(<ConnectorAppsPage />);+ expect(await screen.findByText(PUBLIC_URL_BANNER)).toBeTruthy();+ const setUp = card("google-workspace").getByRole("button", { name: "Set up Google Workspace" });+ expect((setUp as HTMLButtonElement).disabled).toBe(true);+ });++ it("keeps a refused set-up open on the values, saying what the vendor said", async () => {+ const calls = serve(listOf(NONE_GOOGLE), {+ "PUT /gateway/connector-apps/google-workspace": [+ 422,+ {+ detail: "Google Workspace doesn't recognise this client ID and secret together.",+ field: "client_secret",+ checks: [],+ },+ ],+ });+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "Set up Google Workspace" }));+ expect(screen.getByText(audienceText("internal"))).toBeTruthy();+ fireEvent.click(screen.getByLabelText("Anyone with a Google account"));+ expect(screen.getByText(audienceText("external"))).toBeTruthy();+ expect(screen.queryByText(audienceText("internal"))).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Next" }));++ const secret = screen.getByLabelText("Client secret") as HTMLInputElement;+ expect(secret.type).toBe("password");+ expect(secret.value).toBe("");+ fireEvent.change(screen.getByLabelText("Client ID"), { target: { value: "example-client-id" } });+ fireEvent.change(secret, { target: { value: "example-wrong-secret" } });+ fireEvent.click(screen.getByRole("button", { name: "Check and save" }));++ expect(await screen.findByText(/doesn't recognise this client ID and secret/)).toBeTruthy();+ expect(screen.getByText("Step 2 of 3 · Paste its values")).toBeTruthy();+ expect(secret.getAttribute("aria-invalid")).toBe("true");+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({+ client_id: "example-client-id",+ client_secret: "example-wrong-secret",+ replace: false,+ });+ });++ it("reads GitHub's private key from its file and never shows it", async () => {+ const calls = serve(+ listOf({ ...GITHUB, ...NONE_GOOGLE, slug: "github", name: "GitHub", kind: "github_app" }),+ { "PUT /gateway/connector-apps/github": [200, GITHUB] },+ );+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "Set up GitHub" }));+ fireEvent.click(screen.getByRole("button", { name: "Next" }));+ fireEvent.change(screen.getByLabelText("Client ID"), { target: { value: "example-client-id" } });+ fireEvent.change(screen.getByLabelText("Client secret"), { target: { value: "example-secret" } });+ const file = new File([PEM], "example.pem", { type: "application/x-pem-file" });+ fireEvent.change(screen.getByLabelText("Private key"), { target: { files: [file] } });+ expect(await screen.findByText(/Private key: example.pem/)).toBeTruthy();+ expect(document.body.textContent).not.toContain("example-not-a-real-key-material");+ fireEvent.click(screen.getByRole("button", { name: "Check and save" }));+ await waitFor(() =>+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({+ client_id: "example-client-id",+ client_secret: "example-secret",+ private_key: PEM,+ replace: false,+ }),+ );+ expect(document.body.textContent).not.toContain("example-not-a-real-key-material");+ });++ it("updates a secret without disconnecting anyone", async () => {+ const calls = serve(listOf(app()), {+ "PUT /gateway/connector-apps/google-workspace": [200, app()],+ });+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "More for Google Workspace" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Update secret" }));+ expect(screen.getByText("Nobody is disconnected.")).toBeTruthy();+ fireEvent.change(screen.getByLabelText("Client secret"), { target: { value: "example-new-secret" } });+ fireEvent.click(screen.getByRole("button", { name: "Check and save" }));+ await waitFor(() =>+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({+ client_id: "example-client-id",+ client_secret: "example-new-secret",+ replace: false,+ }),+ );+ });++ it("warns before switching apps, shows who reconnects, then switches on purpose", async () => {+ const calls = serve(listOf(app()), {+ "GET /gateway/connector-apps/google-workspace/impact": [200, { connected_members: 12, workspaces: 3 }],+ "PUT /gateway/connector-apps/google-workspace": [200, app({ client_id: "another-client-id" })],+ });+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "More for Google Workspace" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Use a different app" }));+ expect(screen.getByText(/Everyone connected through the current app \(12 people in 3 workspaces\)/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ fireEvent.click(screen.getByRole("button", { name: "Next" }));+ fireEvent.change(screen.getByLabelText("Client ID"), { target: { value: "another-client-id" } });+ fireEvent.change(screen.getByLabelText("Client secret"), { target: { value: "example-secret" } });+ fireEvent.click(screen.getByRole("button", { name: "Check who reconnects" }));+ expect(await screen.findByText("12 people in 3 workspaces will need to reconnect.")).toBeTruthy();+ expect(calls.some((c) => c.method === "PUT")).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Switch app" }));+ await waitFor(() =>+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({+ client_id: "another-client-id",+ client_secret: "example-secret",+ replace: true,+ }),+ );+ });++ it("goes back a step, keeping what was entered, and never before the first", async () => {+ serve(listOf(NONE_GOOGLE));+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "Set up Google Workspace" }));+ expect(screen.queryByRole("button", { name: "Back" })).toBeNull();+ expect(screen.getByRole("link", { name: "Open Clients" }).getAttribute("href")).toBe(+ "https://console.cloud.google.com/auth/clients",+ );+ fireEvent.click(screen.getByRole("button", { name: "Next" }));+ fireEvent.change(screen.getByLabelText("Client ID"), { target: { value: "example-client-id" } });+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByText(/Step 1 of 3/)).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Back" })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Next" }));+ expect((screen.getByLabelText("Client ID") as HTMLInputElement).value).toBe("example-client-id");+ });++ it("goes back from creating the app to the warning when switching", async () => {+ serve(listOf(app()));+ render(<ConnectorAppsPage />);+ fireEvent.click(await screen.findByRole("button", { name: "More for Google Workspace" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Use a different app" }));+ expect(screen.queryByRole("button", { name: "Back" })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ expect(screen.getByText(/Step 1 of 3/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByText(/Everyone connected through the current app/)).toBeTruthy();+ });++ it("walks moving off configuration, ticking copying in once it is done", async () => {+ const configured = app({ source: "configuration", saved_client_id: null });+ let imported = false;+ const calls = serve(listOf(configured), {+ "GET /gateway/connector-apps": () => [+ 200,+ listOf(imported ? app({ source: "configuration", saved_ignored: true }) : configured),+ ],+ "POST /gateway/connector-apps/google-workspace/import": () => {+ imported = true;+ return [200, app({ source: "configuration", saved_ignored: true })];+ },+ });+ render(<ConnectorAppsPage />);+ const chip = (await screen.findByText("Set on the server")).closest(".MuiChip-root")!;+ expect(chip.className).toContain("MuiChip-colorSuccess");+ expect(chip.className).toContain("MuiChip-filled");+ expect(+ screen.getByText(+ "From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here.",+ ),+ ).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Manage it here instead" }));+ expect(screen.getAllByLabelText("To do")).toHaveLength(3);+ fireEvent.click(screen.getByRole("button", { name: "Copy into Switch" }));+ await waitFor(() => expect(screen.getAllByLabelText("Done")).toHaveLength(1));+ expect(screen.getAllByLabelText("To do")).toHaveLength(2);+ expect(calls.filter((c) => c.method === "POST")).toHaveLength(1);+ expect(+ await screen.findByText(/A copy is saved here, same client\. Remove the variable and restart Switch to use the copy\./),+ ).toBeTruthy();+ expect(screen.queryByText(/waiting for restart/)).toBeNull();+ });+});diff --git a/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx b/gateway/src/pages/connector-apps/ConnectorAppsPage.tsxnew file mode 100644index 000000000..8de79d7f0--- /dev/null+++ b/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx@@ -0,0 +1,101 @@+import { Alert, Box, CircularProgress, Snackbar, Stack, Typography } from "@mui/material";+import { useState } from "react";+import { CONNECTORS_NOT_ENABLED } from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import { useConnectorApps } from "../../data/hooks";+import ConnectorAppCard from "./ConnectorAppCard";+import {+ cardOrder,+ ONLY_THE_OPERATOR,+ PUBLIC_URL_BANNER,+ sentBackTo,+} from "./connectorApps";++function Heading({ publicUrl }: { publicUrl: string | null }) {+ return (+ <Box mb={2}>+ <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.+ {publicUrl !== null && ` ${sentBackTo(publicUrl)}`}+ </Typography>+ </Box>+ );+}++function ConnectorAppsList() {+ const { data, loading, error, refetch } = useConnectorApps();+ const [checkFailures, setCheckFailures] = useState<Record<string, string>>({});+ const [toast, setToast] = useState<string | null>(null);++ const heading = <Heading publicUrl={data?.public_url ?? null} />;+ if (loading && data === null)+ return (+ <>+ {heading}+ <CircularProgress />+ </>+ );+ if (error !== null)+ return (+ <>+ {heading}+ <Alert severity={error === CONNECTORS_NOT_ENABLED ? "info" : "error"}>{error}</Alert>+ </>+ );+ if (data === null) return heading;++ const missingUrl = data.public_url === null;+ return (+ <>+ {heading}+ <Stack spacing={2}>+ {missingUrl && <Alert severity="warning">{PUBLIC_URL_BANNER}</Alert>}+ {cardOrder(data.apps, checkFailures).map((app) => (+ <ConnectorAppCard+ key={app.slug}+ app={app}+ publicUrl={data.public_url}+ checkFailure={checkFailures[app.slug] ?? null}+ onCheckFailure={(message) =>+ setCheckFailures((current) => {+ const next = { ...current };+ if (message === null) delete next[app.slug];+ else next[app.slug] = message;+ return next;+ })+ }+ onChanged={(message) => {+ setToast(message);+ refetch();+ }}+ />+ ))}+ <Snackbar+ open={toast !== null}+ autoHideDuration={4000}+ onClose={() => setToast(null)}+ message={toast}+ />+ </Stack>+ </>+ );+}++/** The server operator's page; anyone else is told whose it is, and nothing is asked of the server. */+export default function ConnectorAppsPage() {+ const { isOperator } = useAuth();+ return (+ <Box>+ {isOperator ? (+ <ConnectorAppsList />+ ) : (+ <>+ <Heading publicUrl={null} />+ <Alert severity="info">{ONLY_THE_OPERATOR}</Alert>+ </>+ )}+ </Box>+ );+}diff --git a/gateway/src/pages/connector-apps/RemoveDialog.tsx b/gateway/src/pages/connector-apps/RemoveDialog.tsxnew file mode 100644index 000000000..f5e7f61f2--- /dev/null+++ b/gateway/src/pages/connector-apps/RemoveDialog.tsx@@ -0,0 +1,69 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+} from "@mui/material";+import { useState } from "react";+import { type ConnectorApp, removeConnectorApp } from "../../data/api";+import { removeWarning } from "./connectorApps";++export default function RemoveDialog({+ app,+ open,+ onClose,+ onRemoved,+}: {+ app: ConnectorApp;+ open: boolean;+ onClose: () => void;+ onRemoved: () => void;+}) {+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ const remove = async () => {+ setBusy(true);+ setError(null);+ try {+ await removeConnectorApp(app.slug);+ onRemoved();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ return (+ <Dialog open={open} onClose={busy ? undefined : onClose}>+ <DialogTitle>Remove {app.name}'s app?</DialogTitle>+ <DialogContent>+ <DialogContentText>{removeWarning(app)}</DialogContentText>+ {error && (+ <Alert severity="error" sx={{ mt: 2 }}>+ {error}+ </Alert>+ )}+ </DialogContent>+ <DialogActions>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button+ variant="contained"+ color="error"+ disabled={busy}+ onClick={() => void remove()}+ startIcon={busy ? <CircularProgress size={16} /> : undefined}+ >+ Remove+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/connector-apps/SetupDialog.tsx b/gateway/src/pages/connector-apps/SetupDialog.tsxnew file mode 100644index 000000000..bfb8c9348--- /dev/null+++ b/gateway/src/pages/connector-apps/SetupDialog.tsx@@ -0,0 +1,341 @@+import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";+import {+ Alert,+ Box,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ FormControlLabel,+ IconButton,+ Link,+ Radio,+ RadioGroup,+ Stack,+ TextField,+ Tooltip,+ Typography,+} from "@mui/material";+import { useEffect, useState } from "react";+import {+ type ConnectorApp,+ type ConnectorAppField,+ type ConnectorAppImpact,+ ConnectorAppRefusal,+ fetchConnectorAppImpact,+ saveConnectorApp,+} from "../../data/api";+import {+ type Audience,+ asksWhoConnects,+ peopleIn,+ type SecretField,+ secretFields,+ setupInstructions,+ switchWarning,+ vendorName,+} from "./connectorApps";++export type SetupMode = "set_up" | "switch" | "enter_again";++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++function Copyable({ value }: { value: string }) {+ return (+ <Stack direction="row" alignItems="center" spacing={0.5}>+ <Typography+ variant="body1"+ sx={{ fontFamily: "monospace", wordBreak: "break-all", flexGrow: 1 }}+ >+ {value}+ </Typography>+ <Tooltip title="Copy">+ <IconButton+ size="small"+ aria-label={`Copy ${value}`}+ onClick={() => void navigator.clipboard?.writeText(value)}+ >+ <ContentCopyOutlined fontSize="small" />+ </IconButton>+ </Tooltip>+ </Stack>+ );+}++/**+ * The secret inputs, labelled as the vendor labels them: empty, masked, and+ * a private key read from its file in the browser and never shown.+ */+export function SecretInputs({+ fields,+ values,+ onChange,+ highlighted,+}: {+ fields: SecretField[];+ values: Record<string, string>;+ onChange: (name: string, value: string) => void;+ highlighted: ConnectorAppField | null;+}) {+ const [fileNames, setFileNames] = useState<Record<string, string>>({});+ return (+ <>+ {fields.map((field) =>+ field.file ? (+ <Box key={field.name}>+ <Button variant="outlined" component="label" color={highlighted === field.name ? "error" : "primary"}>+ {fileNames[field.name] ? `${field.label}: ${fileNames[field.name]}` : `Choose the ${field.label.toLowerCase()} (.pem)`}+ <input+ hidden+ type="file"+ accept=".pem"+ aria-label={field.label}+ onChange={(event) => {+ const file = event.target.files?.[0];+ if (!file) return;+ void file.text().then((text) => {+ setFileNames((names) => ({ ...names, [field.name]: file.name }));+ onChange(field.name, text);+ });+ }}+ />+ </Button>+ <Typography variant="caption" color="text.secondary" display="block">+ Read here in your browser and sent only to Switch; never shown.+ </Typography>+ </Box>+ ) : (+ <TextField+ key={field.name}+ label={field.label}+ type="password"+ autoComplete="off"+ value={values[field.name] ?? ""}+ error={highlighted === field.name}+ onChange={(event) => onChange(field.name, event.target.value)}+ />+ ),+ )}+ </>+ );+}++/**+ * Setting up an app, entering it again, or switching to a different one:+ * create it at the vendor, paste its values, and check and save in one+ * click. Switching starts with what it does to the people connected.+ */+export default function SetupDialog({+ app,+ publicUrl,+ mode,+ open,+ onClose,+ onSaved,+}: {+ app: ConnectorApp;+ publicUrl: string | null;+ mode: SetupMode;+ open: boolean;+ onClose: () => void;+ onSaved: (saved: ConnectorApp) => void;+}) {+ const first = mode === "switch" ? 0 : 1;+ const [step, setStep] = useState(first);+ const [audience, setAudience] = useState<Audience>("internal");+ const [clientId, setClientId] = useState(mode === "enter_again" ? (app.saved_client_id ?? "") : "");+ const [secrets, setSecrets] = useState<Record<string, string>>({});+ const [error, setError] = useState<string | null>(null);+ const [field, setField] = useState<ConnectorAppField | null>(null);+ const [busy, setBusy] = useState(false);+ const [impact, setImpact] = useState<ConnectorAppImpact | null>(null);++ useEffect(() => {+ if (!open) return;+ setStep(first);+ setClientId(mode === "enter_again" ? (app.saved_client_id ?? "") : "");+ setSecrets({});+ setError(null);+ setField(null);+ setImpact(null);+ }, [open, first, mode, app.saved_client_id]);++ const fields = secretFields(app);+ const complete = clientId.trim() !== "" && fields.every((f) => (secrets[f.name] ?? "") !== "");+ const replacing = app.saved_client_id !== null && clientId.trim() !== app.saved_client_id;++ const save = async () => {+ setBusy(true);+ setError(null);+ setField(null);+ try {+ if (mode === "switch" && impact === null) {+ setImpact(await fetchConnectorAppImpact(app.slug, clientId.trim()));+ setBusy(false);+ return;+ }+ const saved = await saveConnectorApp(app.slug, {+ client_id: clientId.trim(),+ ...secrets,+ replace: mode === "switch",+ });+ onSaved(saved);+ } catch (err) {+ setError(errorText(err));+ setField(err instanceof ConnectorAppRefusal ? err.field : null);+ setStep(2);+ } finally {+ setBusy(false);+ }+ };++ const title =+ mode === "switch"+ ? "Use a different app"+ : mode === "enter_again"+ ? `Enter ${app.name}'s app again`+ : `Set up ${app.kind === "github_app" ? "GitHub" : app.name}`;++ return (+ <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth="sm">+ <DialogTitle>{title}</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ pt: 1 }}>+ {step === 0 && (+ <Alert severity="warning">+ {switchWarning(app, app).map((line) => (+ <Typography key={line} variant="body2" sx={{ mb: 0.5 }}>+ {line}+ </Typography>+ ))}+ </Alert>+ )}++ {step === 1 && (+ <>+ <Typography variant="subtitle1">+ Step 1 of 3 · Create the app at {vendorName(app)}+ </Typography>+ {asksWhoConnects(app) && (+ <Box>+ <Typography variant="body1" fontWeight={600}>+ Who will connect?+ </Typography>+ <RadioGroup+ value={audience}+ onChange={(_, value) => setAudience(value as Audience)}+ >+ <FormControlLabel+ value="internal"+ control={<Radio size="small" />}+ label="Only people in your Google organization (recommended)"+ />+ <FormControlLabel+ value="external"+ control={<Radio size="small" />}+ label="Anyone with a Google account"+ />+ </RadioGroup>+ </Box>+ )}+ <Box component="ol" sx={{ pl: 2.5, m: 0 }}>+ {setupInstructions(app, audience, publicUrl).map((instruction) => (+ <Box component="li" key={instruction.text} sx={{ mb: 1.5 }}>+ <Typography variant="body1">+ {instruction.text}+ {instruction.link && (+ <>+ {" "}+ <Link href={instruction.link.href} target="_blank" rel="noreferrer">+ {instruction.link.label}+ </Link>+ </>+ )}+ </Typography>+ {instruction.copy && <Copyable value={instruction.copy} />}+ </Box>+ ))}+ </Box>+ </>+ )}++ {step === 2 && (+ <>+ <Typography variant="subtitle1">Step 2 of 3 · Paste its values</Typography>+ <TextField+ label="Client ID"+ value={clientId}+ autoComplete="off"+ error={field === "client_id"}+ onChange={(event) => {+ setClientId(event.target.value);+ setImpact(null);+ }}+ />+ <SecretInputs+ fields={fields}+ values={secrets}+ highlighted={field}+ onChange={(name, value) => setSecrets((current) => ({ ...current, [name]: value }))}+ />+ {app.kind === "github_app" && (+ <Typography variant="caption" color="text.secondary">+ The App's name is read from GitHub when Switch checks it.+ </Typography>+ )}+ {error && <Alert severity="error">{error}</Alert>}+ {mode === "enter_again" && replacing && (+ <Alert severity="warning">+ This is a different client ID from the one saved. Use a different app to+ switch on purpose.+ </Alert>+ )}+ {impact && (+ <Alert severity="warning">+ {impact.connected_members === 0+ ? "Nobody is connected through the current app."+ : `${peopleIn(impact)} will need to reconnect.`}+ </Alert>+ )}+ </>+ )}+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ {step > first && (+ <Button onClick={() => setStep(step - 1)} disabled={busy}>+ Back+ </Button>+ )}+ {step < 2 ? (+ <Button variant="contained" onClick={() => setStep(step + 1)}>+ {step === 0 ? "Continue" : "Next"}+ </Button>+ ) : (+ <Button+ variant="contained"+ color={mode === "switch" ? "warning" : "primary"}+ disabled={!complete || busy || (mode === "enter_again" && replacing)}+ onClick={() => void save()}+ startIcon={busy ? <CircularProgress size={16} /> : undefined}+ >+ {busy+ ? "Checking…"+ : mode === "switch"+ ? impact+ ? "Switch app"+ : "Check who reconnects"+ : "Check and save"}+ </Button>+ )}+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/connector-apps/UpdateSecretDialog.tsx b/gateway/src/pages/connector-apps/UpdateSecretDialog.tsxnew file mode 100644index 000000000..264a1e504--- /dev/null+++ b/gateway/src/pages/connector-apps/UpdateSecretDialog.tsx@@ -0,0 +1,102 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Stack,+ Typography,+} from "@mui/material";+import { useEffect, useState } from "react";+import {+ type ConnectorApp,+ type ConnectorAppField,+ ConnectorAppRefusal,+ saveConnectorApp,+} from "../../data/api";+import { menuLabel, secretFields, UPDATE_SECRET_NOTE } from "./connectorApps";+import { SecretInputs } from "./SetupDialog";++/**+ * A new secret (or, for GitHub, a new private key) for the same app: nobody+ * is disconnected. What is left empty keeps what is saved.+ */+export default function UpdateSecretDialog({+ app,+ open,+ onClose,+ onSaved,+}: {+ app: ConnectorApp;+ open: boolean;+ onClose: () => void;+ onSaved: (saved: ConnectorApp) => void;+}) {+ const [secrets, setSecrets] = useState<Record<string, string>>({});+ const [error, setError] = useState<string | null>(null);+ const [field, setField] = useState<ConnectorAppField | null>(null);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ if (!open) return;+ setSecrets({});+ setError(null);+ setField(null);+ }, [open]);++ const given = Object.fromEntries(Object.entries(secrets).filter(([, value]) => value !== ""));++ const save = async () => {+ if (app.client_id === null) return;+ setBusy(true);+ setError(null);+ setField(null);+ try {+ onSaved(+ await saveConnectorApp(app.slug, { client_id: app.client_id, ...given, replace: false }),+ );+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setField(err instanceof ConnectorAppRefusal ? err.field : null);+ } finally {+ setBusy(false);+ }+ };++ return (+ <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth="sm">+ <DialogTitle>{menuLabel(app, "update_secret")}</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ pt: 1 }}>+ <Typography variant="body2" color="text.secondary">+ For the app with client ID {app.client_id}.+ {app.kind === "github_app" && " Leave either empty to keep what is saved."}+ </Typography>+ <SecretInputs+ fields={secretFields(app)}+ values={secrets}+ highlighted={field}+ onChange={(name, value) => setSecrets((current) => ({ ...current, [name]: value }))}+ />+ {error && <Alert severity="error">{error}</Alert>}+ <Typography variant="body2">{UPDATE_SECRET_NOTE}</Typography>+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button+ variant="contained"+ disabled={busy || Object.keys(given).length === 0}+ onClick={() => void save()}+ startIcon={busy ? <CircularProgress size={16} /> : undefined}+ >+ {busy ? "Checking…" : "Check and save"}+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/connector-apps/connectorApps.test.ts b/gateway/src/pages/connector-apps/connectorApps.test.tsnew file mode 100644index 000000000..008e5876b--- /dev/null+++ b/gateway/src/pages/connector-apps/connectorApps.test.ts@@ -0,0 +1,291 @@+import { describe, expect, it } from "vitest";+import {+ actionLabel,+ attention,+ audienceText,+ cardOrder,+ cardState,+ configuredSentence,+ menuActions,+ menuLabel,+ moveChecklist,+ peopleIn,+ primaryAction,+ removeWarning,+ secretSummary,+ sentBackTo,+ setupInstructions,+ stateLabel,+ switchWarning,+} from "./connectorApps";+import { app } from "./testFixtures";++const PUBLIC_URL = "https://switch.example.test";++const NONE = app({+ source: "none",+ client_id: null,+ saved_client_id: null,+ secrets: { client_secret: { set: false, last4: null } },+ connected_members: 0,+ workspaces: 0,+});+const CONFIGURED = app({ source: "configuration", saved_client_id: null });+const GITHUB = app({+ slug: "github",+ name: "GitHub",+ kind: "github_app",+ configuration_variables: ["GITHUB_APP_CONFIG_PATH", "GITHUB_APP_PRIVATE_KEY_PATH"],+ fields: { slug: "example-app" },+ secrets: {+ client_secret: { set: true, last4: "cd34" },+ private_key: { set: true, fingerprint: "SHA256:example" },+ },+});++describe("card state", () => {+ it("is one of four", () => {+ expect(cardState(app(), null)).toBe("ready");+ expect(cardState(NONE, null)).toBe("not_set_up");+ expect(cardState(CONFIGURED, null)).toBe("configured");+ expect(cardState(app(), "Google says no.")).toBe("attention");+ expect(["ready", "not_set_up", "configured", "attention"].map((s) => stateLabel(s as never))).toEqual([+ "Ready",+ "Not set up",+ "Set on the server",+ "Needs attention",+ ]);+ });++ it("names one cause and one fix for each kind of attention", () => {+ expect(attention(app(), "Google doesn't recognise this client.")).toEqual({+ cause: "check_failed",+ sentence: "Google doesn't recognise this client.",+ action: "update_secret",+ });+ expect(attention(app({ source: "none", unreadable: true, load_error: "x" }), null)).toEqual({+ cause: "unreadable",+ sentence: "Switch can't read the saved secret any more.",+ action: "enter_again",+ });+ expect(attention(app({ source: "none", load_error: "Not RSA." }), null)?.cause).toBe(+ "load_error",+ );+ expect(+ attention(+ app({ source: "configuration", saved_ignored: true, saved_client_id: "other" }),+ null,+ ),+ ).toEqual({+ cause: "saved_ignored",+ sentence:+ "Saved here, but GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH is still set, so Switch uses that. Remove it and restart Switch.",+ action: "manage_here",+ });+ expect(attention(app({ stale_connections: 5 }), null)).toEqual({+ cause: "stale",+ sentence: "5 people still need to reconnect.",+ action: null,+ });+ expect(attention(app({ stale_connections: 1 }), null)?.sentence).toBe(+ "1 person still needs to reconnect.",+ );+ expect(attention(app(), null)).toBeNull();+ });++ it("does not call a copied-in app waiting for its restart a problem", () => {+ const waiting = app({ source: "configuration", saved_ignored: true });+ expect(attention(waiting, null)).toBeNull();+ expect(cardState(waiting, null)).toBe("configured");+ expect(primaryAction(waiting, null)).toBeNull();+ });+});++describe("set-up blocked by the server", () => {+ const BLOCKED = "GitHub needs GATEWAY_PUBLIC_URL to be an https address, to send people back to Switch.";++ it("is the card's one sentence, with Set up as the fix", () => {+ const github = { ...GITHUB, source: "none" as const, client_id: null, redirect_uri: null, setup_blocked: BLOCKED };+ expect(attention(github, null)).toEqual({+ cause: "setup_blocked",+ sentence: BLOCKED,+ action: "set_up",+ });+ expect(primaryAction(github, null)).toBe("set_up");+ });++ it("leaves an app set on the server working", () => {+ const configured = { ...GITHUB, source: "configuration" as const, setup_blocked: BLOCKED };+ expect(attention(configured, null)).toBeNull();+ expect(cardState(configured, null)).toBe("configured");+ });++ it("names where people are sent back to", () => {+ expect(sentBackTo("https://switch.example.test")).toBe(+ "People are sent back to https://switch.example.test.",+ );+ });+});++describe("set on the server", () => {+ it("names the variable, and how to change it or move off it", () => {+ expect(configuredSentence(CONFIGURED)).toBe(+ "From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here.",+ );+ expect(configuredSentence({ ...GITHUB, source: "configuration", saved_client_id: null })).toBe(+ "From GITHUB_APP_CONFIG_PATH and GITHUB_APP_PRIVATE_KEY_PATH. Change them there, or remove them to manage it here.",+ );+ });++ it("says a copy saved here under the same client is used once the variable goes", () => {+ const copied = app({ source: "configuration", saved_ignored: true });+ expect(configuredSentence(copied)).toBe(+ "From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here. A copy is saved here, same client. Remove the variable and restart Switch to use the copy.",+ );+ expect(configuredSentence(copied)).not.toMatch(/waiting for restart/);+ });++ it("leaves a copy of another client to the attention sentence", () => {+ const other = app({ source: "configuration", saved_ignored: true, saved_client_id: "other" });+ expect(configuredSentence(other)).toBe(+ "From GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH. Change it there, or remove it to manage it here.",+ );+ expect(attention(other, null)?.cause).toBe("saved_ignored");+ });+});++describe("order", () => {+ it("puts what needs attention first, then not set up, then working", () => {+ const stale = app({ slug: "a", name: "A", stale_connections: 2 });+ const failing = app({ slug: "b", name: "B" });+ const ordered = cardOrder([app({ slug: "z", name: "Z" }), NONE, CONFIGURED, stale, failing], {+ b: "No.",+ });+ expect(ordered.map((a) => a.name)).toEqual([+ "A",+ "B",+ "Google Workspace",+ "Google Workspace",+ "Z",+ ]);+ expect(ordered[2]!.source).toBe("none");+ expect(ordered[3]!.source).toBe("configuration");+ });+});++describe("actions", () => {+ it("offers one obvious button per state", () => {+ expect(primaryAction(NONE, null)).toBe("set_up");+ expect(actionLabel(NONE, "set_up")).toBe("Set up Google Workspace");+ expect(actionLabel(GITHUB, "set_up")).toBe("Set up GitHub");+ expect(primaryAction(CONFIGURED, null)).toBe("manage_here");+ expect(primaryAction(app(), null)).toBe("check");+ expect(primaryAction(app(), "No.")).toBe("update_secret");+ expect(primaryAction(app({ source: "none", unreadable: true }), null)).toBe("enter_again");+ expect(primaryAction(app({ stale_connections: 3 }), null)).toBe("check");+ expect(primaryAction(app({ source: "configuration", deprecated: true }), null)).toBeNull();+ });++ it("splits changes by what they do to the people connected", () => {+ expect(menuActions(app())).toEqual(["update_secret", "switch_app", "remove"]);+ expect(menuActions(NONE)).toEqual([]);+ expect(menuActions(CONFIGURED)).toEqual([]);+ expect(menuActions(app({ source: "none", unreadable: true }))).toEqual(["remove"]);+ expect(menuLabel(app(), "update_secret")).toBe("Update secret");+ expect(menuLabel(GITHUB, "update_secret")).toBe("Update secret or private key");+ expect(menuLabel(app(), "switch_app")).toBe("Use a different app");+ });+});++describe("wording", () => {+ it("counts people and workspaces", () => {+ expect(peopleIn({ connected_members: 12, workspaces: 3 })).toBe("12 people in 3 workspaces");+ expect(peopleIn({ connected_members: 1, workspaces: 1 })).toBe("1 person in 1 workspace");+ });++ it("warns before switching apps, GitHub's repositories included", () => {+ expect(switchWarning(app(), { connected_members: 12, workspaces: 3 })).toEqual([+ "Everyone connected through the current app (12 people in 3 workspaces) will need to reconnect, and their agents lose Google Workspace until they do.",+ "If the old app's secret leaked, also delete it at Google: tokens already handed to agents stay valid for up to an hour.",+ ]);+ expect(switchWarning(GITHUB, { connected_members: 2, workspaces: 1 })).toContain(+ "They will also need to choose their repositories again.",+ );+ });++ it("says who loses a removed app", () => {+ expect(removeWarning(app())).toBe(+ "Nobody will be able to connect Google Workspace, and the 12 people connected now lose it. They can still disconnect.",+ );+ expect(removeWarning(NONE)).toBe("Nobody will be able to connect Google Workspace.");+ });++ it("shows how to recognise a secret, never the secret", () => {+ expect(secretSummary(app())).toBe("Secret ends in ab12");+ expect(secretSummary(GITHUB)).toBe("Secret ends in cd34 · Key SHA256:example");+ expect(secretSummary(NONE)).toBeNull();+ });++ it("changes only the instructions with who will connect", () => {+ const internal = setupInstructions(NONE, "internal", PUBLIC_URL);+ const external = setupInstructions(NONE, "external", PUBLIC_URL);+ expect(internal[2]!.text).toBe(audienceText("internal"));+ expect(external[2]!.text).toBe(audienceText("external"));+ expect(internal.filter((_, i) => i !== 2)).toEqual(external.filter((_, i) => i !== 2));+ expect(audienceText("external")).toMatch(/add the people who will try it as test users/);+ expect(audienceText("external")).toMatch(/reconnect every 7 days/);+ expect(audienceText("external")).toMatch(/security assessment renewed every year/);+ });++ it("walks Google's set-up page by page, each with its link", () => {+ const steps = setupInstructions(NONE, "internal", PUBLIC_URL);+ expect(steps.map((s) => s.link?.href ?? null)).toEqual([+ "https://console.cloud.google.com/projectcreate",+ "https://console.cloud.google.com/auth/branding",+ "https://console.cloud.google.com/auth/audience",+ "https://console.cloud.google.com/auth/clients",+ null,+ "https://console.cloud.google.com/apis/library",+ ]);+ expect(steps[1]!.text).toMatch(/app name .* support email/);+ expect(steps[4]!.copy).toBe(NONE.redirect_uri);+ expect(steps[5]!.text).toBe(+ "Enable the Google Drive, Docs, Sheets, Slides and Calendar APIs for the project.",+ );+ });++ it("walks GitHub's form from top to bottom, with what to paste", () => {+ const steps = setupInstructions(GITHUB, "internal", PUBLIC_URL);+ expect(steps[0]!.link).toEqual({ label: "Open GitHub", href: "https://github.com/settings/apps/new" });+ expect(steps.slice(1).every((s) => s.link === null)).toBe(true);+ expect(steps.map((s) => s.copy).filter((c) => c !== null)).toEqual([PUBLIC_URL, GITHUB.redirect_uri]);+ const texts = steps.map((s) => s.text);+ expect(texts[1]).toMatch(/^Set the Homepage URL/);+ expect(texts[2]).toMatch(/^Set the Callback URL/);+ expect(texts[3]).toMatch(/Expire user authorization tokens turned on/);+ expect(texts[4]).toMatch(/^Under Webhook, untick Active/);+ expect(texts[5]).toMatch(/Contents and Pull requests to Read and write/);+ expect(texts[6]).toMatch(/Where can this GitHub App be installed, choose Any account/);+ expect(texts[7]).toMatch(/generate a client secret, then a private key/);+ });++ it("links only to the vendors' public pages", () => {+ const links = [+ ...setupInstructions(NONE, "external", PUBLIC_URL),+ ...setupInstructions(GITHUB, "internal", PUBLIC_URL),+ ].flatMap((s) => (s.link ? [s.link.href] : []));+ expect(links.every((href) => /^https:\/\/(console\.cloud\.google\.com|github\.com)\//.test(href))).toBe(true);+ });+});++describe("moving off configuration", () => {+ it("ticks copying in once the saved app matches, and names the Helm value", () => {+ 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.",+ );+ const after = moveChecklist(app({ source: "configuration", saved_ignored: true }));+ expect(after.map((item) => item.done)).toEqual([true, false, false]);+ });+});diff --git a/gateway/src/pages/connector-apps/connectorApps.ts b/gateway/src/pages/connector-apps/connectorApps.tsnew file mode 100644index 000000000..7ff4f8116--- /dev/null+++ b/gateway/src/pages/connector-apps/connectorApps.ts@@ -0,0 +1,377 @@+/**+ * What the Connectors page shows, decided here and only displayed by the+ * components: each card's state, the one sentence and button that go with+ * it, the order, which actions it offers, and the wording of every dialog.+ * Labels follow what Google and GitHub call things, so the operator can copy+ * values across.+ */+import type { ConnectorApp, ConnectorAppField, ConnectorAppImpact } from "../../data/api";++export type CardState = "ready" | "not_set_up" | "configured" | "attention";++export type AttentionCause =+ | "setup_blocked"+ | "check_failed"+ | "unreadable"+ | "load_error"+ | "saved_ignored"+ | "stale";++export type CardAction = "set_up" | "manage_here" | "check" | "update_secret" | "enter_again";++export interface Attention {+ cause: AttentionCause;+ sentence: string;+ /** The one fix offered beside the sentence; null where there is nothing to press. */+ action: CardAction | null;+}++export type MenuAction = "update_secret" | "switch_app" | "remove";++export type Audience = "internal" | "external";++export interface Instruction {+ text: string;+ /** A value to paste at the vendor, offered with a copy button. */+ copy: string | null;+ /** The vendor's page for this step, where it has one of its own. */+ link: { label: string; href: string } | null;+}++export interface SecretField {+ name: Exclude<ConnectorAppField, "client_id">;+ label: string;+ /** A file the browser reads (the .pem), never shown. */+ file: boolean;+}++const GOOGLE = "google-workspace";++export function vendorName(app: Pick<ConnectorApp, "slug" | "kind" | "name">): string {+ if (app.kind === "github_app") return "GitHub";+ if (app.slug === GOOGLE) return "Google";+ return app.name;+}++/** "12 people in 3 workspaces", "1 person in 1 workspace". */+export function peopleIn(usage: ConnectorAppImpact): string {+ const people = usage.connected_members === 1 ? "1 person" : `${usage.connected_members} people`;+ const workspaces = usage.workspaces === 1 ? "1 workspace" : `${usage.workspaces} workspaces`;+ return `${people} in ${workspaces}`;+}++function variables(app: ConnectorApp): string {+ return app.configuration_variables.join(" and ");+}++/** Copied into Switch, and waiting for the configuration to be removed. */+export function waitingForRestart(app: ConnectorApp): boolean {+ return (+ app.source === "configuration" &&+ app.saved_ignored &&+ app.saved_client_id !== null &&+ app.saved_client_id === app.client_id+ );+}++/** What needs the operator, most pressing first; null when nothing does. */+export function attention(app: ConnectorApp, checkFailure: string | null): Attention | null {+ // A configured app keeps working: only setting one up here is blocked.+ if (app.setup_blocked !== null && app.source !== "configuration")+ return { cause: "setup_blocked", sentence: app.setup_blocked, action: "set_up" };+ if (checkFailure !== null)+ return { cause: "check_failed", sentence: checkFailure, action: "update_secret" };+ if (app.unreadable)+ return {+ cause: "unreadable",+ sentence: "Switch can't read the saved secret any more.",+ action: "enter_again",+ };+ if (app.load_error !== null)+ return { cause: "load_error", sentence: app.load_error, action: "enter_again" };+ if (app.saved_ignored && !waitingForRestart(app))+ return {+ cause: "saved_ignored",+ sentence: `Saved here, but ${variables(app)} is still set, so Switch uses that. Remove it and restart Switch.`,+ action: "manage_here",+ };+ if (app.stale_connections > 0)+ return {+ cause: "stale",+ sentence:+ app.stale_connections === 1+ ? "1 person still needs to reconnect."+ : `${app.stale_connections} people still need to reconnect.`,+ action: null,+ };+ return null;+}++export function cardState(app: ConnectorApp, checkFailure: string | null): CardState {+ if (attention(app, checkFailure) !== null) return "attention";+ if (app.source === "configuration") return "configured";+ if (app.source === "saved") return "ready";+ return "not_set_up";+}++export function stateLabel(state: CardState): string {+ switch (state) {+ case "ready":+ return "Ready";+ case "not_set_up":+ return "Not set up";+ case "configured":+ return "Set on the server";+ case "attention":+ return "Needs attention";+ }+}++const ORDER: Record<CardState, number> = {+ attention: 0,+ not_set_up: 1,+ configured: 2,+ ready: 3,+};++/** Cards that need attention first, then not set up, then working. */+export function cardOrder(+ apps: ConnectorApp[],+ checkFailures: Record<string, string>,+): ConnectorApp[] {+ return [...apps].sort(+ (a, b) =>+ ORDER[cardState(a, checkFailures[a.slug] ?? null)] -+ ORDER[cardState(b, checkFailures[b.slug] ?? null)] || a.name.localeCompare(b.name),+ );+}++export function notSetUpSentence(app: ConnectorApp): string {+ return app.kind === "github_app"+ ? "People can't connect GitHub until you add Switch's GitHub App."+ : `People can't connect ${app.name} until you add Switch's ${vendorName(app)} client.`;+}++/** The card's one obvious button. */+export function primaryAction(app: ConnectorApp, checkFailure: string | null): CardAction | null {+ const state = cardState(app, checkFailure);+ if (state === "not_set_up") return "set_up";+ if (state === "attention") {+ const fix = attention(app, checkFailure)?.action ?? null;+ return fix ?? (app.source === "none" ? null : "check");+ }+ if (state === "configured") return app.deprecated || waitingForRestart(app) ? null : "manage_here";+ return "check";+}++export function actionLabel(app: ConnectorApp, action: CardAction): string {+ switch (action) {+ case "set_up":+ return `Set up ${app.kind === "github_app" ? "GitHub" : app.name}`;+ case "manage_here":+ return "Manage it here instead";+ case "check":+ return "Check it works";+ case "update_secret":+ return "Update secret";+ case "enter_again":+ return "Enter it again";+ }+}++/** The ⋯ menu: changes split by what they do to the people connected. */+export function menuActions(app: ConnectorApp): MenuAction[] {+ if (app.source === "saved") return ["update_secret", "switch_app", "remove"];+ // Saved, but unusable: it can be entered again, or removed.+ if (app.source === "none" && app.saved_client_id !== null) return ["remove"];+ return [];+}++export function menuLabel(app: ConnectorApp, action: MenuAction): string {+ switch (action) {+ case "update_secret":+ return app.kind === "github_app" ? "Update secret or private key" : "Update secret";+ case "switch_app":+ return "Use a different app";+ case "remove":+ return "Remove";+ }+}++export function configuredSentence(app: ConnectorApp): string {+ if (app.deprecated)+ return "Using HOSTED_GITHUB_CONFIG_PATH, which names no private key, so GitHub can be connected but not granted. Set up the GitHub App here instead, after unsetting it.";+ const one = app.configuration_variables.length === 1;+ const from = `From ${variables(app)}. Change ${one ? "it" : "them"} there, or remove ${one ? "it" : "them"} to manage it here.`;+ if (waitingForRestart(app))+ return `${from} A copy is saved here, same client. Remove the ${one ? "variable" : "variables"} and restart Switch to use the copy.`;+ return from;+}++export function secretFields(app: Pick<ConnectorApp, "kind">): SecretField[] {+ const secret: SecretField = { name: "client_secret", label: "Client secret", file: false };+ return app.kind === "github_app"+ ? [secret, { name: "private_key", label: "Private key", file: true }]+ : [secret];+}++/** "ends in ab12", or a key's fingerprint. */+export function secretSummary(app: ConnectorApp): string | null {+ const secret = app.secrets.client_secret;+ const parts = [];+ if (secret?.set) parts.push(secret.last4 ? `Secret ends in ${secret.last4}` : "Secret set");+ const key = app.secrets.private_key;+ if (key?.set) parts.push(key.fingerprint ? `Key ${key.fingerprint}` : "Key set");+ return parts.length ? parts.join(" · ") : null;+}++export function usedBy(app: ConnectorApp): string {+ return `Used by ${peopleIn(app)}`;+}++/** Google's choice of who may connect; it changes only the instructions. */+export function asksWhoConnects(app: Pick<ConnectorApp, "slug">): boolean {+ return app.slug === GOOGLE;+}++export function audienceText(audience: Audience): string {+ return audience === "internal"+ ? "Under Audience, choose Internal. Only people in your Google organization can connect, and Google doesn't need to review the app."+ : "Under Audience, choose External, and add the people who will try it as test users. Until Google verifies the app, only test users can connect, and they must reconnect every 7 days. Because Switch reads Drive, Google's review includes a security assessment renewed every year.";+}++const GOOGLE_CLOUD = "https://console.cloud.google.com";++/** Step 1 of setting up: creating the app at the vendor, one page at a time. */+export function setupInstructions(+ app: ConnectorApp,+ audience: Audience,+ publicUrl: string | null,+): Instruction[] {+ const redirect = app.redirect_uri;+ if (app.kind === "github_app")+ return [+ {+ text: "In GitHub, create a new GitHub App: Settings, Developer settings, GitHub Apps. For an App owned by an organization, start from the organization's settings instead.",+ copy: null,+ link: { label: "Open GitHub", href: "https://github.com/settings/apps/new" },+ },+ { text: "Set the Homepage URL to Switch's public URL:", copy: publicUrl, link: null },+ { text: "Set the Callback URL to:", copy: redirect, link: null },+ { text: "Keep Expire user authorization tokens turned on.", copy: null, link: null },+ {+ text: "Under Webhook, untick Active. Switch doesn't use GitHub's webhooks, and GitHub asks for a webhook URL while it is ticked.",+ copy: null,+ link: null,+ },+ {+ text: "Under Repository permissions, set Contents and Pull requests to Read and write.",+ copy: null,+ link: null,+ },+ {+ text: "Under Where can this GitHub App be installed, choose Any account, so people can install it on their own accounts and organizations. Choose Only on this account only if every member's repositories are in your own organization.",+ copy: null,+ link: null,+ },+ {+ text: "Create the GitHub App. On its page, generate a client secret, then a private key, and keep the downloaded .pem file.",+ copy: null,+ link: null,+ },+ ];+ if (app.slug === GOOGLE)+ return [+ {+ text: "In Google Cloud, create a project for Switch, or pick an existing one.",+ copy: null,+ link: { label: "Create a project", href: `${GOOGLE_CLOUD}/projectcreate` },+ },+ {+ text: "In Google Auth Platform, under Branding, enter an app name people will recognise and a support email.",+ copy: null,+ link: { label: "Open Branding", href: `${GOOGLE_CLOUD}/auth/branding` },+ },+ {+ text: audienceText(audience),+ copy: null,+ link: { label: "Open Audience", href: `${GOOGLE_CLOUD}/auth/audience` },+ },+ {+ text: "Under Clients, create a client of type Web application.",+ copy: null,+ link: { label: "Open Clients", href: `${GOOGLE_CLOUD}/auth/clients` },+ },+ {+ text: "Add this under Authorized redirect URIs, create the client, and copy its Client ID and Client secret:",+ copy: redirect,+ link: null,+ },+ {+ text: "Enable the Google Drive, Docs, Sheets, Slides and Calendar APIs for the project.",+ copy: null,+ link: { label: "Open the API Library", href: `${GOOGLE_CLOUD}/apis/library` },+ },+ ];+ return [+ {+ text: `Register an OAuth client for Switch at ${app.name}, with this redirect URI:`,+ copy: redirect,+ link: null,+ },+ ];+}++export const UPDATE_SECRET_NOTE = "Nobody is disconnected.";++/** The warning before switching to another app. */+export function switchWarning(app: ConnectorApp, impact: ConnectorAppImpact): string[] {+ const lines = [+ `Everyone connected through the current app (${peopleIn(impact)}) will need to reconnect, and their agents lose ${app.name} until they do.`,+ ];+ if (app.kind === "github_app")+ lines.push("They will also need to choose their repositories again.");+ lines.push(+ `If the old app's secret leaked, also delete it at ${vendorName(app)}: tokens already handed to agents stay valid for up to an hour.`,+ );+ return lines;+}++export function removeWarning(app: ConnectorApp): string {+ const name = app.name;+ if (app.connected_members === 0) return `Nobody will be able to connect ${name}.`;+ const people =+ app.connected_members === 1 ? "the 1 person" : `the ${app.connected_members} people`;+ return `Nobody will be able to connect ${name}, and ${people} connected now lose it. They can still disconnect.`;+}++export interface ChecklistItem {+ text: string;+ done: boolean;+}++const HELM_VALUES: Record<string, string> = {+ github: "switchCore.githubConnectionsSecret and switchCore.githubAppPrivateKeyPath",+ [GOOGLE]: "switchCore.googleWorkspaceClientSecret",+};++/** Moving off configuration: copy in, remove the configuration, restart. */+export function moveChecklist(app: ConnectorApp): ChecklistItem[] {+ const helm = HELM_VALUES[app.slug];+ 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}.` : ""}`,+ done: false,+ },+ { text: "Restart Switch.", done: false },+ ];+}++export const sentBackTo = (publicUrl: string): string => `People are sent back to ${publicUrl}.`;++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/connector-apps/testFixtures.ts b/gateway/src/pages/connector-apps/testFixtures.tsnew file mode 100644index 000000000..810fc5cde--- /dev/null+++ b/gateway/src/pages/connector-apps/testFixtures.ts@@ -0,0 +1,30 @@+import type { ConnectorApp } from "../../data/api";++/** A connector app as the server lists it, with placeholder values. */+export function app(overrides: Partial<ConnectorApp> = {}): ConnectorApp {+ return {+ slug: "google-workspace",+ name: "Google Workspace",+ kind: "oauth_client",+ source: "saved",+ configuration_variables: ["GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH"],+ deprecated: false,+ client_id: "example-client-id",+ saved_client_id: "example-client-id",+ fields: {},+ secrets: { client_secret: { set: true, last4: "ab12" } },+ saved_ignored: false,+ unreadable: false,+ load_error: null,+ redirect_uri:+ "https://switch.example.test/gateway/service-connections/google-workspace/flows/callback",+ setup_blocked: null,+ install_url: null,+ updated_by_name: "Ada",+ updated_at: "2026-10-15T10:00:00Z",+ connected_members: 12,+ workspaces: 3,+ stale_connections: 0,+ ...overrides,+ };+}