From 156da8ddea544f74e2feb97a3586b031bcb2c6e2 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:21:28 +0000 Subject: [PATCH] Keep keyboard context through saved User Access outcomes Restore the exact principal after the required saved reread, keep Retry in that journey, and recover blurred rejection feedback without changing drafts, requests or grants. Retire late focus work with the reader and preserve deliberate keyboard moves. Contract-Neutral: Preserve existing User Access keyboard return across saved rereads and refusals; no API, authorization, storage or transport semantics change. Change-source: pulse-maintainer --- .../984fafa82a65b0bf.json | 40 +++ .../Settings/UserAssignmentsDialog.tsx | 10 +- .../Settings/UserAssignmentsPanel.tsx | 82 +++++- .../UserAccessSavedFocus.transport.test.tsx | 261 ++++++++++++++++++ .../Settings/useUserAssignmentsPanelState.ts | 3 + 5 files changed, 391 insertions(+), 5 deletions(-) create mode 100644 frontend-modern/browser-verification/984fafa82a65b0bf.json create mode 100644 frontend-modern/src/components/Settings/__tests__/UserAccessSavedFocus.transport.test.tsx diff --git a/frontend-modern/browser-verification/984fafa82a65b0bf.json b/frontend-modern/browser-verification/984fafa82a65b0bf.json new file mode 100644 index 0000000000..bc576636aa --- /dev/null +++ b/frontend-modern/browser-verification/984fafa82a65b0bf.json @@ -0,0 +1,40 @@ +{ + "version": 1, + "base_sha": "a9b56aebb5f203a786ecb98bc10f6393bb3e0c19", + "verified_at": "2026-11-15T17:21:24Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx", + "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx", + "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx": "2131d8a2defc8c02a0cef36653f38aed3f3a012c4dafcce4694de1d8c7f722ea", + "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx": "857e0fe999705c89313b19e60e5c564364b76a9e6acaef0fc515dc4701bb3d1f", + "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts": "d60d8bb3060557dda29e351aa1f7e39b76f483882ae0173fd69c79c7dced26ab" + }, + "routes": [ + "/" + ], + "viewports": [ + { + "width": 1440, + "height": 1000 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "Actual User Access panel, grid, editor, state, RBACAPI and HTTP client; only entitlement availability and local HTTP data are synthetic. This is a consuming-panel fixture, not App, tenant authorization or installed IdP proof.", + "Same-name principals with literal SSO IDs, same-name roles and a preserved unlisted saved role. Saved/failed inventory reads, explicit Retry, rejected and uncertain writes, missing user, cancellation, deliberate focus move, user/organization round trip, permission withdrawal and unmount.", + "Chromium desktop/light and narrow/dark; WebKit desktop/dark and narrow/light. Playwright 1.56.1 matches integration lock. 32 PNGs/16 comparable pairs were opened through native image inspection: overview, saved, failed read and rejected save. Original and final fixture data, viewport, theme and interaction state match." + ], + "interactions": [ + "Final containing frontend bytes pass 1110 browser assertions across 44 cases. Parent controls reproduce lost focus after saved and failed rereads; final focus returns to the exact literal principal or search if it disappeared. Retry reads once and returns to that same principal without another role write.", + "A rejected save preserves selected roles and keeps keyboard focus inside its editor, recovering to its existing feedback if the disabled submit control blurred. Unknown outcomes retain their own recovery notice. No restoration steals an active focus target or survives reader replacement, permission loss or unmount.", + "Each save uses one exact encoded-principal PUT with unchanged saved role IDs, API token, organization, cookies and CSRF behavior. All existing identities, roles and actions remain visible; no layout, information, route or grant changes. Browser, Vite and fixture server close; no uncaught page errors.", + "Earlier proof-only textbox locator failure, observed Chromium rejection blur and an unsettled WebKit frame are retained separately; screenshots wait for fonts/frames and finish animations consistently for comparable pixel review. Final error focus ring is inset so its panel does not clip it." + ] +} diff --git a/frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx b/frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx index 38e0373238..310164929d 100644 --- a/frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx +++ b/frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx @@ -60,6 +60,7 @@ export const RoleAccessIdentity: Component<{ interface UserAssignmentsDialogProps { actionError?: string | null; + actionErrorRef?: (element: HTMLDivElement) => void; editingUser: UserRoleAssignment | null; formRoleIds: string[]; isOpen: boolean; @@ -124,7 +125,14 @@ export const UserAssignmentsDialog: Component = (pro
{(message) => ( - + {message()} )} diff --git a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx index e5bf5ecc03..9c02f59108 100644 --- a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx +++ b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx @@ -26,6 +26,11 @@ export const UserAssignmentsPanel: Component = (props const emptyStateCopy = () => getUserAssignmentsEmptyStateCopy(); let searchInputRef: HTMLInputElement | undefined; let inventoryNotice: HTMLDivElement | undefined; + let loadFailureNotice: HTMLDivElement | undefined; + let editorFailureNotice: HTMLDivElement | undefined; + let panel: HTMLDivElement | undefined; + let manageTrigger: HTMLButtonElement | undefined; + let savedUser: { version: number; username: string } | undefined; let focusTimer: number | undefined; createEffect( on(state.unconfirmedChange, (change) => { @@ -39,8 +44,67 @@ export const UserAssignmentsPanel: Component = (props ); onCleanup(() => window.clearTimeout(focusTimer)); + const restoreSavedFocus = ( + version: number, + trigger: Element | null | undefined, + username?: string, + ) => { + const canReturn = () => + panel?.isConnected && + version === state.contextVersion() && + state.accessAllowed() && + !state.loading() && + !state.userPendingDeletion() && + !state.unconfirmedChange(); + // A successful write withdraws the editor and replaces its original row + // during the saved read. The shared dialog cannot focus that detached node. + if (!canReturn()) return; + window.clearTimeout(focusTimer); + focusTimer = window.setTimeout(() => { + if (!canReturn()) return; + const active = document.activeElement; + if (active && active !== document.body && active !== trigger && active.isConnected) return; + if (state.showModal()) { + if (state.editingUser()?.username === username && state.actionError()) + editorFailureNotice?.focus(); + } else if (state.loadError()) { + loadFailureNotice?.focus(); + } else if (state.canEdit()) { + // Match the literal principal, not a mutable name or a CSS selector + // constructed from an opaque SSO ID. A vanished/filtered user returns + // to search instead of selecting a different namesake. + const replacement = Array.from( + panel?.querySelectorAll('button[data-user-access-manage]') ?? [], + ).find((button) => button.dataset.userAccessManage === username && !button.disabled); + (replacement ?? searchInputRef)?.focus(); + } + }, 0); + }; + + const saveAssignments = async () => { + const user = state.editingUser(); + if (!user) return; + const version = state.contextVersion(); + const trigger = manageTrigger; + await state.handleSaveAssignments(); + if (version !== state.contextVersion() || state.unconfirmedChange()) return; + if (!state.showModal()) savedUser = { version, username: user.username }; + restoreSavedFocus(version, trigger, user.username); + }; + + const reloadAssignments = async () => { + const version = state.contextVersion(); + const trigger = document.activeElement; + await state.loadData(); + restoreSavedFocus( + version, + trigger, + savedUser?.version === version ? savedUser.username : undefined, + ); + }; + return ( -
+
= (props {(message) => ( } actionLabel={state.unconfirmedChange() ? undefined : 'Retry'} - actionOnClick={() => void state.loadData()} + actionOnClick={() => void reloadAssignments()} + class="focus:outline-hidden focus:ring-2 focus:ring-inset focus:ring-blue-500" > {message()} @@ -254,7 +321,11 @@ export const UserAssignmentsPanel: Component = (props aria-label={`Manage access for ${getUserIdentityLabel(assignment)}`} title="Manage access" disabled={!state.canEdit()} - onClick={() => state.openManageAccess(assignment)} + data-user-access-manage={assignment.username} + onClick={(event) => { + manageTrigger = event.currentTarget; + void state.openManageAccess(assignment); + }} > @@ -286,6 +357,9 @@ export const UserAssignmentsPanel: Component = (props { + editorFailureNotice = element; + }} editingUser={state.editingUser()} formRoleIds={state.formRoleIds()} isOpen={state.showModal()} @@ -295,7 +369,7 @@ export const UserAssignmentsPanel: Component = (props saving={state.saving()} userPermissions={state.userPermissions()} onClose={state.closeModal} - onSave={state.handleSaveAssignments} + onSave={() => void saveAssignments()} onRetryPermissions={() => void state.loadUserPermissions()} onToggleRole={state.toggleRole} /> diff --git a/frontend-modern/src/components/Settings/__tests__/UserAccessSavedFocus.transport.test.tsx b/frontend-modern/src/components/Settings/__tests__/UserAccessSavedFocus.transport.test.tsx new file mode 100644 index 0000000000..b330d1c6fc --- /dev/null +++ b/frontend-modern/src/components/Settings/__tests__/UserAccessSavedFocus.transport.test.tsx @@ -0,0 +1,261 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library'; +import { createSignal } from 'solid-js'; +import { clearAuth, setApiToken, setOrgID } from '@/utils/apiClient'; +import { eventBus } from '@/stores/events'; +import type { Role, UserRoleAssignment } from '@/types/rbac'; +import { UserAssignmentsPanel } from '../UserAssignmentsPanel'; + +// Exercise the actual panel, dialog, state, RBACAPI and HTTP client. Only +// entitlement availability and the final HTTP boundary are synthetic. +vi.mock('../useRBACFeatureGateState', () => ({ + useRBACFeatureGateState: () => ({ + licenseReady: () => true, + rbacEnabled: () => true, + paywallVisible: () => false, + }), +})); + +const roles: Role[] = [ + { id: 'read/nodes', name: 'Fleet role', description: 'Read monitoring', permissions: [] }, + { + id: 'write/selected', + name: 'Fleet role', + description: 'Operate selected nodes', + permissions: [], + }, +]; +const originalUsers: UserRoleAssignment[] = ['first', 'second', 'third'].map((part) => ({ + username: `sso:oidc:lab:subject/${part}?realm=north#saved["literal"]`, + displayName: 'Alex Example', + roleIds: [roles[0].id, 'saved/unlisted:constraint'], +})); +const selected = originalUsers[1]; +const manageName = (user = selected) => `Manage access for Alex Example (${user.username})`; +const userPath = `/api/admin/users/${encodeURIComponent(selected.username)}`; +const json = (value: unknown, status = 200) => + new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json' } }); +const fetchMock = vi.fn(); +let users: UserRoleAssignment[]; +let releaseRead: (response: Response) => void; +let userReads: number; +let writeStatus: number; +let writeResponse: Promise | undefined; +const writes = () => + fetchMock.mock.calls.filter(([, init]) => !['GET', 'HEAD'].includes(init?.method ?? 'GET')); + +beforeEach(() => { + clearAuth(); + sessionStorage.clear(); + setOrgID('estate/north'); + setApiToken('synthetic-saved-focus-token'); + vi.stubEnv('MODE', 'production'); + document.cookie = 'pulse_csrf=synthetic-saved-focus-csrf; Path=/'; + users = structuredClone(originalUsers); + userReads = 0; + writeStatus = 204; + writeResponse = undefined; + const savedRead = new Promise((resolve) => { + releaseRead = resolve; + }); + fetchMock.mockReset(); + fetchMock.mockImplementation(async (input, init = {}) => { + const path = String(input); + const method = init.method ?? 'GET'; + if (method === 'GET' && path === '/api/admin/users') { + userReads++; + return userReads === 2 ? savedRead : json(users); + } + if (method === 'GET' && path === '/api/admin/roles') return json(roles); + if (method === 'GET' && path.endsWith('/permissions')) return json([]); + if (method === 'PUT' && path === `${userPath}/roles`) { + if (writeResponse) return writeResponse; + if (writeStatus !== 204) return json({ error: 'Synthetic write outcome' }, writeStatus); + const { roleIds } = JSON.parse(String(init.body)); + users = users.map((user) => + user.username === selected.username ? { ...user, roleIds } : user, + ); + return new Response(null, { status: 204 }); + } + throw new Error(`Unexpected saved-focus fixture request: ${method} ${path}`); + }); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + cleanup(); + clearAuth(); + setOrgID(null); + document.cookie = 'pulse_csrf=; Max-Age=0; Path=/'; + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +async function openEditor() { + const [reader, setReader] = createSignal({ user: 'access-maintainer', allowed: true }); + const view = render(() => ( + <> + + + + )); + const trigger = await screen.findByRole('button', { name: manageName() }); + trigger.focus(); + fireEvent.click(trigger); + const dialog = within(await screen.findByRole('dialog')); + await waitFor(() => expect(dialog.getByRole('region')).toHaveAttribute('aria-busy', 'false')); + const operator = dialog.getByRole('checkbox', { name: /Operate selected nodes/ }); + fireEvent.click(operator); + const save = dialog.getByRole('button', { name: 'Save Changes' }); + save.focus(); + fireEvent.click(save); + return { trigger, dialog, operator, setReader, view }; +} + +async function startSavedRead() { + const view = await openEditor(); + await waitFor(() => expect(userReads).toBe(2)); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(view.trigger).not.toBeInTheDocument(); + return view; +} + +function expectSingleBoundWrite() { + expect(writes()).toHaveLength(1); + const [path, init] = writes()[0]; + expect(path).toBe(`${userPath}/roles`); + expect(JSON.parse(String(init?.body))).toEqual({ + roleIds: [roles[0].id, 'saved/unlisted:constraint', roles[1].id], + }); + expect(init).toMatchObject({ + method: 'PUT', + credentials: 'include', + signal: expect.any(AbortSignal), + headers: { + 'X-Pulse-Org-ID': 'estate/north', + 'X-API-Token': 'synthetic-saved-focus-token', + 'X-CSRF-Token': 'synthetic-saved-focus-csrf', + }, + }); +} + +describe('User Access focus after a confirmed write and saved reread', () => { + it('returns to the exact replaced principal, not a same-name user or row position', async () => { + const { trigger } = await startSavedRead(); + users.reverse(); + releaseRead(json(users)); + const replacement = await screen.findByRole('button', { name: manageName() }); + await waitFor(() => expect(replacement).toHaveFocus()); + expect(replacement).not.toBe(trigger); + for (const sibling of [originalUsers[0], originalUsers[2]]) + expect(screen.getByRole('button', { name: manageName(sibling) })).not.toHaveFocus(); + fireEvent.click(replacement); + const dialog = within(await screen.findByRole('dialog')); + expect(dialog.getByRole('checkbox', { name: /Operate selected nodes/ })).toBeChecked(); + expect(dialog.getByText('saved/unlisted:constraint')).toBeVisible(); + expectSingleBoundWrite(); + }); + + it('focuses a failed reread, then returns from Retry to the same saved user without another write', async () => { + await startSavedRead(); + releaseRead(json({ error: 'Synthetic read failure' }, 503)); + const notice = await screen.findByRole('alert'); + await waitFor(() => expect(notice).toHaveFocus()); + expect(screen.queryByRole('button', { name: manageName() })).not.toBeInTheDocument(); + const retry = within(notice).getByRole('button', { name: 'Retry' }); + retry.focus(); + fireEvent.click(retry); + const replacement = await screen.findByRole('button', { name: manageName() }); + await waitFor(() => expect(replacement).toHaveFocus()); + expect(userReads).toBe(3); + expectSingleBoundWrite(); + }); + + it('uses search rather than a namesake when the saved principal is no longer listed', async () => { + await startSavedRead(); + users = users.filter((user) => user.username !== selected.username); + releaseRead(json(users)); + await waitFor(() => + expect(screen.getByRole('textbox', { name: 'Search users...' })).toHaveFocus(), + ); + expect(screen.queryByRole('button', { name: manageName() })).not.toBeInTheDocument(); + expectSingleBoundWrite(); + }); + + it.each([200, 503])( + 'does not steal a deliberate focus move while the saved read returns %s', + async (status) => { + await startSavedRead(); + const outside = screen.getByRole('button', { name: 'Outside task' }); + outside.focus(); + releaseRead(json(status === 200 ? users : { error: 'Synthetic read failure' }, status)); + if (status === 200) await screen.findByRole('button', { name: manageName() }); + else await screen.findByRole('alert'); + await new Promise((resolve) => window.setTimeout(resolve, 20)); + expect(outside).toHaveFocus(); + expectSingleBoundWrite(); + }, + ); + + it.each(['user', 'organization round trip', 'permission loss', 'unmount'])( + 'retires pending focus after %s', + async (change) => { + const { setReader, view } = await startSavedRead(); + if (change === 'user') setReader({ user: 'another-maintainer', allowed: true }); + else if (change === 'permission loss') + setReader({ user: 'access-maintainer', allowed: false }); + else if (change === 'unmount') view.unmount(); + else { + setOrgID('estate/south'); + eventBus.emit('org_switched', 'estate/south'); + setOrgID('estate/north'); + eventBus.emit('org_switched', 'estate/north'); + } + const outside = screen.queryByRole('button', { name: 'Outside task' }); + if (change === 'permission loss') outside?.focus(); + releaseRead(json(users)); + if (['user', 'organization round trip'].includes(change)) + await screen.findByRole('button', { name: manageName() }); + else if (change === 'permission loss') + await screen.findByText('User access is unavailable for this session.'); + await new Promise((resolve) => window.setTimeout(resolve, 20)); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + if (change === 'permission loss' && outside) expect(outside).toHaveFocus(); + else if (change !== 'unmount') + expect(screen.getByRole('button', { name: manageName() })).not.toHaveFocus(); + expect(screen.queryByText(`Roles updated for ${selected.username}`)).not.toBeInTheDocument(); + expectSingleBoundWrite(); + }, + ); + + it('leaves a rejected draft in its editor', async () => { + let releaseWrite!: (response: Response) => void; + writeResponse = new Promise((resolve) => { + releaseWrite = resolve; + }); + const { dialog, operator } = await openEditor(); + // Real browsers can blur a disabled submit control. jsdom retains focus + // on it, so reproduce that observed blur before resolving the HTTP reply. + const save = dialog.getByRole('button', { name: 'Applying...' }); + expect(save).toBeDisabled(); + save.blur(); + releaseWrite(json({ error: 'Synthetic rejection' }, 403)); + const notice = await dialog.findByRole('alert'); + await waitFor(() => expect(notice).toHaveFocus()); + expect(screen.getByRole('dialog')).toContainElement(document.activeElement as HTMLElement); + expect(operator).toBeChecked(); + expect(userReads).toBe(1); + expectSingleBoundWrite(); + }); + + it('leaves uncertainty recovery in charge rather than refocusing a previous user', async () => { + writeStatus = 503; + await openEditor(); + const notice = await screen.findByRole('alert'); + await waitFor(() => expect(notice).toHaveFocus()); + expect(notice).toHaveTextContent('could not be confirmed'); + expect(within(notice).getByRole('button', { name: 'Check saved access' })).toBeVisible(); + expect(userReads).toBe(1); + expectSingleBoundWrite(); + }); +}); diff --git a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts index fba5576179..ff42cf5668 100644 --- a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts +++ b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts @@ -39,6 +39,7 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = ); const [inventoryLoaded, setInventoryLoaded] = createSignal(false); const [unconfirmedChange, setUnconfirmedChange] = createSignal(null); + const [contextVersion, setContextVersion] = createSignal(0); const featureGate = useRBACFeatureGateState({ kind: 'user-assignments', @@ -172,6 +173,7 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = readController = mutationController = undefined; context = { org: currentOrg(), user: props.currentUser, allowed: accessAllowed() }; batch(() => { + setContextVersion((version) => version + 1); clearEditor(); setAssignments([]); setRoles([]); @@ -358,6 +360,7 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = successNotice, accessAllowed, canEdit, + contextVersion, closeDeleteUser, closeModal, deletingUser,