Skip to content

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

Offer archive only on rooms the user can write, and report what bulk archive skipped

Abel Dantas0729f573635e
diff --git a/gateway/src/components/DataTable.tsx b/gateway/src/components/DataTable.tsx
index b90f7acb6..3b2d1cf7f 100644
--- a/gateway/src/components/DataTable.tsx
+++ b/gateway/src/components/DataTable.tsx
@@ -19,6 +19,8 @@ interface DataTableProps<T extends { id: string | number }> {
checkboxSelection?: boolean;
onRowSelectionModelChange?: (ids: GridRowId[]) => void;
onRowClick?: (params: GridRowParams<T>) => void;
+ /** Rows the user may not act on can't be ticked for a bulk action. */
+ isRowSelectable?: (params: GridRowParams<T>) => boolean;
sx?: SxProps<Theme>;
}
@@ -75,6 +77,7 @@ export default function DataTable<T extends { id: string | number }>({
checkboxSelection = false,
onRowSelectionModelChange,
onRowClick,
+ isRowSelectable,
sx,
}: DataTableProps<T>) {
const extraSx = Array.isArray(sx) ? sx : sx ? [sx] : [];
@@ -94,6 +97,7 @@ export default function DataTable<T extends { id: string | number }>({
: undefined
}
onRowClick={onRowClick}
+ isRowSelectable={isRowSelectable}
disableRowSelectionOnClick
sx={[HOOT_GRID_SX, { height: fillHeight ? "100%" : height }, ...extraSx]}
/>
diff --git a/gateway/src/pages/rooms/RoomsPage.test.tsx b/gateway/src/pages/rooms/RoomsPage.test.tsx
new file mode 100644
index 000000000..9f7c1ffc6
--- /dev/null
+++ b/gateway/src/pages/rooms/RoomsPage.test.tsx
@@ -0,0 +1,182 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import type { GridColDef, GridRowId, GridRowParams } from "@mui/x-data-grid";
+import { useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { RoomSummary } from "../../data/api";
+import * as api from "../../data/api";
+import { useAuth } from "../../data/AuthContext";
+import RoomsPage from "./RoomsPage";
+
+// Archiving a room is a write: its owner, an admin, or anyone in a publicly
+// writable room. The page offers it only there, and says when the server
+// changed fewer rooms than were asked for.
+
+vi.mock("react-router", () => ({
+ useNavigate: () => vi.fn(),
+}));
+
+vi.mock("../../data/AuthContext", () => ({
+ useAuth: vi.fn(),
+}));
+
+const room = (id: string, overrides: Partial<RoomSummary>) =>
+ ({
+ id,
+ name: id,
+ description: "",
+ channel_type: null,
+ agent_count: 0,
+ connected_user_count: 0,
+ connected_user_names: [],
+ bridge_id: null,
+ bridge_display_name: null,
+ group_id: null,
+ group_name: null,
+ owner_id: "someone",
+ owner_name: "someone",
+ read_visibility: "public",
+ write_visibility: "private",
+ created_at: "2026-10-01T00:00:00Z",
+ archived: false,
+ ...overrides,
+ }) as RoomSummary;
+
+const ROOMS = [
+ room("mine", { owner_id: "u1" }),
+ room("open", { write_visibility: "public" }),
+ room("readonly", {}),
+];
+
+vi.mock("../../data/hooks", () => ({
+ useRooms: () => ({ data: ROOMS, loading: false, error: null, refetch: vi.fn() }),
+ useRoomGroups: () => ({ data: [], loading: false, error: null, refetch: vi.fn() }),
+}));
+
+vi.mock("../../data/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../data/api")>();
+ return {
+ ...actual,
+ archiveRoom: vi.fn(),
+ unarchiveRoom: vi.fn(),
+ bulkArchiveRooms: vi.fn(),
+ };
+});
+
+// The data grid lays rows out from measured sizes, which jsdom does not have,
+// so it renders none. This draws each row, its selection checkbox when the
+// row is selectable, and its action cell plainly.
+vi.mock("../../components/DataTable", () => ({
+ default: function FakeTable({
+ rows,
+ columns,
+ isRowSelectable,
+ onRowSelectionModelChange,
+ }: {
+ rows: RoomSummary[];
+ columns: GridColDef<RoomSummary>[];
+ isRowSelectable?: (p: GridRowParams<RoomSummary>) => boolean;
+ onRowSelectionModelChange?: (ids: GridRowId[]) => void;
+ }) {
+ const [picked, setPicked] = useState<GridRowId[]>([]);
+ const actions = columns.find((c) => c.field === "actions");
+ return (
+ <div>
+ {rows.map((row) => (
+ <div key={row.id} data-testid={`row-${row.name}`}>
+ {row.name}
+ {(isRowSelectable?.({ row } as GridRowParams<RoomSummary>) ?? true) && (
+ <input
+ type="checkbox"
+ aria-label={`select ${row.name}`}
+ onChange={() => {
+ const next = [...picked, row.id];
+ setPicked(next);
+ onRowSelectionModelChange?.(next);
+ }}
+ />
+ )}
+ {actions?.renderCell?.({ row } as never)}
+ </div>
+ ))}
+ </div>
+ );
+ },
+}));
+
+beforeEach(() => {
+ vi.mocked(useAuth).mockReturnValue({
+ user: { id: "u1" },
+ canAdminTenant: false,
+ } as unknown as ReturnType<typeof useAuth>);
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("RoomsPage archive", () => {
+ it("offers archive only on rooms the user can write", () => {
+ render(<RoomsPage />);
+
+ for (const name of ["mine", "open"]) {
+ const row = screen.getByTestId(`row-${name}`);
+ expect(within(row).getByRole("button", { name: "Archive" })).toBeTruthy();
+ expect(within(row).getByRole("checkbox")).toBeTruthy();
+ }
+ const readonly = screen.getByTestId("row-readonly");
+ expect(within(readonly).queryByRole("button", { name: "Archive" })).toBeNull();
+ expect(within(readonly).queryByRole("checkbox")).toBeNull();
+ });
+
+ it("offers archive on every room to an admin", () => {
+ vi.mocked(useAuth).mockReturnValue({
+ user: { id: "u1" },
+ canAdminTenant: true,
+ } as unknown as ReturnType<typeof useAuth>);
+ render(<RoomsPage />);
+
+ expect(screen.getAllByRole("button", { name: "Archive" })).toHaveLength(3);
+ });
+
+ it("says when a bulk archive changed only some rooms", async () => {
+ vi.mocked(api.bulkArchiveRooms).mockResolvedValue({ updated: 1 });
+ render(<RoomsPage />);
+ fireEvent.click(screen.getByRole("checkbox", { name: "select mine" }));
+ fireEvent.click(screen.getByRole("checkbox", { name: "select open" }));
+
+ fireEvent.click(screen.getByRole("button", { name: "Archive (2)" }));
+
+ await waitFor(() =>
+ expect(api.bulkArchiveRooms).toHaveBeenCalledWith(["mine", "open"], true),
+ );
+ expect(
+ (await screen.findByRole("alert")).textContent,
+ ).toContain("Archived 1 of 2; 1 you can't change or no longer exist.");
+ });
+
+ it("says when a bulk archive failed", async () => {
+ vi.mocked(api.bulkArchiveRooms).mockResolvedValue(null);
+ render(<RoomsPage />);
+ fireEvent.click(screen.getByRole("checkbox", { name: "select mine" }));
+
+ fireEvent.click(screen.getByRole("button", { name: "Archive (1)" }));
+
+ expect((await screen.findByRole("alert")).textContent).toContain(
+ "Couldn't archive the selected rooms.",
+ );
+ });
+
+ it("says when archiving one room failed", async () => {
+ vi.mocked(api.archiveRoom).mockRejectedValue(new Error("Not authorized"));
+ render(<RoomsPage />);
+
+ fireEvent.click(
+ within(screen.getByTestId("row-open")).getByRole("button", { name: "Archive" }),
+ );
+
+ expect((await screen.findByRole("alert")).textContent).toContain(
+ "Couldn't archive the room: Not authorized",
+ );
+ });
+});
diff --git a/gateway/src/pages/rooms/RoomsPage.tsx b/gateway/src/pages/rooms/RoomsPage.tsx
index a6ff4c547..e7f061fc0 100644
--- a/gateway/src/pages/rooms/RoomsPage.tsx
+++ b/gateway/src/pages/rooms/RoomsPage.tsx
@@ -3,7 +3,7 @@ import AccountTreeIcon from "@mui/icons-material/AccountTree";
import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
import FolderOutlined from "@mui/icons-material/FolderOutlined";
import UnarchiveOutlined from "@mui/icons-material/UnarchiveOutlined";
-import { Box, Button, Chip, CircularProgress, Stack, Typography } from "@mui/material";
+import { Alert, Box, Button, Chip, CircularProgress, Stack, Typography } from "@mui/material";
import type { GridColDef, GridRowId } from "@mui/x-data-grid";
import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router";
@@ -15,9 +15,11 @@ import {
bulkArchiveRooms,
unarchiveRoom,
} from "../../data/api";
+import { useAuth } from "../../data/AuthContext";
import { useRoomGroups, useRooms } from "../../data/hooks";
import { EM_DASH, MONO_SX, channelTypeLabel, formatDate } from "../../theme/hootFormat";
import { buildGroupIndex, effectiveColor, groupPathName } from "./groupTree";
+import { canWriteRoom } from "./roomAccess";
import { RoomFilters, filterRooms, useRoomFilterState } from "./roomFilters";
function Missing() {
@@ -47,6 +49,11 @@ export default function RoomsPage() {
const filters = useRoomFilterState();
const [selected, setSelected] = useState<GridRowId[]>([]);
const [busy, setBusy] = useState(false);
+ const [notice, setNotice] = useState<{
+ severity: "error" | "warning";
+ text: string;
+ } | null>(null);
+ const { user, canAdminTenant } = useAuth();
const { data: rooms, loading, refetch } = useRooms(
filters.debouncedSearch || undefined,
@@ -72,12 +79,29 @@ export default function RoomsPage() {
],
);
+ // Archiving is a write: the owner, an admin, or anyone in a publicly
+ // writable room. Other rooms get no archive action and can't be selected.
+ const canWrite = useCallback(
+ (room: RoomSummary) => canWriteRoom(room, user?.id, canAdminTenant),
+ [user, canAdminTenant],
+ );
+
const handleToggleArchive = useCallback(
async (roomId: string, archived: boolean) => {
- if (archived) {
- await unarchiveRoom(roomId);
- } else {
- await archiveRoom(roomId);
+ setNotice(null);
+ try {
+ if (archived) {
+ await unarchiveRoom(roomId);
+ } else {
+ await archiveRoom(roomId);
+ }
+ } catch (err) {
+ setNotice({
+ severity: "error",
+ text: `Couldn't ${archived ? "unarchive" : "archive"} the room: ${
+ err instanceof Error ? err.message : "unknown error"
+ }`,
+ });
}
refetch();
},
@@ -86,9 +110,26 @@ export default function RoomsPage() {
const handleBulkArchive = useCallback(async () => {
setBusy(true);
+ setNotice(null);
const ids = selected.map(String);
// Active view → archive the selection; Archived view → unarchive it.
- await bulkArchiveRooms(ids, !viewingArchived);
+ const action = viewingArchived ? "unarchive" : "archive";
+ const done = viewingArchived ? "Unarchived" : "Archived";
+ const result = await bulkArchiveRooms(ids, !viewingArchived);
+ // The server skips, without failing, any room the user can't change or
+ // that is gone, and says how many it did change.
+ if (result === null) {
+ setNotice({
+ severity: "error",
+ text: `Couldn't ${action} the selected rooms.`,
+ });
+ } else if (result.updated < ids.length) {
+ const skipped = ids.length - result.updated;
+ setNotice({
+ severity: "warning",
+ text: `${done} ${result.updated} of ${ids.length}; ${skipped} you can't change or no longer exist.`,
+ });
+ }
setSelected([]);
setBusy(false);
refetch();
@@ -176,28 +217,29 @@ export default function RoomsPage() {
width: 116,
sortable: false,
filterable: false,
- renderCell: ({ row }) => (
- <Button
- size="small"
- color="inherit"
- startIcon={
- row.archived ? (
- <UnarchiveOutlined fontSize="small" />
- ) : (
- <ArchiveOutlined fontSize="small" />
- )
- }
- onClick={(e) => {
- e.stopPropagation();
- handleToggleArchive(row.id, row.archived);
- }}
- >
- {row.archived ? "Unarchive" : "Archive"}
- </Button>
- ),
+ renderCell: ({ row }) =>
+ canWrite(row) && (
+ <Button
+ size="small"
+ color="inherit"
+ startIcon={
+ row.archived ? (
+ <UnarchiveOutlined fontSize="small" />
+ ) : (
+ <ArchiveOutlined fontSize="small" />
+ )
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ handleToggleArchive(row.id, row.archived);
+ }}
+ >
+ {row.archived ? "Unarchive" : "Archive"}
+ </Button>
+ ),
},
],
- [handleToggleArchive, byId],
+ [handleToggleArchive, byId, canWrite],
);
return (
@@ -241,6 +283,12 @@ export default function RoomsPage() {
</Stack>
</Stack>
+ {notice && (
+ <Alert severity={notice.severity} onClose={() => setNotice(null)} sx={{ mb: 2 }}>
+ {notice.text}
+ </Alert>
+ )}
+
<RoomFilters rooms={rooms ?? []} groups={groupList} state={filters} />
{loading ? (
@@ -252,6 +300,7 @@ export default function RoomsPage() {
fillHeight
checkboxSelection
onRowSelectionModelChange={setSelected}
+ isRowSelectable={({ row }) => canWrite(row)}
onRowClick={(params) => navigate(`/rooms/${params.id}`)}
sx={{ "& .MuiDataGrid-row": { cursor: "pointer" } }}
/>
diff --git a/gateway/src/pages/rooms/roomAccess.ts b/gateway/src/pages/rooms/roomAccess.ts
new file mode 100644
index 000000000..d06875e99
--- /dev/null
+++ b/gateway/src/pages/rooms/roomAccess.ts
@@ -0,0 +1,17 @@
+import type { VisibilityPair } from "../../data/visibility";
+
+/** Whether a user may write to a room, as the server decides it (`can(...,
+ * "write", room)` in `switch_core.authz`): its owner, a tenant admin, or
+ * anyone when the room is publicly writable. */
+export function canWriteRoom(
+ room: VisibilityPair & { owner_id: string | null },
+ userId: string | null | undefined,
+ canAdminTenant: boolean,
+): boolean {
+ if (!userId) return false;
+ return (
+ canAdminTenant ||
+ (room.owner_id !== null && room.owner_id === userId) ||
+ room.write_visibility === "public"
+ );
+}