refactor(site): migrate the connection logs filter to use new combobox variant (#32367)

> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Migrates the connection logs filter to use the newer variant on the
Connection Logs page.

<img width="865" height="486" alt="image"
src="https://github.com/user-attachments/assets/dee5f2da-7627-40e9-a468-a305048a1982"
/>
This commit is contained in:
Jake Howell authored and GitHub committed 2026-11-19 12:35:41 +11:00
1 parent b4f0e3b131
commit c8d29a1ce3
7 files changed
+270 -386

No files matched your search

@@ -8,8 +8,6 @@ import {
import { useAuthenticated } from "#/hooks/useAuthenticated";
import { type UseFilterMenuOptions, useFilterMenu } from "./menu";
export const DEFAULT_USER_FILTER_WIDTH = 175;
export const useUserFilterMenu = ({
value,
onChange,
-120
View File
@@ -1,120 +0,0 @@
/**
* @file Defines a centralized place for filter dropdown groups that are
* relevant across multiple pages within the Coder UI.
*
* @todo 2024-09-06 - Figure out how to move the user dropdown group into this
* file (or whether there are enough subtle differences that it's not worth
* centralizing the logic). We currently have two separate implementations for
* the workspaces and audits page that have a risk of getting out of sync.
*/
import { API } from "#/api/api";
import { Avatar } from "#/components/Avatar/Avatar";
import { ComboboxInput } from "#/components/Combobox/Combobox";
import {
type UseFilterMenuOptions,
useFilterMenu,
} from "#/components/Filter/menu";
import {
SelectFilter,
type SelectFilterOption,
} from "#/components/Filter/SelectFilter";
// Organization helpers ////////////////////////////////////////////////////////
export const useOrganizationsFilterMenu = ({
value,
onChange,
}: Pick<UseFilterMenuOptions, "value" | "onChange">) => {
return useFilterMenu({
onChange,
value,
id: "organizations",
getSelectedOption: async () => {
if (value) {
const organizations = await API.getOrganizations();
const organization = organizations.find((o) => o.name === value);
if (organization) {
return {
label: organization.display_name || organization.name,
value: organization.name,
startIcon: (
<Avatar
key={organization.id}
size="sm"
fallback={organization.display_name || organization.name}
src={organization.icon}
/>
),
};
}
}
return null;
},
getOptions: async () => {
// Only show the organizations for which you can view audit logs.
const organizations = await API.getOrganizations();
const permissions = await API.checkAuthorization({
checks: Object.fromEntries(
organizations.map((organization) => [
organization.id,
{
object: {
resource_type: "audit_log",
organization_id: organization.id,
},
action: "read",
},
]),
),
});
return organizations
.filter((organization) => permissions[organization.id])
.map<SelectFilterOption>((organization) => ({
label: organization.display_name || organization.name,
value: organization.name,
startIcon: (
<Avatar
key={organization.id}
size="sm"
fallback={organization.display_name || organization.name}
src={organization.icon}
/>
),
}));
},
});
};
export type OrganizationsFilterMenu = ReturnType<
typeof useOrganizationsFilterMenu
>;
type OrganizationsMenuProps = {
menu: OrganizationsFilterMenu;
width?: number;
};
export const OrganizationsMenu: React.FC<OrganizationsMenuProps> = ({
menu,
width,
}) => {
return (
<SelectFilter
label="Select an organization"
placeholder="All organizations"
emptyText="No organizations found"
options={menu.searchOptions}
onSelect={menu.selectOption}
selectedOption={menu.selectedOption ?? undefined}
searchLabel="Search organization"
selectFilterSearch={
<ComboboxInput
placeholder="Search organization..."
value={menu.query}
onValueChange={menu.setQuery}
/>
}
width={width}
/>
);
};
@@ -0,0 +1,53 @@
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useSearchParams } from "react-router";
import { useFilter } from "#/components/Filter/Filter";
import { renderWithAuth } from "#/testHelpers/renderHelpers";
import { ConnectionLogFilter } from "./ConnectionLogFilter";
const Harness = ({ onChange }: { onChange: (query: string) => void }) => {
const [searchParams, setSearchParams] = useSearchParams();
const filter = useFilter({
searchParams,
onSearchParamsChange: setSearchParams,
onUpdate: onChange,
});
return <ConnectionLogFilter filter={filter} />;
};
describe("ConnectionLogFilter", () => {
it("replaces the query with the active SSH preset", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithAuth(<Harness onChange={onChange} />, {
route: "/?filter=status:completed%20workspace_owner:alice",
});
await user.click(await screen.findByRole("button", { name: "Filters" }));
await user.click(
await screen.findByRole("option", { name: "Active SSH connections" }),
);
await waitFor(() =>
expect(onChange).toHaveBeenLastCalledWith("status:ongoing method:ssh"),
);
});
it("replaces status without losing the legacy type or advanced fields", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderWithAuth(<Harness onChange={onChange} />, {
route: "/?filter=status:completed%20type:ssh%20app:code-server",
});
await user.click(await screen.findByRole("button", { name: "Filters" }));
await user.hover(await screen.findByRole("option", { name: "Status" }));
// user-event omits relatedTarget when entering the flyout, closing it.
await userEvent.click(
await screen.findByRole("button", { name: "Ongoing" }),
{ skipHover: true },
);
await waitFor(() =>
expect(onChange).toHaveBeenLastCalledWith(
"status:ongoing type:ssh app:code-server",
),
);
});
});
@@ -1,199 +1,149 @@
import capitalize from "lodash/capitalize";
import {
type ConnectionLogMethod,
Building2Icon,
CircleDotIcon,
PlugIcon,
Settings2Icon,
UserIcon,
} from "lucide-react";
import { useMemo } from "react";
import { useQueryClient } from "react-query";
import {
getValidationErrorMessage,
hasError,
isApiValidationError,
} from "#/api/errors";
import {
ConnectionLogMethods,
type ConnectionLogStatus,
ConnectionLogStatuses,
} from "#/api/typesGenerated";
import { Alert } from "#/components/Alert/Alert";
import type { UseFilterResult } from "#/components/Filter/Filter";
import { FilterCombobox } from "#/components/Filter/FilterCombobox/FilterCombobox";
import { extractFreeText } from "#/components/Filter/FilterCombobox/filterQuery";
import type {
FilterCategory,
FilterOption,
} from "#/components/Filter/FilterCombobox/types";
import { parseFilterQuery } from "#/components/Filter/filterQuery";
import { getOrganizationFilterOptions } from "#/components/Filter/organizationOptions";
import {
Filter,
MenuSkeleton,
type useFilter,
} from "#/components/Filter/Filter";
import {
type UseFilterMenuOptions,
useFilterMenu,
} from "#/components/Filter/menu";
import {
SelectFilter,
type SelectFilterOption,
} from "#/components/Filter/SelectFilter";
import {
DEFAULT_USER_FILTER_WIDTH,
type UserFilterMenu,
UserMenu,
} from "#/components/Filter/UserFilter";
import {
type OrganizationsFilterMenu,
OrganizationsMenu,
} from "#/modules/tableFiltering/options";
import { docs } from "#/utils/docs";
getMeUserFilterOptions,
getUserFilterOptions,
} from "#/components/Filter/userOptions";
import { useAuthenticated } from "#/hooks/useAuthenticated";
import { useDashboard } from "#/modules/dashboard/useDashboard";
import { connectionLogMethodLabels } from "./connectionLogMethodLabels";
type ConnectionLogFilterValues = {
status?: ConnectionLogStatus;
method?: ConnectionLogMethod;
workspace_owner?: string;
organization?: string;
};
const buildConnectionLogFilterQuery = (
v: ConnectionLogFilterValues,
): string => {
const parts: string[] = [];
if (v.status) parts.push(`status:${v.status}`);
if (v.method) parts.push(`method:${v.method}`);
if (v.workspace_owner) parts.push(`workspace_owner:${v.workspace_owner}`);
if (v.organization) parts.push(`organization:${v.organization}`);
return parts.join(" ");
};
const CONNECTION_LOG_PRESET_FILTERS = [
const statusOptions: FilterOption[] = ConnectionLogStatuses.map((status) => ({
value: status,
label: capitalize(status),
}));
const methodOptions: FilterOption[] = ConnectionLogMethods.map((method) => ({
value: method,
label: connectionLogMethodLabels[method],
}));
const presets: FilterOption[] = [
{
query: buildConnectionLogFilterQuery({ status: "ongoing", method: "ssh" }),
name: "Active SSH connections",
label: "Active SSH connections",
value: "active_ssh_connections",
startIcon: <Settings2Icon />,
query: "status:ongoing method:ssh",
},
] satisfies { name: string; query: string }[];
];
type ConnectionLogFilterProps = {
filter: ReturnType<typeof useFilter>;
filter: UseFilterResult;
error?: unknown;
menus: {
user: UserFilterMenu;
status: StatusFilterMenu;
method: MethodFilterMenu;
// The organization menu is only provided in a multi-org setup.
organization?: OrganizationsFilterMenu;
};
};
/** Filters connection events while retaining support for saved legacy queries. */
export const ConnectionLogFilter: React.FC<ConnectionLogFilterProps> = ({
filter,
error,
menus,
}) => {
const width = menus.organization ? DEFAULT_USER_FILTER_WIDTH : undefined;
const { permissions, user: me } = useAuthenticated();
const { showOrganizations } = useDashboard();
const queryClient = useQueryClient();
const categories = useMemo(() => {
const next: FilterCategory[] = [
{
key: "workspace_owner",
optionsKey: "connectionLogs.workspace_owner",
label: "Owner",
icon: <UserIcon />,
getOptions: permissions.viewAllUsers
? (query) => getUserFilterOptions(query, me, queryClient)
: (query) => getMeUserFilterOptions(query, me),
},
{
key: "status",
optionsKey: "connectionLogs.status",
label: "Status",
icon: <CircleDotIcon />,
getOptions: async () => statusOptions,
},
{
key: "method",
optionsKey: "connectionLogs.method",
label: "Method",
icon: <PlugIcon />,
getOptions: async () => methodOptions,
},
];
if (showOrganizations) {
next.push({
key: "organization",
optionsKey: "connectionLogs.organization",
label: "Organization",
icon: <Building2Icon />,
getOptions: (query) =>
getOrganizationFilterOptions(query, queryClient, {
object: { resource_type: "audit_log" },
action: "read",
}),
});
}
next.push({
key: "preset",
optionsKey: "connectionLogs.presets",
label: "Presets",
chipKeys: [],
inlineOptions: true,
inlineOptionsLabel: "Show…",
inlineOptionsIcons: true,
getOptions: async () => presets,
});
return next.map((category) => ({ ...category, singleSelect: true }));
}, [me, permissions.viewAllUsers, queryClient, showOrganizations]);
const handleChange = (query: string) => {
// The API rejects method combined with the deprecated type filter.
filter.update(
parseFilterQuery(query).method ? extractFreeText(query, ["type"]) : query,
);
};
return (
<>
{/* Saved links and bookmarks can still carry the deprecated filter. */}
<div className="mb-6 flex min-w-0 flex-col">
{filter.values.type && (
<Alert severity="warning" className="mb-4">
The <code>type</code> filter is deprecated and will be removed in a
future release. Use <code>method</code> and <code>app</code> instead.
</Alert>
)}
<Filter
learnMoreLink={docs(
"/admin/monitoring/connection-logs#how-to-filter-connection-logs",
)}
presets={CONNECTION_LOG_PRESET_FILTERS}
isLoading={menus.user.isInitializing}
filter={filter}
error={error}
options={
<>
<UserMenu
placeholder="All owners"
menu={menus.user}
width={width}
/>
<StatusMenu menu={menus.status} width={width} />
<MethodMenu menu={menus.method} width={width} />
{menus.organization && (
<OrganizationsMenu menu={menus.organization} width={width} />
)}
</>
}
optionsSkeleton={
<>
<MenuSkeleton />
<MenuSkeleton />
<MenuSkeleton />
{menus.organization && <MenuSkeleton />}
</>
<FilterCombobox
value={filter.query}
onChange={handleChange}
categories={categories}
placeholder="Search and filter connection logs…"
className="w-full min-w-0 self-start sm:w-auto sm:min-w-lg sm:max-w-full"
errorMessage={
hasError(error) && isApiValidationError(error)
? getValidationErrorMessage(error)
: undefined
}
/>
</>
);
};
export const useStatusFilterMenu = ({
value,
onChange,
}: Pick<UseFilterMenuOptions, "value" | "onChange">) => {
const statusOptions: SelectFilterOption[] = ConnectionLogStatuses.map(
(status) => ({
value: status,
label: capitalize(status),
}),
);
return useFilterMenu({
onChange,
value,
id: "status",
getSelectedOption: async () =>
statusOptions.find((option) => option.value === value) ?? null,
getOptions: async () => statusOptions,
});
};
type StatusFilterMenu = ReturnType<typeof useStatusFilterMenu>;
type StatusMenuProps = {
menu: StatusFilterMenu;
width?: number;
};
const StatusMenu: React.FC<StatusMenuProps> = ({ menu, width }) => {
return (
<SelectFilter
label="Filter by session status"
placeholder="All sessions"
options={menu.searchOptions}
onSelect={menu.selectOption}
selectedOption={menu.selectedOption ?? undefined}
width={width}
/>
);
};
export const useMethodFilterMenu = ({
value,
onChange,
}: Pick<UseFilterMenuOptions, "value" | "onChange">) => {
const methodOptions: SelectFilterOption[] = ConnectionLogMethods.map(
(method) => ({
value: method,
label: connectionLogMethodLabels[method],
}),
);
return useFilterMenu({
onChange,
value,
id: "connection_method",
getSelectedOption: async () =>
methodOptions.find((option) => option.value === value) ?? null,
getOptions: async () => methodOptions,
});
};
type MethodFilterMenu = ReturnType<typeof useMethodFilterMenu>;
type MethodMenuProps = {
menu: MethodFilterMenu;
width?: number;
};
const MethodMenu: React.FC<MethodMenuProps> = ({ menu, width }) => {
return (
<SelectFilter
label="Filter by connection method"
placeholder="All methods"
options={menu.searchOptions}
onSelect={menu.selectOption}
selectedOption={menu.selectedOption ?? undefined}
width={width}
/>
</div>
);
};
@@ -121,11 +121,12 @@ describe("ConnectionLogPage", () => {
await renderPage();
const user = userEvent.setup();
await user.click(
screen.getByRole("button", { name: "Filter by connection method" }),
);
await user.click(
await screen.findByRole("option", { name: "Web Terminal" }),
await user.click(screen.getByRole("button", { name: "Filters" }));
await user.hover(await screen.findByRole("option", { name: "Method" }));
// user-event omits relatedTarget when entering the flyout, closing it.
await userEvent.click(
await screen.findByRole("button", { name: "Web Terminal" }),
{ skipHover: true },
);
await waitFor(() =>
@@ -145,14 +146,48 @@ describe("ConnectionLogPage", () => {
count: 1,
count_cap: 0,
});
await renderPage({ filter: "status:ongoing type:ssh" });
expect(screen.getByRole("alert")).toHaveTextContent(
"The type filter is deprecated",
);
await renderPage({
filter: "status:ongoing type:ssh app:code-server workspace_owner:alice",
});
const user = userEvent.setup();
await user.click(
screen.getByRole("button", { name: "Filter by connection method" }),
await user.click(screen.getByRole("button", { name: "Filters" }));
await user.hover(await screen.findByRole("option", { name: "Method" }));
await userEvent.click(
await screen.findByRole("button", { name: "SSH" }),
{ skipHover: true },
);
await waitFor(() =>
expect(getConnectionLogsSpy).toHaveBeenLastCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: 0,
q: "status:ongoing workspace_owner:alice method:ssh app:code-server",
}),
);
});
it("resets page to 1 when filter is changed", async () => {
const getConnectionLogsSpy = vi
.spyOn(API, "getConnectionLogs")
.mockResolvedValue({
connection_logs: [MockConnectedSSHConnectionLog],
count: 100,
count_cap: 0,
});
await renderPage({ page: 2 });
expect(getConnectionLogsSpy).toHaveBeenLastCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: DEFAULT_RECORDS_PER_PAGE,
q: "",
});
const user = userEvent.setup();
await user.type(
screen.getByRole("combobox", {
name: "Search and filter connection logs…",
}),
"method:",
);
await user.click(await screen.findByRole("option", { name: "SSH" }));
@@ -160,27 +195,7 @@ describe("ConnectionLogPage", () => {
expect(getConnectionLogsSpy).toHaveBeenLastCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: 0,
q: "status:ongoing method:ssh",
}),
);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("resets page to 1 when filter is changed", async () => {
await renderPage({ page: 2 });
const getConnectionLogsSpy = vi.spyOn(API, "getConnectionLogs");
getConnectionLogsSpy.mockClear();
const filterField = screen.getByLabelText("Search");
const query = "method:ssh status:ongoing";
await userEvent.type(filterField, query);
await waitFor(() =>
expect(getConnectionLogsSpy).toHaveBeenCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: 0,
q: query,
q: "method:ssh",
}),
);
});
@@ -1,18 +1,11 @@
import { useSearchParams } from "react-router";
import { paginatedConnectionLogs } from "#/api/queries/connectionlog";
import { useFilter } from "#/components/Filter/Filter";
import { useUserFilterMenu } from "#/components/Filter/UserFilter";
import { isNonInitialPage } from "#/components/PaginationWidget/utils";
import { useAuthenticated } from "#/hooks/useAuthenticated";
import { usePaginatedQuery } from "#/hooks/usePaginatedQuery";
import { useDashboard } from "#/modules/dashboard/useDashboard";
import { useFeatureVisibility } from "#/modules/dashboard/useFeatureVisibility";
import { useOrganizationsFilterMenu } from "#/modules/tableFiltering/options";
import { pageTitle } from "#/utils/page";
import {
useMethodFilterMenu,
useStatusFilterMenu,
} from "./ConnectionLogFilter";
import { ConnectionLogPageView } from "./ConnectionLogPageView";
const ConnectionLogPage: React.FC = () => {
@@ -25,8 +18,6 @@ const ConnectionLogPage: React.FC = () => {
// see: https://github.com/coder/coder/issues/14798
const isConnectionLogVisible = feats.connection_log || false;
const { showOrganizations } = useDashboard();
const [searchParams, setSearchParams] = useSearchParams();
const connectionlogsQuery = usePaginatedQuery(
paginatedConnectionLogs(searchParams),
@@ -37,43 +28,6 @@ const ConnectionLogPage: React.FC = () => {
onUpdate: connectionlogsQuery.goToFirstPage,
});
const userMenu = useUserFilterMenu({
value: filter.values.workspace_owner,
onChange: (option) =>
filter.update({
...filter.values,
workspace_owner: option?.value,
}),
});
const statusMenu = useStatusFilterMenu({
value: filter.values.status,
onChange: (option) =>
filter.update({
...filter.values,
status: option?.value,
}),
});
const methodMenu = useMethodFilterMenu({
value: filter.values.method,
onChange: (option) => {
// Saved links can carry the deprecated type filter, which the API
// rejects when combined with method.
const { type: _legacyType, ...values } = filter.values;
filter.update({ ...values, method: option?.value });
},
});
const organizationsMenu = useOrganizationsFilterMenu({
value: filter.values.organization,
onChange: (option) =>
filter.update({
...filter.values,
organization: option?.value,
}),
});
return (
<>
<title>{pageTitle("Connection log")}</title>
@@ -88,12 +42,6 @@ const ConnectionLogPage: React.FC = () => {
filterProps={{
filter,
error: connectionlogsQuery.error,
menus: {
user: userMenu,
status: statusMenu,
method: methodMenu,
organization: showOrganizations ? organizationsMenu : undefined,
},
}}
/>
</>
@@ -1,9 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, within } from "storybook/test";
import {
getDefaultFilterProps,
MockMenu,
} from "#/components/Filter/storyHelpers";
import { expect, userEvent, within } from "storybook/test";
import { getDefaultFilterProps } from "#/components/Filter/storyHelpers";
import {
mockInitialRenderResult,
mockSuccessResult,
@@ -14,8 +11,13 @@ import {
MockDisconnectedSSHConnectionLog,
MockPermissions,
MockUserOwner,
mockApiError,
} from "#/testHelpers/entities";
import { pixelWithTablet } from "#/testHelpers/pixel";
import {
withAuthProvider,
withDashboardProvider,
} from "#/testHelpers/storybook";
import { docs } from "#/utils/docs";
import { ConnectionLogPageView } from "./ConnectionLogPageView";
@@ -24,23 +26,20 @@ type FilterProps = React.ComponentProps<
>["filterProps"];
const defaultFilterProps = getDefaultFilterProps<FilterProps>({
query: `username:${MockUserOwner.username}`,
query: `workspace_owner:${MockUserOwner.username}`,
values: {
username: MockUserOwner.username,
workspace_owner: MockUserOwner.username,
status: undefined,
method: undefined,
organization: undefined,
},
menus: {
user: MockMenu,
status: MockMenu,
method: MockMenu,
},
});
const meta: Meta<typeof ConnectionLogPageView> = {
title: "pages/ConnectionLogPage",
component: ConnectionLogPageView,
decorators: [withDashboardProvider, withAuthProvider],
parameters: { user: MockUserOwner },
args: {
connectionLogs: [
MockConnectedSSHConnectionLog,
@@ -124,3 +123,44 @@ export const NotVisibleWithoutLicenseAccess: Story = {
).not.toBeInTheDocument();
},
};
export const FiltersOpen: Story = {
args: ConnectionLog.args,
play: async ({ canvasElement }) => {
await userEvent.click(
within(canvasElement).getByRole("button", { name: "Filters" }),
);
},
};
export const DeprecatedType: Story = {
args: {
...ConnectionLog.args,
filterProps: getDefaultFilterProps<FilterProps>({
query: "type:ssh",
values: { type: "ssh" },
}),
},
};
const mockInvalidFilterError = mockApiError({
message: "Invalid connection log search query.",
validations: [
{ field: "status", detail: "Status must be ongoing or completed." },
],
});
export const InvalidFilter: Story = {
args: {
connectionLogs: undefined,
connectionLogsQuery: mockInitialRenderResult,
error: mockInvalidFilterError,
filterProps: {
...getDefaultFilterProps<FilterProps>({
query: "status:invalid",
values: { status: "invalid" },
}),
error: mockInvalidFilterError,
},
},
};