From c8d29a1ce335deba0352255cf3a17a5dcebdbdbd Mon Sep 17 00:00:00 2001 From: Jake Howell Date: Thu, 19 Nov 2026 12:35:41 +1100 Subject: [PATCH] refactor(site): migrate the connection logs filter to use new combobox variant (#32367) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 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. image --- site/src/components/Filter/UserFilter.tsx | 2 - site/src/modules/tableFiltering/options.tsx | 120 -------- .../ConnectionLogFilter.test.tsx | 53 ++++ .../ConnectionLogPage/ConnectionLogFilter.tsx | 286 ++++++++---------- .../ConnectionLogPage.test.tsx | 79 +++-- .../ConnectionLogPage/ConnectionLogPage.tsx | 52 ---- .../ConnectionLogPageView.stories.tsx | 64 +++- 7 files changed, 270 insertions(+), 386 deletions(-) delete mode 100644 site/src/modules/tableFiltering/options.tsx create mode 100644 site/src/pages/ConnectionLogPage/ConnectionLogFilter.test.tsx diff --git a/site/src/components/Filter/UserFilter.tsx b/site/src/components/Filter/UserFilter.tsx index c44e4b952bd..80cf7bb6b11 100644 --- a/site/src/components/Filter/UserFilter.tsx +++ b/site/src/components/Filter/UserFilter.tsx @@ -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, diff --git a/site/src/modules/tableFiltering/options.tsx b/site/src/modules/tableFiltering/options.tsx deleted file mode 100644 index 39ea4c7f405..00000000000 --- a/site/src/modules/tableFiltering/options.tsx +++ /dev/null @@ -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) => { - 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: ( - - ), - }; - } - } - 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((organization) => ({ - label: organization.display_name || organization.name, - value: organization.name, - startIcon: ( - - ), - })); - }, - }); -}; - -export type OrganizationsFilterMenu = ReturnType< - typeof useOrganizationsFilterMenu ->; - -type OrganizationsMenuProps = { - menu: OrganizationsFilterMenu; - width?: number; -}; - -export const OrganizationsMenu: React.FC = ({ - menu, - width, -}) => { - return ( - - } - width={width} - /> - ); -}; diff --git a/site/src/pages/ConnectionLogPage/ConnectionLogFilter.test.tsx b/site/src/pages/ConnectionLogPage/ConnectionLogFilter.test.tsx new file mode 100644 index 00000000000..e96e5221b62 --- /dev/null +++ b/site/src/pages/ConnectionLogPage/ConnectionLogFilter.test.tsx @@ -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 ; +}; + +describe("ConnectionLogFilter", () => { + it("replaces the query with the active SSH preset", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + renderWithAuth(, { + 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(, { + 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", + ), + ); + }); +}); diff --git a/site/src/pages/ConnectionLogPage/ConnectionLogFilter.tsx b/site/src/pages/ConnectionLogPage/ConnectionLogFilter.tsx index 7a5986786af..632ffe447c2 100644 --- a/site/src/pages/ConnectionLogPage/ConnectionLogFilter.tsx +++ b/site/src/pages/ConnectionLogPage/ConnectionLogFilter.tsx @@ -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: , + query: "status:ongoing method:ssh", }, -] satisfies { name: string; query: string }[]; +]; type ConnectionLogFilterProps = { - filter: ReturnType; + 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 = ({ 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: , + getOptions: permissions.viewAllUsers + ? (query) => getUserFilterOptions(query, me, queryClient) + : (query) => getMeUserFilterOptions(query, me), + }, + { + key: "status", + optionsKey: "connectionLogs.status", + label: "Status", + icon: , + getOptions: async () => statusOptions, + }, + { + key: "method", + optionsKey: "connectionLogs.method", + label: "Method", + icon: , + getOptions: async () => methodOptions, + }, + ]; + if (showOrganizations) { + next.push({ + key: "organization", + optionsKey: "connectionLogs.organization", + label: "Organization", + icon: , + 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. */} +
{filter.values.type && ( The type filter is deprecated and will be removed in a future release. Use method and app instead. )} - - - - - {menus.organization && ( - - )} - - } - optionsSkeleton={ - <> - - - - {menus.organization && } - + - - ); -}; - -export const useStatusFilterMenu = ({ - value, - onChange, -}: Pick) => { - 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; - -type StatusMenuProps = { - menu: StatusFilterMenu; - width?: number; -}; - -const StatusMenu: React.FC = ({ menu, width }) => { - return ( - - ); -}; - -export const useMethodFilterMenu = ({ - value, - onChange, -}: Pick) => { - 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; - -type MethodMenuProps = { - menu: MethodFilterMenu; - width?: number; -}; - -const MethodMenu: React.FC = ({ menu, width }) => { - return ( - +
); }; diff --git a/site/src/pages/ConnectionLogPage/ConnectionLogPage.test.tsx b/site/src/pages/ConnectionLogPage/ConnectionLogPage.test.tsx index f9179d93535..a14992394e7 100644 --- a/site/src/pages/ConnectionLogPage/ConnectionLogPage.test.tsx +++ b/site/src/pages/ConnectionLogPage/ConnectionLogPage.test.tsx @@ -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", }), ); }); diff --git a/site/src/pages/ConnectionLogPage/ConnectionLogPage.tsx b/site/src/pages/ConnectionLogPage/ConnectionLogPage.tsx index 759dbf0cb62..680e8527907 100644 --- a/site/src/pages/ConnectionLogPage/ConnectionLogPage.tsx +++ b/site/src/pages/ConnectionLogPage/ConnectionLogPage.tsx @@ -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 ( <> {pageTitle("Connection log")} @@ -88,12 +42,6 @@ const ConnectionLogPage: React.FC = () => { filterProps={{ filter, error: connectionlogsQuery.error, - menus: { - user: userMenu, - status: statusMenu, - method: methodMenu, - organization: showOrganizations ? organizationsMenu : undefined, - }, }} /> diff --git a/site/src/pages/ConnectionLogPage/ConnectionLogPageView.stories.tsx b/site/src/pages/ConnectionLogPage/ConnectionLogPageView.stories.tsx index 38a8f82148e..6a43e5d572c 100644 --- a/site/src/pages/ConnectionLogPage/ConnectionLogPageView.stories.tsx +++ b/site/src/pages/ConnectionLogPage/ConnectionLogPageView.stories.tsx @@ -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({ - 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 = { 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({ + 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({ + query: "status:invalid", + values: { status: "invalid" }, + }), + error: mockInvalidFilterError, + }, + }, +};