From 486d2faa818ded2cd9e2c8f9c00d610ed16cf830 Mon Sep 17 00:00:00 2001 From: Jake Howell Date: Wed, 9 Sep 2026 00:35:42 +1000 Subject: [PATCH] refactor: modernize the create user page (#28894) 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. Redesigns the create user flow using the settings page layout and renames it to "New user." The form includes clearer field guidance, explicit authentication-method loading, error, and empty states, updated documentation, and aligned end-to-end selectors. | Old | New | | --- | --- | | 02-create-user | 02-create-user-page | Depends on #28893.
Stack 1. #28893 - Edit user page redesign 2. #28894 - Create user page redesign (this PR)
--- docs/admin/users/headless-auth.md | 3 +- docs/admin/users/index.md | 10 +- site/e2e/helpers.ts | 6 +- .../CreateUserPage/CreateUserForm.stories.tsx | 121 ++++- .../pages/CreateUserPage/CreateUserForm.tsx | 442 ++++++++++-------- .../CreateUserPage/CreateUserPage.stories.tsx | 63 ++- .../pages/CreateUserPage/CreateUserPage.tsx | 111 +++-- .../pages/UsersPage/UsersPageView.stories.tsx | 4 +- site/src/pages/UsersPage/UsersPageView.tsx | 2 +- 9 files changed, 466 insertions(+), 296 deletions(-) diff --git a/docs/admin/users/headless-auth.md b/docs/admin/users/headless-auth.md index 496a58a9e1d..bf15b62bd34 100644 --- a/docs/admin/users/headless-auth.md +++ b/docs/admin/users/headless-auth.md @@ -27,8 +27,7 @@ coder users create \ ## UI -Navigate to **Deployment** > **Users** > **Create user**, then select -**Service account** as the login type. +Navigate to **Deployment** > **Users** > **New user**, then select **Service account** as the login type. ![Create a user via the UI](../../images/admin/users/headless-user.png) diff --git a/docs/admin/users/index.md b/docs/admin/users/index.md index 19fe68f654b..b5c3048096a 100644 --- a/docs/admin/users/index.md +++ b/docs/admin/users/index.md @@ -74,13 +74,11 @@ To create a user with the web UI: 1. Log in as a user admin. 2. Go to **Users** > **New user**. -3. In the window that opens, provide the **username**, **email**, and - **password** for the user (they can opt to change their password after their - initial login). -4. Select **Submit** to create the user. +3. Enter the **Username**, **Email**, and **Password**. +4. Select **Save**. -The new user will appear in the **Users** list. Use the toggle to change their -**Roles** if desired. +The new user appears in the **Users** list. +You can assign roles on this page before you save, or later from the user's actions menu. To create a user via the Coder CLI, run: diff --git a/site/e2e/helpers.ts b/site/e2e/helpers.ts index e0546ce487d..76c0c3a9959 100644 --- a/site/e2e/helpers.ts +++ b/site/e2e/helpers.ts @@ -1342,8 +1342,8 @@ export async function createUser( await page.goto("/deployment/users", { waitUntil: "domcontentloaded" }); await expect(page).toHaveTitle("Users - Coder"); - await page.getByRole("link", { name: "Create user" }).click(); - await expect(page).toHaveTitle("Create User - Coder"); + await page.getByRole("link", { name: "New user" }).click(); + await expect(page).toHaveTitle("New user - Coder"); const username = userValues.username ?? randomName(); const name = userValues.name ?? username; @@ -1353,7 +1353,7 @@ export async function createUser( await page.getByLabel("Username").fill(username); if (name) { - await page.getByLabel("Full name").fill(name); + await page.getByLabel("Name", { exact: true }).fill(name); } await page.getByLabel("Email").fill(email); diff --git a/site/src/pages/CreateUserPage/CreateUserForm.stories.tsx b/site/src/pages/CreateUserPage/CreateUserForm.stories.tsx index f6203563372..dc3838a1fef 100644 --- a/site/src/pages/CreateUserPage/CreateUserForm.stories.tsx +++ b/site/src/pages/CreateUserPage/CreateUserForm.stories.tsx @@ -1,9 +1,11 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; import { action } from "storybook/actions"; -import { userEvent, within } from "storybook/test"; +import { expect, userEvent, within } from "storybook/test"; +import { permittedOrganizationsKey } from "#/api/queries/organizations"; import { assignableRole, MockAuditorRole, + MockAuthMethodsAll, MockAuthMethodsPasswordOnly, MockOrganization, MockOrganization2, @@ -21,27 +23,83 @@ const meta: Meta = { onCancel: action("cancel"), onSubmit: action("submit"), isLoading: false, + showOrganizations: false, serviceAccountsEnabled: true, + authMethods: MockAuthMethodsPasswordOnly, }, }; export default meta; type Story = StoryObj; -export const Ready: Story = {}; +export const Ready: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + canvas.getByRole("heading", { name: "New user" }), + ).toBeVisible(); + await expect( + canvas.getByRole("link", { name: /back to users/i }), + ).toBeVisible(); + await expect( + canvas.getByText(/add a user to this coder deployment/i), + ).toBeVisible(); + await expect(canvas.getByText("Unique identifier.")).toBeVisible(); + await expect( + canvas.getByText("Friendly name. Defaults to the username if blank."), + ).toBeVisible(); + await expect(canvas.queryByText(/optional/i)).not.toBeInTheDocument(); + }, +}; -// Query key used by permittedOrganizations() in the form. -const permittedOrgsKey = [ - "organizations", - "permitted", - { object: { resource_type: "organization_member" }, action: "create" }, -]; +export const NoAvailableLoginTypes: Story = { + args: { + authMethods: { + password: { enabled: false }, + github: { enabled: false, default_provider_configured: false }, + oidc: { enabled: false, signInText: "", iconUrl: "" }, + }, + serviceAccountsEnabled: false, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + canvas.getByText( + "No authentication methods are available for new users.", + ), + ).toBeVisible(); + await expect( + canvas.queryByRole("button", { name: /save/i }), + ).not.toBeInTheDocument(); + }, +}; + +export const KeepsEmailForExternalLogin: Story = { + args: { + authMethods: MockAuthMethodsAll, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const email = canvas.getByLabelText(/email/i); + await userEvent.type(email, "someone@coder.com"); + await userEvent.click(canvas.getByTestId("login-type-input")); + await userEvent.click( + await within(document.body).findByRole("option", { + name: /openID connect/i, + }), + ); + await expect(email).toHaveValue("someone@coder.com"); + }, +}; export const WithOrganizations: Story = { parameters: { queries: [ { - key: permittedOrgsKey, + key: permittedOrganizationsKey({ + object: { resource_type: "organization_member" }, + action: "create", + }), data: [MockOrganization, MockOrganization2], }, ], @@ -61,6 +119,12 @@ export const FormError: Story = { validations: [{ field: "username", detail: "Username taken" }], }), }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: /save/i })); + await expect(await canvas.findByText("Username taken")).toBeVisible(); + await expect(canvas.queryByRole("alert")).not.toBeInTheDocument(); + }, }; export const GeneralError: Story = { @@ -69,12 +133,22 @@ export const GeneralError: Story = { message: "User already exists", }), }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText("User already exists")).toBeVisible(); + await expect(canvas.getByLabelText(/username/i)).toBeVisible(); + }, }; export const Loading: Story = { args: { isLoading: true, }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByRole("button", { name: /save/i })).toBeDisabled(); + await expect(canvas.getByRole("button", { name: /cancel/i })).toBeEnabled(); + }, }; const mockAvailableRoles = [ @@ -87,7 +161,13 @@ const mockAvailableRoles = [ export const RolesLoading: Story = { args: { rolesLoading: true, - authMethods: MockAuthMethodsPasswordOnly, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText("Roles")).toBeVisible(); + await expect( + canvas.queryByRole("checkbox", { name: /owner/i }), + ).not.toBeInTheDocument(); }, }; @@ -96,25 +176,40 @@ export const RolesError: Story = { rolesError: mockApiError({ message: "Failed to fetch assignable roles.", }), - authMethods: MockAuthMethodsPasswordOnly, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + canvas.getByText("Failed to fetch assignable roles."), + ).toBeVisible(); }, }; export const WithRoles: Story = { args: { availableRoles: mockAvailableRoles, - authMethods: MockAuthMethodsPasswordOnly, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + canvas.getByRole("checkbox", { name: /owner/i }), + ).toBeVisible(); }, }; export const WithRolesSelected: Story = { args: { availableRoles: mockAvailableRoles, - authMethods: MockAuthMethodsPasswordOnly, }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); await userEvent.click(canvas.getByRole("checkbox", { name: /owner/i })); await userEvent.click(canvas.getByRole("checkbox", { name: /auditor/i })); + await expect( + canvas.getByRole("checkbox", { name: /owner/i }), + ).toBeChecked(); + await expect( + canvas.getByRole("checkbox", { name: /auditor/i }), + ).toBeChecked(); }, }; diff --git a/site/src/pages/CreateUserPage/CreateUserForm.tsx b/site/src/pages/CreateUserPage/CreateUserForm.tsx index a408b07cd77..afdbcdd07f5 100644 --- a/site/src/pages/CreateUserPage/CreateUserForm.tsx +++ b/site/src/pages/CreateUserPage/CreateUserForm.tsx @@ -1,18 +1,19 @@ import { cn } from "cn"; import { useFormik } from "formik"; -import { CheckIcon } from "lucide-react"; +import { ArrowLeftIcon, CheckIcon } from "lucide-react"; import { Select as SelectPrimitive } from "radix-ui"; import { type FC, useState } from "react"; import { useQuery } from "react-query"; +import { Link } from "react-router"; import * as Yup from "yup"; import { hasApiFieldErrors, isApiError } from "#/api/errors"; import { permittedOrganizations } from "#/api/queries/organizations"; import type * as TypesGen from "#/api/typesGenerated"; +import { Alert } from "#/components/Alert/Alert"; import { ErrorAlert } from "#/components/Alert/ErrorAlert"; import { Button } from "#/components/Button/Button"; -import { FormFooter } from "#/components/Form/Form"; +import { FormFields, FormFooter } from "#/components/Form/Form"; import { FormField } from "#/components/FormField/FormField"; -import { FullPageForm } from "#/components/FullPageForm/FullPageForm"; import { Label } from "#/components/Label/Label"; import { OrganizationAutocomplete } from "#/components/OrganizationAutocomplete/OrganizationAutocomplete"; import { @@ -21,6 +22,11 @@ import { SelectTrigger, SelectValue, } from "#/components/Select/Select"; +import { + SettingsHeader, + SettingsHeaderDescription, + SettingsHeaderTitle, +} from "#/components/SettingsHeader/SettingsHeader"; import { Spinner } from "#/components/Spinner/Spinner"; import { RoleSelector } from "#/modules/roles/RoleSelector"; import { @@ -52,7 +58,7 @@ const loginTypeOptions = { const validationSchema = Yup.object({ username: nameValidator("Username"), - name: displayNameValidator("Full name"), + name: displayNameValidator("Name"), email: Yup.string() .trim() .when("service_account", { @@ -89,7 +95,7 @@ type CreateUserFormProps = { isLoading: boolean; onSubmit: (user: CreateUserFormData) => void; onCancel: () => void; - authMethods?: TypesGen.AuthMethods; + authMethods: TypesGen.AuthMethods; showOrganizations: boolean; serviceAccountsEnabled: boolean; availableRoles?: TypesGen.AssignableRoles[]; @@ -101,27 +107,74 @@ type CreateUserFormProps = { // in the render-time state adjustment pattern. const emptyOrgs: TypesGen.Organization[] = []; -export const CreateUserForm: FC = ({ +const createOrgMemberCheck = { + object: { resource_type: "organization_member" }, + action: "create", +} as const; + +export const CreateUserForm: FC = (props) => { + const availableLoginTypes = ( + ["password", "oidc", "github", "none"] as const + ).filter((key) => { + if (key === "none") { + return props.serviceAccountsEnabled; + } + return props.authMethods[key].enabled; + }); + const defaultLoginType = availableLoginTypes[0]; + + if (!defaultLoginType) { + return ( +
+ +
+ + New user + + Add a user to this Coder deployment. + + + + No authentication methods are available for new users. + +
+
+ ); + } + + return ( + + ); +}; + +type AvailableLoginType = keyof typeof loginTypeOptions; + +type CreateUserFormFieldsProps = CreateUserFormProps & { + availableLoginTypes: readonly AvailableLoginType[]; + defaultLoginType: AvailableLoginType; +}; + +const CreateUserFormFields: FC = ({ error, isLoading, onSubmit, onCancel, showOrganizations, - authMethods, - serviceAccountsEnabled, availableRoles, rolesLoading, rolesError, + availableLoginTypes, + defaultLoginType, }) => { - const availableLoginTypes = [ - authMethods?.password.enabled && "password", - authMethods?.oidc.enabled && "oidc", - authMethods?.github.enabled && "github", - serviceAccountsEnabled && "none", - ].filter(Boolean) as Array; - - const defaultLoginType = availableLoginTypes[0]; - const form = useFormik({ initialValues: { email: "", @@ -137,7 +190,6 @@ export const CreateUserForm: FC = ({ }, validationSchema, onSubmit, - enableReinitialize: true, }); const [selectedOrg, setSelectedOrg] = useState( @@ -145,10 +197,7 @@ export const CreateUserForm: FC = ({ ); const permittedOrgsQuery = useQuery({ - ...permittedOrganizations({ - object: { resource_type: "organization_member" }, - action: "create", - }), + ...permittedOrganizations(createOrgMemberCheck), enabled: showOrganizations, }); const orgOptions = permittedOrgsQuery.data ?? emptyOrgs; @@ -181,190 +230,183 @@ export const CreateUserForm: FC = ({ }); return ( - - {isApiError(error) && !hasApiFieldErrors(error) && ( - - )} -
-
- {showOrganizations && ( -
- - { - setSelectedOrg(newValue); - void form.setFieldValue("organization", newValue?.id ?? ""); - }} - /> -
- )} - - {/* Login type — "none" is presented as "Service account" */} -
- - - {loginTypeField.helperText && ( - - {loginTypeField.helperText} - +
+ +
+ + New user + + Add a user to this Coder deployment. + + +
+ + {isApiError(error) && !hasApiFieldErrors(error) && ( + )} -
+ + {showOrganizations && ( +
+ + { + setSelectedOrg(newValue); + void form.setFieldValue( + "organization", + newValue?.id ?? "", + ); + }} + /> +
+ )} - +
+ + + {loginTypeField.helperText && ( + + {loginTypeField.helperText} - - } - id="email" - name="email" - value={form.values.email} - onChange={onChangeTrimmed(form)} - onBlur={form.handleBlur} - autoComplete="email" - type="email" - /> - )} + )} +
- {isPasswordLogin && ( - - )} + - form.setFieldValue("roles", roles)} - /> + + + {!isServiceAccount && ( + + )} + + {isPasswordLogin && ( + + )} + + form.setFieldValue("roles", roles)} + /> +
+ + + + + +
- - - - - - - +
+
); }; diff --git a/site/src/pages/CreateUserPage/CreateUserPage.stories.tsx b/site/src/pages/CreateUserPage/CreateUserPage.stories.tsx index 5013e971f2d..d20cb04d06d 100644 --- a/site/src/pages/CreateUserPage/CreateUserPage.stories.tsx +++ b/site/src/pages/CreateUserPage/CreateUserPage.stories.tsx @@ -26,6 +26,38 @@ const meta = { export default meta; type Story = StoryObj; +export const Loading: Story = { + parameters: { + queries: [{ key: rolesQueryKey, data: [] }], + }, + beforeEach: () => { + spyOn(API, "getAuthMethods").mockReturnValue(new Promise(() => {})); + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + canvas.getByRole("status", { name: /loading/i }), + ).toBeVisible(); + }, +}; + +export const AuthMethodsError: Story = { + parameters: { + queries: [{ key: rolesQueryKey, data: [] }], + }, + beforeEach: () => { + spyOn(API, "getAuthMethods").mockRejectedValue( + mockApiError({ message: "Failed to load authentication methods." }), + ); + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect( + await canvas.findByText("Failed to load authentication methods."), + ).toBeVisible(); + }, +}; + export const ShowsSuccessNotificationOnSubmit: Story = { beforeEach: () => { spyOn(API, "createUser").mockResolvedValue({ @@ -106,29 +138,26 @@ async function fillForm( loginType: "password" | "service account" = "password", ) { const isPasswordLogin = loginType === "password"; - const body = within(document.body); - await user.type(await canvas.findByLabelText("Username"), "someuser"); + await user.type(await canvas.findByLabelText(/username/i), "someuser"); if (isPasswordLogin) { await user.type(canvas.getByLabelText(/email/i), "someone@coder.com"); - } - - await user.click(canvas.getByTestId("login-type-input")); - await user.click( - await body.findByRole("option", { name: new RegExp(loginType, "i") }), - ); - // Wait for the select to finish closing; while it is open or exit-animating - // Radix locks body pointer-events, which would fail the next interaction. - await waitFor(() => - expect(body.queryByRole("listbox")).not.toBeInTheDocument(), - ); - - if (isPasswordLogin) { await user.type( - await canvas.findByTestId("password-input"), + canvas.getByTestId("password-input"), "SomeSecurePassword!", ); + } else { + const body = within(document.body); + await user.click(canvas.getByTestId("login-type-input")); + await user.click( + await body.findByRole("option", { name: /service account/i }), + ); + // Wait for the select to finish closing; while it is open or exit-animating + // Radix locks body pointer-events, which would fail the next interaction. + await waitFor(() => + expect(body.queryByRole("listbox")).not.toBeInTheDocument(), + ); } - await user.click(canvas.getByRole("button", { name: /save/i })); + await user.click(await canvas.findByRole("button", { name: /save/i })); } diff --git a/site/src/pages/CreateUserPage/CreateUserPage.tsx b/site/src/pages/CreateUserPage/CreateUserPage.tsx index 37ee4639a14..4d601eaf81f 100644 --- a/site/src/pages/CreateUserPage/CreateUserPage.tsx +++ b/site/src/pages/CreateUserPage/CreateUserPage.tsx @@ -5,7 +5,8 @@ import { toast } from "sonner"; import { getErrorDetail, getErrorMessage } from "#/api/errors"; import { roles } from "#/api/queries/roles"; import { authMethods, createUser } from "#/api/queries/users"; -import { Margins } from "#/components/Margins/Margins"; +import { ErrorAlert } from "#/components/Alert/ErrorAlert"; +import { Loader } from "#/components/Loader/Loader"; import { useDashboard } from "#/modules/dashboard/useDashboard"; import { useFeatureVisibility } from "#/modules/dashboard/useFeatureVisibility"; import { pageTitle } from "#/utils/page"; @@ -21,58 +22,66 @@ const CreateUserPage: FC = () => { const { service_accounts: serviceAccountsEnabled } = useFeatureVisibility(); return ( - - {pageTitle("Create User")} + <> + {pageTitle("New user")} - { - const mutation = createUserMutation.mutateAsync( - { - username: user.username, - name: user.name, - email: user.email, - organization_ids: [user.organization], - login_type: user.login_type, - password: user.password, - user_status: null, - service_account: user.service_account, - roles: [...user.roles], - }, - { - onSuccess: () => { - navigate("..", { relative: "path" }); + {!authMethodsQuery.data ? ( + authMethodsQuery.error ? ( + + ) : ( + + ) + ) : ( + { + const mutation = createUserMutation.mutateAsync( + { + username: user.username, + name: user.name, + email: user.email, + organization_ids: [user.organization], + login_type: user.login_type, + password: user.password, + user_status: null, + service_account: user.service_account, + roles: [...user.roles], }, - }, - ); - const requestedAccount = user.service_account - ? "service account" - : "user"; - toast.promise(mutation, { - loading: `Creating ${requestedAccount} "${user.username}"...`, - success: (created) => - `${created.is_service_account ? "Service account" : "User"} "${created.username}" created successfully.`, - error: (e) => ({ - message: getErrorMessage( - e, - `Failed to create ${requestedAccount} "${user.username}".`, - ), - description: getErrorDetail(e), - }), - }); - }} - onCancel={() => { - navigate("..", { relative: "path" }); - }} - authMethods={authMethodsQuery.data} - showOrganizations={showOrganizations} - serviceAccountsEnabled={serviceAccountsEnabled} - availableRoles={rolesQuery.data} - rolesLoading={rolesQuery.isLoading} - rolesError={rolesQuery.error} - /> - + { + onSuccess: () => { + navigate("..", { relative: "path" }); + }, + }, + ); + const requestedAccount = user.service_account + ? "service account" + : "user"; + toast.promise(mutation, { + loading: `Creating ${requestedAccount} "${user.username}"...`, + success: (created) => + `${created.is_service_account ? "Service account" : "User"} "${created.username}" created successfully.`, + error: (e) => ({ + message: getErrorMessage( + e, + `Failed to create ${requestedAccount} "${user.username}".`, + ), + description: getErrorDetail(e), + }), + }); + }} + onCancel={() => { + navigate("..", { relative: "path" }); + }} + authMethods={authMethodsQuery.data} + showOrganizations={showOrganizations} + serviceAccountsEnabled={serviceAccountsEnabled} + availableRoles={rolesQuery.data} + rolesLoading={rolesQuery.isLoading} + rolesError={rolesQuery.error} + /> + )} + ); }; diff --git a/site/src/pages/UsersPage/UsersPageView.stories.tsx b/site/src/pages/UsersPage/UsersPageView.stories.tsx index 592b3c92b3f..cbc1c5eb24c 100644 --- a/site/src/pages/UsersPage/UsersPageView.stories.tsx +++ b/site/src/pages/UsersPage/UsersPageView.stories.tsx @@ -52,9 +52,7 @@ export const Admin: Story = { }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); - await expect( - canvas.getByRole("link", { name: "Create user" }), - ).toBeVisible(); + await expect(canvas.getByRole("link", { name: "New user" })).toBeVisible(); }, }; diff --git a/site/src/pages/UsersPage/UsersPageView.tsx b/site/src/pages/UsersPage/UsersPageView.tsx index 41698800186..8a6dc36974c 100644 --- a/site/src/pages/UsersPage/UsersPageView.tsx +++ b/site/src/pages/UsersPage/UsersPageView.tsx @@ -41,7 +41,7 @@ export const UsersPageView: FC = ({ )