Skip to content

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

feat(gateway): install and disconnect the Switch app from the dashboard (CHOO-2626)

Petr Bauch98ccec8076a3
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 0bae2bc28..065666d9d 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -816,11 +816,12 @@ export async function fetchAllExternalUsers(): Promise<
return [...byId.values()];
}
-export async function deleteBridge(bridgeId: string): Promise<boolean> {
- const res = await fetchJson<{ ok: boolean }>(`/collaborations/${bridgeId}`, {
- method: "DELETE",
- });
- return res?.ok ?? false;
+// Throws rather than returning false: a connection created by installing the
+// Switch app is refused here with a 409 saying to disconnect the app instead,
+// and a caller that only sees "it didn't work" would leave the operator
+// clicking Delete at a row that will never go.
+export async function deleteBridge(bridgeId: string): Promise<{ ok: boolean }> {
+ return jsonRequest<{ ok: boolean }>(`/collaborations/${bridgeId}`, "DELETE");
}
export interface BridgeUpdateInput {
@@ -839,6 +840,62 @@ export async function updateBridge(
});
}
+// ── Installed apps ───────────────────────────────────────────────────────────
+//
+// The other way a connection comes into being: instead of an operator
+// registering their own app and pasting its credentials, they install this
+// deployment's app into their workspace and the platform hands the credential
+// back. Most deployments have no app of their own, so `fetchInstallablePlatforms`
+// answering with an empty list is the ordinary case and not a failure.
+
+export interface InstalledApp {
+ id: string;
+ platform: string;
+ external_workspace_id: string;
+ // "active", "disconnected" (ended here) or "revoked" (ended at the
+ // platform). The last two are kept apart because an operator whose
+ // connection stopped working needs to know which of the two it was.
+ status: string;
+ // The platform's own spelling of what was granted, shown verbatim.
+ scopes: string;
+ bridge_id: string | null;
+ installed_at: string;
+ ended_at: string | null;
+}
+
+export async function fetchInstallablePlatforms(): Promise<string[] | null> {
+ const res = await fetchJson<{ platforms: string[] }>("/messaging-apps");
+ return res === null ? null : res.platforms;
+}
+
+export async function fetchInstalledApps(): Promise<InstalledApp[] | null> {
+ const res = await fetchJson<{ installs: InstalledApp[] }>(
+ "/messaging-apps/installs",
+ );
+ return res === null ? null : res.installs;
+}
+
+// Answers with a URL rather than redirecting, because the install has to begin
+// in a top-level window on the platform's own domain — a redirect returned to
+// this fetch would be followed by the fetch.
+export async function beginAppInstall(platform: string): Promise<string> {
+ const res = await jsonRequest<{ authorize_url: string }>(
+ `/messaging-apps/${platform}/install`,
+ "POST",
+ );
+ return res.authorize_url;
+}
+
+// Throwing, because 502 here means the platform refused to revoke, nothing was
+// destroyed, and trying again is the right next move — all of which is in the
+// message and none of which survives a boolean.
+export async function disconnectApp(installId: string): Promise<InstalledApp> {
+ return jsonRequest<InstalledApp>(
+ `/messaging-apps/installs/${installId}`,
+ "DELETE",
+ );
+}
+
// ── Auth ────────────────────────────────────────────────────────────────────
export interface UserInfo {
diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.ts
index c89af9d67..2f24101a8 100644
--- a/gateway/src/data/hooks.ts
+++ b/gateway/src/data/hooks.ts
@@ -10,6 +10,7 @@ import {
type DocumentDetail,
type DocumentSummary,
type InboundLinkedRoomDetail,
+ type InstalledApp,
type KnownAgentType,
type LinkedRoomDetail,
type RoomGraphData,
@@ -35,6 +36,8 @@ import {
fetchDocumentRooms,
fetchDocuments,
fetchInboundLinkedRooms,
+ fetchInstallablePlatforms,
+ fetchInstalledApps,
fetchKnownAgentTypes,
fetchLinkedRooms,
fetchRoomGraph,
@@ -155,6 +158,17 @@ export function useAllExternalUsers(): UseQueryResult<ExternalUserSummary[]> {
return useQuery(fetchAllExternalUsers);
}
+// Empty on every deployment that registered no app of its own, which is most
+// of them — the page reads that as "there is nothing to install here", not as
+// a failure.
+export function useInstallablePlatforms(): UseQueryResult<string[]> {
+ return useQuery(fetchInstallablePlatforms);
+}
+
+export function useInstalledApps(): UseQueryResult<InstalledApp[]> {
+ return useQuery(fetchInstalledApps);
+}
+
export function useKnownAgentTypes(): UseQueryResult<KnownAgentType[]> {
return useQuery(fetchKnownAgentTypes);
}
diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsx
index 2ae99d390..fb2ddb86f 100644
--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx
+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx
@@ -2,6 +2,7 @@ import AddLinkOutlined from "@mui/icons-material/AddLinkOutlined";
import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutline from "@mui/icons-material/DeleteOutline";
import {
+ Alert,
Box,
Button,
Chip,
@@ -25,6 +26,7 @@ import { useAuth } from "../../data/AuthContext";
import { useBridges } from "../../data/hooks";
import { formatDate, titleCase } from "../../theme/hootFormat";
import AddToChatDialog from "./AddToChatDialog";
+import InstalledAppsSection from "./InstalledAppsSection";
import RegisterMessagingAppDialog from "./RegisterMessagingAppDialog";
type BridgeRow = BridgeDetail & { id: string };
@@ -41,6 +43,7 @@ export default function CollaborationsPage() {
const { data: bridges, loading, refetch } = useBridges();
const [deleteTarget, setDeleteTarget] = useState<BridgeDetail | null>(null);
const [deleting, setDeleting] = useState(false);
+ const [deleteError, setDeleteError] = useState<string | null>(null);
const [savingId, setSavingId] = useState<string | null>(null);
const [registerOpen, setRegisterOpen] = useState(false);
const [installTarget, setInstallTarget] = useState<BridgeDetail | null>(null);
@@ -48,10 +51,19 @@ export default function CollaborationsPage() {
const handleDelete = useCallback(async () => {
if (!deleteTarget) return;
setDeleting(true);
- await deleteBridge(deleteTarget.bridge_id);
- setDeleteTarget(null);
- setDeleting(false);
- refetch();
+ setDeleteError(null);
+ try {
+ await deleteBridge(deleteTarget.bridge_id);
+ setDeleteTarget(null);
+ refetch();
+ } catch (e) {
+ // A connection an install created is refused here, and the refusal says
+ // to disconnect the app instead. Closing the dialog on it would leave
+ // the operator clicking Delete at a row that will never go.
+ setDeleteError(e instanceof Error ? e.message : "Failed to delete");
+ } finally {
+ setDeleting(false);
+ }
}, [deleteTarget, refetch]);
const handleToggleGreetings = useCallback(
@@ -221,6 +233,8 @@ export default function CollaborationsPage() {
<DataTable rows={rows} columns={columns} />
)}
+ <InstalledAppsSection isAdmin={isAdmin} onConnectionsChanged={refetch} />
+
<RegisterMessagingAppDialog
open={registerOpen}
onClose={() => setRegisterOpen(false)}
@@ -232,7 +246,14 @@ export default function CollaborationsPage() {
onClose={() => setInstallTarget(null)}
/>
- <Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
+ <Dialog
+ open={!!deleteTarget}
+ onClose={() => {
+ if (deleting) return;
+ setDeleteError(null);
+ setDeleteTarget(null);
+ }}
+ >
<DialogTitle>Delete collaboration bridge</DialogTitle>
<DialogContent>
<DialogContentText>
@@ -241,9 +262,22 @@ export default function CollaborationsPage() {
{deleteTarget?.room_count ?? 0} associated room
{deleteTarget?.room_count === 1 ? "" : "s"} and external users.
</DialogContentText>
+ {deleteError && (
+ <Alert severity="error" sx={{ mt: 2 }}>
+ {deleteError}
+ </Alert>
+ )}
</DialogContent>
<DialogActions>
- <Button onClick={() => setDeleteTarget(null)}>Cancel</Button>
+ <Button
+ onClick={() => {
+ setDeleteError(null);
+ setDeleteTarget(null);
+ }}
+ disabled={deleting}
+ >
+ Cancel
+ </Button>
<Button
color="error"
variant="contained"
diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx
new file mode 100644
index 000000000..7f6b3c2f8
--- /dev/null
+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx
@@ -0,0 +1,96 @@
+import {
+ Alert,
+ Button,
+ CircularProgress,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogContentText,
+ DialogTitle,
+} from "@mui/material";
+import { useState } from "react";
+import { type InstalledApp, disconnectApp } from "../../data/api";
+import { titleCase } from "../../theme/hootFormat";
+
+/**
+ * Disconnecting is the only way an install-created connection can be removed,
+ * because it is the only one that revokes the token at the platform first.
+ * Deleting the connection instead is refused, so this dialog carries the
+ * warning that would otherwise sit on the delete: the rooms survive and go
+ * internal-only, which is not obvious and cannot be undone by re-installing.
+ *
+ * It can fail with the platform's own refusal, in which case nothing has been
+ * destroyed and trying again is the right move — so the error is shown here
+ * rather than closing the dialog on the way out.
+ */
+interface Props {
+ install: InstalledApp | null;
+ onClose: () => void;
+ onDisconnected: () => void;
+}
+
+export default function DisconnectAppDialog({
+ install,
+ onClose,
+ onDisconnected,
+}: Props) {
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const handleClose = () => {
+ if (submitting) return;
+ setError(null);
+ onClose();
+ };
+
+ const handleDisconnect = async () => {
+ if (!install) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await disconnectApp(install.id);
+ onDisconnected();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Failed to disconnect");
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog open={!!install} onClose={handleClose} fullWidth maxWidth="xs">
+ <DialogTitle>Disconnect the app</DialogTitle>
+ <DialogContent>
+ <DialogContentText>
+ Remove Switch from the {titleCase(install?.platform ?? "")} workspace{" "}
+ <b>{install?.external_workspace_id}</b>? The token is revoked at the
+ platform and the connection it created is removed.
+ </DialogContentText>
+ <DialogContentText sx={{ mt: 2 }}>
+ Rooms that used this connection are kept, but become internal-only:
+ they stop mirroring to the workspace, and installing again creates a
+ new connection rather than reattaching them.
+ </DialogContentText>
+ {error && (
+ <Alert severity="error" sx={{ mt: 2 }}>
+ {error}
+ </Alert>
+ )}
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={handleClose} disabled={submitting}>
+ Cancel
+ </Button>
+ <Button
+ color="error"
+ variant="contained"
+ onClick={handleDisconnect}
+ disabled={submitting}
+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}
+ >
+ Disconnect
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+}
diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.tsx
new file mode 100644
index 000000000..61cd9ef5d
--- /dev/null
+++ b/gateway/src/pages/collaborations/InstalledAppsSection.tsx
@@ -0,0 +1,235 @@
+import LinkOffOutlined from "@mui/icons-material/LinkOffOutlined";
+import {
+ Alert,
+ Box,
+ Button,
+ Chip,
+ CircularProgress,
+ IconButton,
+ Stack,
+ Tooltip,
+ Typography,
+} from "@mui/material";
+import type { GridColDef } from "@mui/x-data-grid";
+import { useCallback, useMemo, useState } from "react";
+import DataTable from "../../components/DataTable";
+import { type InstalledApp, beginAppInstall } from "../../data/api";
+import { useInstallablePlatforms, useInstalledApps } from "../../data/hooks";
+import { EM_DASH, MONO_SX, formatDate, titleCase } from "../../theme/hootFormat";
+import DisconnectAppDialog from "./DisconnectAppDialog";
+
+/**
+ * The other way a connection comes into being. Registering an app means
+ * creating one on the platform, choosing its scopes and pasting its token in
+ * here; installing means clicking a button and approving a consent screen,
+ * with this deployment's own app supplying the credentials.
+ *
+ * Both are shown because both exist, and an operator has to be able to tell
+ * which of their connections is which — a registered app's token is theirs to
+ * rotate and an installed one's is not, and only the second has to be removed
+ * through Disconnect.
+ *
+ * Renders nothing at all on a deployment that has no app of its own and has
+ * never had one, which is most of them: an empty section explaining a feature
+ * nobody here can use is worse than no section.
+ */
+type InstallRow = InstalledApp & { id: string };
+
+const STATUS_COLOR: Record<string, "success" | "warning" | "default"> = {
+ active: "success",
+ // Ended at the platform rather than here — somebody removed the app, or its
+ // token was killed. Warned rather than greyed out, because unlike
+ // "disconnected" it is news.
+ revoked: "warning",
+ disconnected: "default",
+};
+
+interface Props {
+ isAdmin: boolean;
+ // Disconnecting removes the connection the install created, so the list of
+ // connections above this section is stale once it succeeds.
+ onConnectionsChanged: () => void;
+}
+
+export default function InstalledAppsSection({
+ isAdmin,
+ onConnectionsChanged,
+}: Props) {
+ const { data: platforms } = useInstallablePlatforms();
+ const { data: installs, loading, refetch } = useInstalledApps();
+ const [starting, setStarting] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [disconnectTarget, setDisconnectTarget] = useState<InstalledApp | null>(
+ null,
+ );
+
+ const handleInstall = useCallback(async (platform: string) => {
+ setStarting(platform);
+ setError(null);
+ try {
+ // A top-level navigation, not a popup and not an iframe: the platform's
+ // consent screen sets cookies on its own domain and refuses to be
+ // framed, and a popup opened after an await is what a browser blocks.
+ // `starting` is deliberately left set — the page is on its way out.
+ window.location.href = await beginAppInstall(platform);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Failed to start the install");
+ setStarting(null);
+ }
+ }, []);
+
+ const handleDisconnected = useCallback(() => {
+ setDisconnectTarget(null);
+ refetch();
+ onConnectionsChanged();
+ }, [refetch, onConnectionsChanged]);
+
+ const columns = useMemo<GridColDef<InstallRow>[]>(
+ () => [
+ {
+ field: "platform",
+ headerName: "Platform",
+ width: 130,
+ renderCell: ({ value }) => (
+ <Chip label={titleCase(String(value))} size="small" />
+ ),
+ },
+ {
+ field: "external_workspace_id",
+ headerName: "Workspace",
+ width: 170,
+ renderCell: ({ value }) => (
+ <Box component="span" sx={MONO_SX}>
+ {String(value)}
+ </Box>
+ ),
+ },
+ {
+ field: "status",
+ headerName: "Status",
+ width: 140,
+ renderCell: ({ value }) => (
+ <Chip
+ label={titleCase(String(value))}
+ size="small"
+ color={STATUS_COLOR[value as string] ?? "default"}
+ />
+ ),
+ },
+ {
+ field: "scopes",
+ headerName: "Scopes",
+ flex: 1,
+ minWidth: 180,
+ // Verbatim, and in full on hover: a scope string that means nothing
+ // here is still the answer to why the platform refused a call.
+ renderCell: ({ value }) => (
+ <Tooltip title={String(value)}>
+ <Box component="span" sx={MONO_SX}>
+ {String(value)}
+ </Box>
+ </Tooltip>
+ ),
+ },
+ {
+ field: "installed_at",
+ headerName: "Installed",
+ width: 130,
+ valueFormatter: (value) => formatDate(value as string),
+ },
+ {
+ field: "ended_at",
+ headerName: "Ended",
+ width: 130,
+ valueFormatter: (value) =>
+ value ? formatDate(value as string) : EM_DASH,
+ },
+ ...(isAdmin
+ ? [
+ {
+ field: "actions" as const,
+ headerName: "",
+ width: 70,
+ sortable: false,
+ filterable: false,
+ align: "right" as const,
+ renderCell: ({ row }: { row: InstallRow }) =>
+ row.status === "active" ? (
+ <Tooltip title="Disconnect this app">
+ <IconButton
+ size="small"
+ onClick={() => setDisconnectTarget(row)}
+ >
+ <LinkOffOutlined fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ ) : null,
+ },
+ ]
+ : []),
+ ],
+ [isAdmin],
+ );
+
+ const rows = useMemo<InstallRow[]>(() => installs ?? [], [installs]);
+
+ const installable = platforms ?? [];
+ if (installable.length === 0 && rows.length === 0) return null;
+
+ return (
+ <Box mt={5}>
+ <Stack direction="row" alignItems="center" mb={1}>
+ <Typography variant="h5">Installed apps</Typography>
+ {isAdmin && (
+ <Stack direction="row" spacing={1} sx={{ ml: "auto" }}>
+ {installable.map((platform) => (
+ <Button
+ key={platform}
+ variant="contained"
+ disabled={starting !== null}
+ startIcon={
+ starting === platform ? (
+ <CircularProgress size={16} />
+ ) : undefined
+ }
+ onClick={() => handleInstall(platform)}
+ >
+ Add to {titleCase(platform)}
+ </Button>
+ ))}
+ </Stack>
+ )}
+ </Stack>
+
+ <Typography variant="body2" color="text.secondary" mb={2}>
+ Installing adds this Switch deployment&apos;s own app to your workspace.
+ The workspace grants it a token that Switch holds and you cannot see or
+ rotate, and the connection it creates receives messages over HTTPS
+ rather than the socket a registered app opens. Removing it has to go
+ through Disconnect, which revokes that token at the platform first.
+ </Typography>
+
+ {error && (
+ <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
+ {error}
+ </Alert>
+ )}
+
+ {loading ? (
+ <CircularProgress />
+ ) : rows.length === 0 ? (
+ <Typography variant="body2" color="text.secondary">
+ No workspaces yet. Use the button above to install the app into one.
+ </Typography>
+ ) : (
+ <DataTable rows={rows} columns={columns} height={360} />
+ )}
+
+ <DisconnectAppDialog
+ install={disconnectTarget}
+ onClose={() => setDisconnectTarget(null)}
+ onDisconnected={handleDisconnected}
+ />
+ </Box>
+ );
+}