diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index fc4f1d23..84f482a2 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -65,8 +65,8 @@ field or view. as one quiet **Record** line ("Record example-rack-a01 · created 2026-10-01"), plus any fact the page shows nowhere else. The namespace (always `default`), the UID and a per-record verification row are not - shown. No page has a History tab; it returns when an activity timeline - exists. The breadcrumb is the way back; there is no separate back link. + shown. No page has a general History tab; it returns when an activity + timeline exists. A Device's Operations tab lists its power operations. The breadcrumb is the way back; there is no separate back link. 2. **One primary view per kind**, above the fold: | Kind | Primary view | @@ -893,8 +893,9 @@ plain: there is no green. Every reason is a tooltip and accessible text. "BMC key shared"); else "BMC ?" in amber. - **Hardware: expected next to observed.** When discovery has read a System, a Field | Expected | Observed table replaces the reported model - and system UUID facts: Serial, Model, Manufacturer, System UUID, SKU and - Power (Redfish `powerState` as a short word). Expected is `spec.identity` + and system UUID facts: Serial, Model, Manufacturer, System UUID and SKU. + The observed power state is in the header strip (see + [Device page: power](#device-page-power-implemented-in-the-ui)). Expected is `spec.identity` and is blank where spec does not record the field. The compared System is the one reporting the spec system UUID, else the spec serial (as serial number or SKU), else the only System; with several candidates the table is @@ -955,6 +956,79 @@ Cables. `inventory-record-layout.test.tsx` covers the drawn and tiled pictures on the fixture pages, the header strip and the Edit button's description. +### Device page: power (implemented in the UI) + +Staff power a Device on or off, or reset it, from the Device page by creating a +staff `DevicePowerOperation`. The UI is tested against synthetic data, not live +hardware. It offers only actions discovery explicitly observed. The coordinator decides +admission. The page repeats only the checks its records show; discovery age +is left to the coordinator, because the page does not know the configured +discovery interval. + +- **Header.** The identity strip shows **Power** with the observed state of the + System discovery compares (amber when read from another endpoint). The latest + power operation follows it as a badge while it runs, for an hour after it + ends, and while custody holds it for an unknown outcome. +- **Power button.** It sits in the header actions. Users for whom a + SelfSubjectAccessReview does not allow `create` on `devicepoweroperations` in + `default` do not see it. The answer is cached and rechecked on + **Refresh inventory**, like the inventory management checks. The button is + disabled, with the reason as its tooltip and accessible description, when: + discovery has not read the inventory, read another BMC endpoint, or has not + read the System with the recorded system UUID; no system UUID is recorded; + the System offers no power action; IdentityMatched is not True at the + Device's generation; the BMC key was not read at the recorded endpoint, or + another Device shares it; custody is missing, unreadable or + Unverified; the holder is `Allocation` or `Release` ("Allocated to a + customer") or `Retired`; custody has a recovery hold ("Held") or an active + operation; the holder is `Service` without either; a power operation for the + Device has not ended; the caller's + identity or the operations list cannot be read. +- **Dialog.** The user chooses an action and enters a required reason (at + most 512 characters). The actions are those the System with the recorded + system UUID lists in `resetTypes`, in the order On, Force off, Force restart, + Power cycle. `ForceOff`, `ForceRestart` and `PowerCycle` ask again: the + confirmation and its button name the server ("Force restart Compute + a01-01"). +- **Request.** One POST with `metadata.generateName`, the + `fleet.datumapis.com/device-uid` label set to the Device's UID, `spec.creator` + set to the caller's username and, when present, UID from a SelfSubjectReview through the + same proxy, `spec.deviceRef` with the Device's name, + `spec.authority.serviceRequest.reason`, `spec.action`, and + `spec.expectedSystemUUID` set to the recorded system UUID in lower case. The + creator UID identifies the authenticated caller, not an inventory object. No field is typed by hand except + the reason. A denied (401, 403) or rejected + (422) create, or a failure before the POST is sent, reports that nothing + was created. Any other failure after sending is an unknown outcome: because + the name is generated, a second POST would be a second operation, so the + control stays disabled until the Device page is opened again. As in the + location correction, leaving the page, a session or navigation change, or a + changed Device closes an open request without sending it. +- **Operations tab.** Up to 20 power operations for the Device, newest first: + Time, Action, Result, Power (before → after, with when the command was sent + and the reset evidence as the tooltip), Creator, Reason. The tab carries the + count, or an amber `?` when the list is unreadable. Results: Pending, + Admitted, Sent and Verifying (dashed); Succeeded (plain); Refused (red, a + `Failed` that sent no command) or Failed (red, sent); Expired (amber, + `Cancelled` with `Expired`) or Cancelled (amber); Outcome unknown (red), + with "· held" and the hold time when custody's hold names that operation's + kind and name and the fence it was admitted at. A same-name operation + created later has no admission at that fence, so it is never shown as held. + The reason and message are the tooltip. +- **Updates.** Operations and custody are polled every 10 seconds, and every + 2 seconds while an operation runs; a failed read keeps polling. Operations + are listed with a selector on the Device's `device-uid` label, and kept only + when they name the Device. Custody counts as the Device's only when its + `device-uid` label is the Device's UID. + +Fixture builds grant the power permission, use a synthetic caller, and keep a +created operation in memory as `Pending`; nothing is sent. a01-01 is free with +a history covering each result, a01-02 is allocated, and a01-05 is held for a +power cycle whose outcome is unknown. `device-power.test.tsx` and +`device-power.test.ts` cover the offered actions, the required reason, the +destructive confirmation, the exact request body, the hidden and each disabled +state, each phase and result, the hold, and the unknown create outcome. + ### Names Views never show a generated resource name (`netbox-ca213d185ea9153b853f295e`, diff --git a/ui/provider/README.md b/ui/provider/README.md index 68716876..b8a28f69 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -109,6 +109,10 @@ fixture build replaces every API read with synthetic data: - Inventory writes are disabled: permission checks answer "not allowed", so management and capacity-registration controls stay hidden or read-only. Nothing is sent to the API. +- Device power reads synthetic custody and power operations + (`src/lib/power-fixtures.ts`). The power permission is granted so the + control shows; an operation created on the page stays in memory as + Pending. Nothing is sent to the API. Add `?fixture=` to a preview URL to deny whole collections, as a 403 would: `power-feeds-denied`, `devices-denied` or `cables-denied` diff --git a/ui/provider/scripts/screenshot-pages.ts b/ui/provider/scripts/screenshot-pages.ts index 181b606d..0621a0d7 100644 --- a/ui/provider/scripts/screenshot-pages.ts +++ b/ui/provider/scripts/screenshot-pages.ts @@ -72,6 +72,11 @@ export const PAGES: CapturePage[] = [ { name: 'device-discovery-mismatch', path: record('Device', 'example-srv-a01-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'device-discovery-pin', path: record('Device', 'example-srv-a01-05', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', viewports: ['desktop-light', 'phone'] }, { name: 'device-discovery-none', path: record('Device', 'example-srv-a02-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-fact-section', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, + // Staff power: the header control and fact, the dialog and its destructive confirmation, the Operations tab, and a held server. + { name: 'device-power-header', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-power-control button', element: '.inventory-record-header', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + { name: 'device-power-dialog', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-power-control button:not([disabled])', click: '.inventory-power-control button', viewports: ['desktop-light', 'phone'] }, + { name: 'device-power-operations', path: record('Device', 'example-srv-a01-01', '&tab=operations'), ready: '[data-tab="operations"] table', element: '.inventory-record-tabs', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + { name: 'device-power-held', path: record('Device', 'example-srv-a01-05', '&tab=operations'), ready: '[data-tab="operations"] table', viewports: ['desktop-light', 'phone'] }, { name: 'device-location', path: record('Device', 'example-srv-a01-01', '&tab=location'), ready: '[data-tab="location"] .inventory-fields', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'record-footer', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-record-footer', element: '.inventory-record-footer', viewports: ['desktop-light', 'phone'] }, // Device detail for a model without a layout (grouped tiles), and the one component table. diff --git a/ui/provider/src/components/device-discovery.test.tsx b/ui/provider/src/components/device-discovery.test.tsx index 41ab82ad..8e173251 100644 --- a/ui/provider/src/components/device-discovery.test.tsx +++ b/ui/provider/src/components/device-discovery.test.tsx @@ -31,7 +31,9 @@ describe('Device page: expected next to observed identity', () => { expect(cells('Identity', 'Model').map(cell => cell.textContent)).toEqual(['Model', 'EX-C1', 'Example EX-C1']); // Spec records no SKU or power state: the expected cell is blank. expect(cells('Identity', 'SKU').map(cell => cell.textContent)).toEqual(['SKU', '', 'SYNTH-SKU-1']); - expect(cells('Identity', 'Power')[2]).toHaveTextContent(/^On$/); + // Power is stated once, in the header strip. + expect(within(table('Identity')).queryByRole('cell', { name: 'Power' })).toBeNull(); + expect(within(screen.getByLabelText('Identity', { selector: 'dl' })).getByText('Power', { selector: 'dt' }).nextElementSibling).toHaveTextContent(/^On/); expect(table('Identity').querySelector('[data-tone]')).toBeNull(); expect(hardware()).not.toHaveTextContent(/verified/i); // The table states the system UUID; the plain fact is not repeated. diff --git a/ui/provider/src/components/device-power.test.tsx b/ui/provider/src/components/device-power.test.tsx new file mode 100644 index 00000000..3ee2bbae --- /dev/null +++ b/ui/provider/src/components/device-power.test.tsx @@ -0,0 +1,417 @@ +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Device, DeviceCustody, DevicePowerOperation } from '../../../shared/fleet-api'; +import { FIXTURE_NAMES, inventoryFixture } from '../lib/inventory-fixtures'; +import { fixtureCustody, fixturePowerOperations } from '../lib/power-fixtures'; +import { chooseValue, selectOptions } from '../test/field-select'; +import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; +import { DevicePowerControl, DevicePowerFact, DevicePowerHistory } from './device-power'; + +const named = (name: string) => structuredClone(inventoryFixture.devices.find(device => device.metadata.name === name)!); +const SERVER = FIXTURE_NAMES.server; +const UUID = named(SERVER).spec.identity.systemUUID!; +const NAME = named(SERVER).spec.displayName!; + +interface Api { + allowed?: boolean; + custody?: DeviceCustody | null | number; + operations?: DevicePowerOperation[] | number; + caller?: { username: string; uid?: string } | number; + create?: (body: unknown) => Response | Promise; +} + +const json = (data: unknown, status = 200) => Response.json(status < 400 ? { data } : { error: typeof data === 'string' ? data : 'Failed' }, { status }); + +function stub(api: Api = {}) { + const { allowed = true, custody = fixtureCustody(SERVER), operations = [], caller = { username: 'staff@example.com', uid: 'staff-uid' } } = api; + const fetch = vi.fn(async (url: string, init: RequestInit = {}) => { + if (url.includes('selfsubjectaccessreviews')) return json({ status: { allowed } }); + if (url.includes('selfsubjectreviews')) return typeof caller === 'number' ? json('Failed', caller) : json({ status: { userInfo: caller } }); + if (url.includes('/devicecustodies/')) return typeof custody === 'number' ? json('Failed', custody) : custody === null ? json('Not found', 404) : json(custody); + if (url.includes('/devicepoweroperations') && init.method === 'POST') return api.create ? api.create(JSON.parse(String(init.body))) : json({ ...JSON.parse(String(init.body)), metadata: { name: 'created', uid: 'created-uid' } }, 201); + if (url.includes('/devicepoweroperations')) return typeof operations === 'number' ? json('Failed', operations) : json({ items: operations }); + throw new Error(`Unexpected request ${url}`); + }); + vi.stubGlobal('fetch', fetch); + return fetch; +} + +function show(device: Device, ui: 'control' | 'history' | 'fact' = 'control') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const node = ui === 'control' ? : ui === 'history' ? :
; + return { ...render({node}), client }; +} + +const powerButton = () => screen.findByRole('button', { name: 'Power' }); +async function enabledPower() { + const button = await powerButton(); + await waitFor(() => expect(button).toBeEnabled()); + return button; +} +async function openDialog() { + fireEvent.click(await enabledPower()); + return screen.getByRole('dialog'); +} +const actionField = () => screen.getByRole('combobox', { name: /^Action/ }); +const posts = (fetch: ReturnType) => fetch.mock.calls.filter(([url, init]) => url.includes('/devicepoweroperations') && init?.method === 'POST'); + +beforeEach(() => vi.stubGlobal('confirm', vi.fn(() => true))); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +describe('Power control', () => { + it('offers only the actions discovery reports, in menu order', async () => { + stub(); + const device = named(SERVER); + device.status!.discovery!.inventory!.systems![0].resetTypes = ['PowerCycle', 'GracefulShutdown', 'On', 'Nmi']; + show(device); + await openDialog(); + expect(selectOptions(actionField()).map(option => [option.value, option.text])).toEqual([['On', 'Power on'], ['PowerCycle', 'Power cycle']]); + }); + + it('reads offered actions from the system with the recorded UUID, not another one', async () => { + stub(); + const device = named(SERVER); + const inventory = device.status!.discovery!.inventory!; + inventory.systems = [{ id: 'Other', uuid: '00000000-0000-4000-8000-00000000ffff', resetTypes: ['On', 'ForceOff', 'ForceRestart', 'PowerCycle'] }, { ...inventory.systems![0], uuid: UUID.toUpperCase(), resetTypes: ['ForceOff'] }]; + show(device); + await openDialog(); + expect(selectOptions(actionField()).map(option => option.value)).toEqual(['ForceOff']); + }); + + it('requires a reason and sends nothing without one', async () => { + const fetch = stub(); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + expect(await screen.findByRole('alert')).toHaveTextContent(/Reason/); + expect(screen.getByRole('textbox', { name: 'Reason' })).toHaveAttribute('aria-invalid', 'true'); + expect(posts(fetch)).toHaveLength(0); + }); + + it('sends the exact staff request: generated name, device-uid label, caller, Device name, reason and recorded system UUID', async () => { + const fetch = stub(); + const device = named(SERVER); + show(device); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: ' First power-on after racking ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + const [url, init] = posts(fetch)[0]; + expect(url).toBe('/api/internal/apis/resourcemanager.miloapis.com/v1alpha1/projects/datum-cloud/control-plane/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devicepoweroperations'); + expect(JSON.parse(String(init!.body))).toEqual({ + apiVersion: 'fleet.datumapis.com/v1alpha1', + kind: 'DevicePowerOperation', + metadata: { generateName: `${SERVER}-power-`, namespace: 'default', labels: { 'fleet.datumapis.com/device-uid': device.metadata.uid } }, + spec: { + // The creator is the only object UID a spec may carry; the Device incarnation is the label. + creator: { username: 'staff@example.com', uid: 'staff-uid' }, + deviceRef: { name: SERVER }, + authority: { serviceRequest: { reason: 'First power-on after racking' } }, + action: 'On', + expectedSystemUUID: UUID, + }, + }); + expect(await screen.findByRole('status')).toHaveTextContent('Power on requested'); + // The system UUID comes from the record: the dialog has no field for it. + expect(screen.queryByRole('textbox', { name: /UUID/ })).toBeNull(); + }); + + it.each([['ForceOff', 'Force off'], ['ForceRestart', 'Force restart'], ['PowerCycle', 'Power cycle']])('asks again before %s, naming the server', async (action, words) => { + const fetch = stub(); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), action); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Hung in firmware' } }); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + expect(posts(fetch)).toHaveLength(0); + expect(screen.getByRole('alert')).toHaveTextContent(`${words} ${NAME}?`); + // Back returns to the form without sending. + fireEvent.click(screen.getByRole('button', { name: 'Back' })); + expect(screen.queryByText(`${words} ${NAME}?`)).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + fireEvent.click(screen.getByRole('button', { name: `${words} ${NAME}` })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + expect(JSON.parse(String(posts(fetch)[0][1]!.body)).spec.action).toBe(action); + }); + + it('powers on without a second question and omits the UID for a username-only credential', async () => { + const fetch = stub({ caller: { username: 'staff@example.com' } }); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(posts(fetch)).toHaveLength(1)); + expect(JSON.parse(String(posts(fetch)[0][1]!.body)).spec.creator).toEqual({ username: 'staff@example.com' }); + }); + + it('is hidden without the power operator permission', async () => { + const fetch = stub({ allowed: false }); + show(named(SERVER)); + await waitFor(() => expect(fetch.mock.calls.some(([url]) => url.includes('selfsubjectaccessreviews'))).toBe(true)); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(screen.queryByRole('button', { name: 'Power' })).toBeNull(); + const review = JSON.parse(String(fetch.mock.calls.find(([url]) => url.includes('selfsubjectaccessreviews'))![1]!.body)); + expect(review.spec.resourceAttributes).toEqual({ group: 'fleet.datumapis.com', version: 'v1alpha1', resource: 'devicepoweroperations', namespace: 'default', verb: 'create' }); + // A user who cannot create is never asked for their identity. + expect(fetch.mock.calls.some(([url]) => url.includes('selfsubjectreviews'))).toBe(false); + }); + + const custodyWith = (spec: Partial) => ({ ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, ...spec } }); + const running = { ...fixturePowerOperations[0], status: { phase: 'Dispatched' as const } }; + it.each<[string, (device: Device) => void, Api]>([ + ['Allocated to a customer', () => undefined, { custody: custodyWith({ holder: { type: 'Allocation', allocationRef: { name: 'example-allocation' } } }) }], + ['Allocated to a customer', () => undefined, { custody: custodyWith({ holder: { type: 'Release', allocationRef: { name: 'example-allocation' }, openGates: ['Cleaning'] } }) }], + ['Held: DevicePowerOperation example-held outcome unknown', () => undefined, { custody: custodyWith({ holder: { type: 'Service' }, recoveryHold: { kind: 'DevicePowerOperation', name: 'example-held', fence: 3, since: '2026-01-02T03:04:05Z', reason: 'SiteCouldNotProve' } }) }], + ['DeviceWipe example-wipe is running', () => undefined, { custody: custodyWith({ activeOperation: { kind: 'DeviceWipe', name: 'example-wipe', fence: 5, phase: 'Dispatched', admittedAt: '', deadline: '', creator: { username: 'release', uid: 'r' } } }) }], + ['Force restart is in progress', () => undefined, { operations: [running] }], + ['Custody unverified', () => undefined, { custody: custodyWith({ state: 'Unverified' }) }], + ['Retired', () => undefined, { custody: custodyWith({ holder: { type: 'Retired' } }) }], + ['No custody record', () => undefined, { custody: null }], + ['No custody record', () => undefined, { custody: { ...fixtureCustody(SERVER)!, metadata: { ...fixtureCustody(SERVER)!.metadata, labels: { 'fleet.datumapis.com/device-uid': 'removed-device-uid' } } } }], + ['No custody record', () => undefined, { custody: { ...fixtureCustody(SERVER)!, metadata: { ...fixtureCustody(SERVER)!.metadata, labels: undefined } } }], + ['Custody unreadable', () => undefined, { custody: 403 }], + ['Not discovered', device => { device.status = undefined; }, {}], + ['No system UUID recorded', device => { device.spec.identity.systemUUID = undefined; }, {}], + ['The BMC offers no power actions', device => { device.status!.discovery!.inventory!.systems![0].resetTypes = undefined; }, {}], + ['Discovery read another BMC endpoint', device => { device.status!.discovery!.inventory!.endpoint = 'https://192.0.2.99:443'; }, {}], + ['Your username could not be read', () => undefined, { caller: 500 }], + ['The BMC offers no power actions', device => { device.status!.discovery!.inventory!.systems![0].resetTypesObserved = false; }, {}], + ['Power operations unreadable', () => undefined, { operations: 403 }], + ['Identity not matched', device => { device.status!.conditions = device.status!.conditions!.map(item => item.type === 'IdentityMatched' ? { ...item, status: 'False', reason: 'SerialMismatch' } : item); }, {}], + ['Identity not matched', device => { device.metadata.generation = 2; }, {}], + ['BMC key not read', device => { device.status!.discovery!.tls = undefined; }, {}], + ['BMC key not read', device => { device.status!.discovery!.tls!.endpoint = 'https://192.0.2.99:443'; }, {}], + ['BMC key shared', device => { device.status!.conditions = device.status!.conditions!.map(item => item.type === 'PublicKeyUnique' ? { ...item, status: 'False', reason: 'Shared' } : item); }, {}], + ['Held for a staff operation', () => undefined, { custody: custodyWith({ holder: { type: 'Service' } }) }], + ])('is disabled with the reason as its tooltip: %s', async (reason, change, api) => { + const fetch = stub(api); + const device = named(SERVER); + change(device); + show(device); + const button = await powerButton(); + await waitFor(() => expect(button).toHaveAccessibleDescription(reason)); + expect(button).toBeDisabled(); + expect(button.closest('[title]')).toHaveAttribute('title', reason); + fireEvent.click(button); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(posts(fetch)).toHaveLength(0); + }); + + it('is not blocked by a free Device with disabled capacity: only custody decides', async () => { + stub({ custody: custodyWith({ holder: { type: 'None' } }) }); + show(named(SERVER)); + expect(await enabledPower()).not.toHaveAccessibleDescription(); + }); + + it('keeps the control off after an unknown outcome, even after operations are read again', async () => { + const fetch = stub({ create: () => json('Upstream timeout', 504) }); + const { client } = show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(screen.getAllByRole('status')[0]).toHaveTextContent('Outcome unknown. Check Operations before another request.')); + expect(posts(fetch)).toHaveLength(1); + // The submit is off until the list has been reread: a second POST would be a second operation. + expect(screen.getByRole('button', { name: 'Power on' })).toBeDisabled(); + fireEvent.submit(screen.getByRole('button', { name: 'Power on' }).closest('form')!); + expect(posts(fetch)).toHaveLength(1); + // A reread does not prove the create did not land: it may still be in flight. + await act(async () => { await client.refetchQueries(); }); + expect(screen.getByRole('button', { name: 'Power on' })).toBeDisabled(); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(screen.getByRole('button', { name: 'Power' })).toHaveAccessibleDescription('Outcome unknown · check Operations, then reopen this Device'); + expect(posts(fetch)).toHaveLength(1); + }); + + it('keeps polling after a failed read, so one blip does not leave the control off', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + let fail = true; + const fetch = stub(); + const base = fetch.getMockImplementation()!; + fetch.mockImplementation(async (url: string, init?: RequestInit) => url.includes('/devicepoweroperations') && init?.method !== 'POST' && fail ? json('Unavailable', 503) : base(url, init)); + show(named(SERVER)); + const button = await powerButton(); + await waitFor(() => expect(button).toHaveAccessibleDescription('Power operations unreadable')); + fail = false; + await act(async () => { await vi.advanceTimersByTimeAsync(11_000); }); + await waitFor(() => expect(button).toBeEnabled()); + } finally { vi.useRealTimers(); } + }); + + it('closes an open request when the Device changes, and sends nothing for the old one', async () => { + const fetch = stub(); + const device = named(SERVER); + const view = show(device); + await openDialog(); + chooseValue(actionField(), 'ForceOff'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Move' } }); + fireEvent.click(screen.getByRole('button', { name: 'Continue' })); + view.rerender(); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(posts(fetch)).toHaveLength(0); + }); + + it('says nothing was sent when the request fails before the POST, and stays usable', async () => { + const fetch = stub(); + const base = fetch.getMockImplementation()!; + let reviews = 0; + // The permission is checked again at submit; that check fails on the network. + fetch.mockImplementation(async (url: string, init?: RequestInit) => url.includes('selfsubjectaccessreviews') && ++reviews > 1 ? Promise.reject(new TypeError('network')) : base(url, init)); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('Nothing was sent. Try again.')); + expect(posts(fetch)).toHaveLength(0); + expect(screen.getByRole('button', { name: 'Power on' })).toBeEnabled(); + }); + + it('reports a session change before sending as nothing sent', async () => { + const fetch = stub(); + const session = new InventoryOperationScope(); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render(); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + session.hold('checking'); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(fetch.mock.calls.filter(([url]) => url.includes('selfsubjectaccessreviews'))).toHaveLength(2)); + expect(posts(fetch)).toHaveLength(0); + session.invalidate(); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('The session changed. Nothing was sent.')); + expect(posts(fetch)).toHaveLength(0); + }); + + it('reports a denied create without calling it unknown', async () => { + stub({ create: () => json('forbidden', 403) }); + show(named(SERVER)); + await openDialog(); + chooseValue(actionField(), 'On'); + fireEvent.change(screen.getByRole('textbox', { name: 'Reason' }), { target: { value: 'Racked' } }); + fireEvent.click(screen.getByRole('button', { name: 'Power on' })); + await waitFor(() => expect(within(screen.getByRole('dialog')).getByRole('status')).toHaveTextContent('Power operator access is no longer valid. Nothing was created.')); + expect(screen.getByRole('button', { name: 'Power on' })).toBeEnabled(); + }); +}); + +describe('Operations history', () => { + const operation = (name: string, phase: NonNullable['phase'], extra: Partial> = {}, created = '2026-01-02T03:04:05Z'): DevicePowerOperation => ({ + metadata: { name, namespace: 'default', uid: `${name}-uid`, creationTimestamp: created, labels: { 'fleet.datumapis.com/device-uid': named(SERVER).metadata.uid! } }, + spec: { creator: { username: 'staff@example.com', uid: 's' }, deviceRef: { name: SERVER }, authority: { serviceRequest: { reason: `Reason for ${name}` } }, action: 'ForceRestart', expectedSystemUUID: UUID }, + status: { phase, ...extra }, + }); + const rows = () => within(screen.getByRole('table', { name: 'Power operations' })).getAllByRole('row').slice(1); + const resultOf = (name: string) => rows().find(row => row.textContent?.includes(`Reason for ${name}`))!.querySelector('.inventory-power-outcome')!; + + it.each<[string, DevicePowerOperation['status'], string, string | undefined]>([ + ['Pending', { phase: 'Pending' }, 'Pending', 'progress'], + ['Admitted', { phase: 'Admitted' }, 'Admitted', 'progress'], + ['Dispatched', { phase: 'Dispatched' }, 'Sent', 'progress'], + ['Verifying', { phase: 'Verifying' }, 'Verifying', 'progress'], + ['Succeeded', { phase: 'Succeeded', evidence: { requestSentAt: '2026-01-02T03:04:06Z', power: { before: { state: 'On', observedAt: '2026-01-02T03:04:05Z' }, after: { state: 'On', observedAt: '2026-01-02T03:04:41Z' } }, resetEvidence: 'LastResetTime' } }, 'Succeeded', undefined], + ['refused', { phase: 'Failed', reason: 'SystemUUIDMismatch', message: 'expectedSystemUUID is not the recorded system UUID' }, 'Refused', 'danger'], + ['failed after sending', { phase: 'Failed', reason: 'BMCRefused', evidence: { requestSentAt: '2026-01-02T03:04:06Z' } }, 'Failed', 'danger'], + ['Cancelled Expired', { phase: 'Cancelled', reason: 'Expired', message: 'a staff operation must be admitted within 5m0s' }, 'Expired', 'warning'], + ['Cancelled', { phase: 'Cancelled', reason: 'Withdrawn' }, 'Cancelled', 'warning'], + ['OutcomeUnknown', { phase: 'OutcomeUnknown', reason: 'SiteCouldNotProve' }, 'Outcome unknown', 'danger'], + ])('shows %s with its tone and reason', async (_, status, label, tone) => { + stub({ operations: [operation('one', status!.phase!, status)] }); + show(named(SERVER), 'history'); + const result = await waitFor(() => resultOf('one')); + expect(result).toHaveTextContent(new RegExp(`^${label}`)); + expect(result.getAttribute('data-tone') ?? undefined).toBe(tone); + const reason = [status!.reason, status!.message].filter(Boolean).join(' · '); + if (reason) expect(result).toHaveAttribute('title', reason); + }); + + const holdOn = (name: string, fence: number) => ({ ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, holder: { type: 'Service' as const }, recoveryHold: { kind: 'DevicePowerOperation', name, fence, since: '2026-01-02T03:10:00Z', reason: 'SiteCouldNotProve' } } }); + + it('names the recovery hold on an unknown outcome custody holds, matched by kind, name and admission fence', async () => { + const held = operation('held', 'OutcomeUnknown', { reason: 'SiteCouldNotProve', admission: { fence: 3 } }); + stub({ operations: [held], custody: holdOn('held', 3) }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('held')).toHaveTextContent('Outcome unknown · held')); + expect(resultOf('held')).toHaveAttribute('title', 'SiteCouldNotProve\nRecovery hold since 2026-01-02T03:10:00Z'); + }); + + it.each<[string, Partial>]>([ + ['a same-name operation created later, with no admission', {}], + ['a same-name operation admitted at another fence', { admission: { fence: 9 } }], + ])('does not claim the hold for %s', async (_, admission) => { + stub({ operations: [operation('held', 'OutcomeUnknown', { reason: 'SiteCouldNotProve', ...admission })], custody: holdOn('held', 3) }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('held')).toHaveTextContent(/^Outcome unknown\. SiteCouldNotProve$/)); + expect(resultOf('held')).not.toHaveTextContent(/held/i); + }); + + it('does not claim a hold for an unknown outcome custody no longer holds', async () => { + stub({ operations: [operation('settled', 'OutcomeUnknown', { reason: 'SiteCouldNotProve' })] }); + show(named(SERVER), 'history'); + await waitFor(() => expect(resultOf('settled')).toHaveTextContent(/^Outcome unknown\. SiteCouldNotProve$/)); + expect(resultOf('settled')).not.toHaveTextContent(/held/i); + }); + + it('lists action, result, power before and after, creator and reason, newest first', async () => { + stub({ operations: fixturePowerOperations.filter(item => item.spec.deviceRef.name === SERVER).reverse() }); + show(named(SERVER), 'history'); + await waitFor(() => expect(rows()).toHaveLength(4)); + expect(within(screen.getByRole('table')).getAllByRole('columnheader').map(cell => cell.textContent)).toEqual(['Time', 'Action', 'Result', 'Power', 'Creator', 'Reason']); + const cells = rows().map(row => within(row).getAllByRole('cell').slice(1).map(cell => cell.textContent)); + expect(cells[0]).toEqual(['Force restart', 'Succeeded', expect.stringMatching(/^On → On\./), 'staff@example.com', 'Hung in firmware during qualification']); + expect(cells[1]).toEqual(['Power cycle', expect.stringMatching(/^Refused/), '', 'tech@example.com', 'Retry after the BMC replacement']); + expect(cells[2]).toEqual(['Force off', expect.stringMatching(/^Expired/), '', 'tech@example.com', 'Move to rack a02']); + expect(cells[3]).toEqual(['Power on', 'Succeeded', expect.stringMatching(/^Off → On\./), 'staff@example.com', 'First power-on after racking']); + expect(within(rows()[0]).getByText('On → On')).toHaveAttribute('title', expect.stringContaining('BMC reported a reset')); + }); + + it('lists by the device-uid label, and ignores operations for another Device of the same name', async () => { + const old = operation('old', 'Succeeded'); + const fetch = stub({ operations: [{ ...old, metadata: { ...old.metadata, labels: { 'fleet.datumapis.com/device-uid': 'removed-device-uid' } } }] }); + show(named(SERVER), 'history'); + expect(await screen.findByText('No power operations')).toBeInTheDocument(); + const list = fetch.mock.calls.find(([url, init]) => url.includes('/devicepoweroperations') && init?.method !== 'POST')![0]; + expect(new URL(list, 'http://x').searchParams.get('labelSelector')).toBe(`fleet.datumapis.com/device-uid=${named(SERVER).metadata.uid}`); + }); + + it('ignores an unlabelled operation', async () => { + const bare = operation('bare', 'Succeeded'); + stub({ operations: [{ ...bare, metadata: { ...bare.metadata, labels: undefined } }] }); + show(named(SERVER), 'history'); + expect(await screen.findByText('No power operations')).toBeInTheDocument(); + }); + + it('says the history is unreadable rather than empty', async () => { + stub({ operations: 403 }); + show(named(SERVER), 'history'); + expect(await screen.findByText('Power operations unreadable')).toBeInTheDocument(); + }); +}); + +describe('header power fact', () => { + it('shows the observed state and the running operation', async () => { + stub({ operations: [{ ...fixturePowerOperations[0], status: { phase: 'Verifying' } }] }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent('On Force restart · Verifying')); + }); + + it('drops an operation that ended over an hour ago', async () => { + stub({ operations: [{ ...fixturePowerOperations[0], status: { phase: 'Succeeded', finishedAt: new Date(Date.now() - 2 * 3_600_000).toISOString() } }] }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent(/^On$/)); + }); + + it('keeps an unknown outcome while custody holds it', async () => { + const held = { ...fixturePowerOperations[0], status: { phase: 'OutcomeUnknown' as const, admission: { fence: 2 }, finishedAt: new Date(Date.now() - 5 * 3_600_000).toISOString() } }; + stub({ operations: [held], custody: { ...fixtureCustody(SERVER)!, spec: { ...fixtureCustody(SERVER)!.spec, recoveryHold: { kind: 'DevicePowerOperation', name: held.metadata.name, fence: 2, since: held.status.finishedAt, reason: 'SiteCouldNotProve' } } } }); + show(named(SERVER), 'fact'); + await waitFor(() => expect(screen.getByRole('definition')).toHaveTextContent('On Force restart · Outcome unknown · held')); + }); +}); diff --git a/ui/provider/src/components/device-power.tsx b/ui/provider/src/components/device-power.tsx new file mode 100644 index 00000000..40549676 --- /dev/null +++ b/ui/provider/src/components/device-power.tsx @@ -0,0 +1,210 @@ +// Staff power on the Device page: the observed power state and the latest +// operation in the header strip, the Power control in the header actions, and +// the Operations tab. See "Device page: power" in +// docs/development/staff-inventory-ui.md. +import { Button } from '@datum-cloud/datum-ui/button'; +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { useQueryClient } from '@tanstack/react-query'; +import { useContext, useEffect, useId, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; +import type { Device, DeviceCustody, DevicePowerOperation, PowerAction } from '../../../shared/fleet-api'; +import { ApiError } from '../lib/api'; +import { comparedSystem, powerWord, staleReason } from '../lib/device-discovery'; +import { + ACTION_WORDS, createPowerOperation, destructive, evidenceNote, offeredActions, powerBlock, powerChange, powerOutcome, POWER_QUERY_KEY, + useCaller, useCustody, usePowerOperations, usePowerPermission, type PowerOutcome, +} from '../lib/device-power'; +import { displayLabel } from '../lib/display-names'; +import { InventoryOperationContext, InventoryOperationGenerationContext, InventoryOperationInvalidated, InventoryOperationReadyContext, InventoryOperationScope } from '../lib/inventory-operation'; +import { formatAge } from '../lib/telemetry'; +import { FieldSelect } from './field-select'; +import { InventoryDraftGuard, InventoryForm, InventoryFormSurface } from './inventory-form-surface'; +import { SmallTable } from './inventory-record-layout'; + +const HOUR = 3_600_000; + +/** A phase badge: the reason and any recovery hold are its tooltip and accessible text. */ +export function PowerOutcomeBadge({ outcome, prefix }: { outcome: PowerOutcome; prefix?: string }) { + const note = [outcome.reason, outcome.hold].filter(Boolean).join('\n') || undefined; + return + {prefix && <>{prefix} · }{outcome.label}{outcome.hold && } + {note && . {note}} + ; +} + +/** + * The header's power fact: the observed state, then the latest operation + * while it runs, for an hour after it ends, or while custody holds it. + */ +export function DevicePowerFact({ device }: { device: Device }) { + const operations = usePowerOperations(device); + const custody = useCustody(device); + const system = comparedSystem(device); + const stale = staleReason(device.status?.discovery?.inventory, device); + const state = powerWord(system?.powerState); + const latest = operations.data?.[0]; + const outcome = latest && powerOutcome(latest, custody.data); + const finished = latest?.status?.finishedAt ? Date.parse(latest.status.finishedAt) : NaN; + const recent = outcome && (outcome.tone === 'progress' || !!outcome.hold || !(Date.now() - finished > HOUR)); + if (!state && !recent) return null; + return
Power
+ {state && {state}{stale && . Check: {stale}}} + {recent && latest && <> } +
; +} + +function failureMessage(error: unknown, sent: boolean): { message: string; uncertain: boolean } { + if (error instanceof InventoryOperationInvalidated) return { message: error.dispatched ? 'Outcome unknown: the session changed after sending. Check Operations before another request.' : 'The session changed. Nothing was sent.', uncertain: error.dispatched }; + if (error instanceof ApiError && error.status === 422) return { message: `Rejected: ${error.message}`, uncertain: false }; + if (error instanceof ApiError && [401, 403].includes(error.status)) return { message: 'Power operator access is no longer valid. Nothing was created.', uncertain: false }; + // Before the POST went out, nothing can have been created. + if (!sent) return { message: 'Nothing was sent. Try again.', uncertain: false }; + return { message: 'Outcome unknown. Check Operations before another request.', uncertain: true }; +} + +/** + * The Power button and its dialog. Hidden without the power operator role; + * disabled, with the reason as its tooltip, when the Device cannot be powered + * now. A destructive action asks again, naming the server. + */ +export function DevicePowerControl({ device }: { device: Device }) { + const client = useQueryClient(); + const session = useContext(InventoryOperationContext); + const ready = useContext(InventoryOperationReadyContext); + const generation = useContext(InventoryOperationGenerationContext); + const permission = usePowerPermission(true); + const permitted = permission.data === true && !permission.error; + const caller = useCaller(permitted); + const custody = useCustody(device); + const operations = usePowerOperations(device); + const scope = useRef(new InventoryOperationScope()); + const [open, setOpen] = useState(false); + const [action, setAction] = useState(''); + const [reason, setReason] = useState(''); + const [confirming, setConfirming] = useState(false); + const [pending, setPending] = useState(false); + const [message, setMessage] = useState(''); + // A create whose outcome is unknown may still land, and a second POST would be a second + // operation, so the control stays off until the Device page is opened again. + const [uncertain, setUncertain] = useState(false); + const hintID = useId(); + useEffect(() => () => scope.current.invalidate(), []); + // As in the location editor: leaving the page, a new session or navigation, or a changed + // Device ends the open request, so a confirmation never names a state the page no longer shows. + useLayoutEffect(() => { + const invalidate = () => scope.current.invalidate(); + const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; + window.addEventListener('pagehide', invalidate); + document.addEventListener('visibilitychange', visibility); + return () => { window.removeEventListener('pagehide', invalidate); document.removeEventListener('visibilitychange', visibility); }; + }, []); + useLayoutEffect(() => { + scope.current.invalidate(); + setOpen(false); setAction(''); setReason(''); setConfirming(false); + }, [device.metadata.uid, device.metadata.resourceVersion, session, generation]); + if (!permitted) return null; + const server = displayLabel(device); + const offered = offeredActions(device); + const block = powerBlock(device, { custody: custody.data, custodyError: custody.error, operations: operations.data }) + ?? (caller.error ? 'Your username could not be read' : !caller.data || !ready || permission.isFetching ? 'Checking access…' : undefined) + ?? (operations.error ? 'Power operations unreadable' : undefined) + ?? (!operations.data ? 'Checking power operations…' : undefined) + ?? (uncertain ? 'Outcome unknown · check Operations, then reopen this Device' : undefined); + const chosen = offered.find(item => item === action); + const dirty = open && (!!action || !!reason); + function reset() { setAction(''); setReason(''); setConfirming(false); } + function dismiss() { + if (pending) return; + if (dirty && !uncertain && !window.confirm('Discard this power request?')) return; + scope.current.invalidate(); setOpen(false); reset(); + } + async function send() { + if (!chosen || !caller.data || pending || block) return; + const operation = scope.current.begin(session); + setPending(true); setMessage(''); + try { + await createPowerOperation(device, chosen, reason, caller.data, operation); + setOpen(false); reset(); setMessage(`${ACTION_WORDS[chosen]} requested`); + } catch (error) { + const failure = failureMessage(error, operation.sent); + setMessage(failure.message); + if (failure.uncertain) { setUncertain(true); setConfirming(false); } + } finally { + setPending(false); + await client.invalidateQueries({ queryKey: POWER_QUERY_KEY }); + } + } + function submit(event: FormEvent) { + event.preventDefault(); + if (!chosen || block) return; + if (destructive(chosen) && !confirming) { setConfirming(true); return; } + void send(); + } + const hint = block ? { id: hintID, text: block } : undefined; + const status =

{message}

; + const verb = chosen ? ACTION_WORDS[chosen] : 'Continue'; + return
+ {open && } + { if (block) return; scope.current = new InventoryOperationScope(); reset(); setMessage(''); setOpen(true); }}>Power}> + +
+ + +
+ {confirming && chosen &&

+ {ACTION_WORDS[chosen]} {server}? +

} +
+ + +
+
+
+
; +} + +const HISTORY_LIMIT = 20; + +function Time({ value, now }: { value?: string; now: number }) { + const at = value ? Date.parse(value) : NaN; + if (!Number.isFinite(at)) return null; + return ; +} + +function historyRow(operation: DevicePowerOperation, custody: DeviceCustody | null | undefined, now: number) { + const evidence = operation.status?.evidence; + const change = powerChange(evidence); + const note = evidenceNote(evidence); + const reason = operation.spec.authority.serviceRequest?.reason; + return [ +