Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add a bulk web-link editor to the workloads table
rcourtman967e51701e21
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 520e96d735..bf3d2d6e9b 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -1118,6 +1118,16 @@ change may globally weaken the Task 03 lifecycle-state idempotency invariant.renders only for a saved URL and adds no fetch, polling or per-row work.`GuestDrawer.test.tsx` verifies its target, the unsafe-URL warning, andthat opening it does not collapse the drawer.+ The workloads table header owns the bulk web-link editor in+ `WorkloadWebLinksDialog.tsx`, with derivations in+ `workloadWebLinksModel.ts`. It edits the guests in the current filtered+ view through the same guest metadata API and metadata-changed event as the+ drawer field, and `getWorkloadGuestMetadataRecord` is the single lookup for+ a row's saved link in both the table and the editor. Editor rows read live+ inventory only while the dialog is open and keep unchanged row objects+ across ticks, so a closed editor adds no per-tick work and an open one+ never remounts the input being typed in.+ `WorkloadsSurface.performance.contract.test.tsx` pins that wiring.Drawer history charts belong to `frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx`.A current metric may remain visible in a chart legend only when labelled`current`; it must never be expanded into synthetic timestamps or a flatdiff --git a/frontend-modern/browser-verification/743cc04a20d534ac.json b/frontend-modern/browser-verification/743cc04a20d534ac.jsonnew file mode 100644index 0000000000..76e0f3baaf--- /dev/null+++ b/frontend-modern/browser-verification/743cc04a20d534ac.json@@ -0,0 +1,52 @@+{+ "version": 1,+ "base_sha": "53e2d27ab420c505f54694b0ccbb7d843ff6eded",+ "verified_at": "2026-10-04T23:36:36Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/components/Workloads/WorkloadPanel.tsx",+ "frontend-modern/src/components/Workloads/WorkloadWebLinksDialog.tsx",+ "frontend-modern/src/components/Workloads/WorkloadsSurface.tsx",+ "frontend-modern/src/components/Workloads/WorkloadsTable.tsx",+ "frontend-modern/src/components/Workloads/workloadWebLinksModel.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/Workloads/WorkloadPanel.tsx": "f46e070a2fad03d7fe30103a8f5a9a6412604a810b3b4b65c56071baeaf6198c",+ "frontend-modern/src/components/Workloads/WorkloadWebLinksDialog.tsx": "85af2231815206c30c34671af4b358cb9e4243df4a1fa54e7f9968491cc668fa",+ "frontend-modern/src/components/Workloads/WorkloadsSurface.tsx": "ea5b51e677ccb2a8deaeb51e18068ef7c4dd4a956f0004b4afb373e67708985a",+ "frontend-modern/src/components/Workloads/WorkloadsTable.tsx": "d7d54e85014320bf46a3a19fd0ac47d12de3341580bd368643a9a0edc56232bc",+ "frontend-modern/src/components/Workloads/workloadWebLinksModel.ts": "cec219e47e3bf46487fccdac46535cb6ae0301b5e3e165970d0bf3946f9179e8"+ },+ "routes": [+ "/proxmox",+ "/proxmox?agent=Production+West-pve2"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 800+ },+ {+ "width": 1024,+ "height": 768+ },+ {+ "width": 375,+ "height": 812+ }+ ],+ "states": [+ "Private mock stack built from this tree (backend :7701, Vite :5221, 3 nodes, 31 Proxmox guests) with five guests already carrying saved web-interface URLs.",+ "Guests table header shows an 'Edit links' action beside the guest count at 1280, 1024 and 375 widths without horizontal overflow; it opens a right-hand panel listing all 31 guests in the filtered view, name-sorted, each with type, ID and node, the saved URL or an IP-based placeholder, and a label tied to its input.",+ "Node-scoped view (Show guests on West Production B) limits the editor to that node's 8 guests; the 'Without a link' filter shows the 25 guests with no saved link, including one whose link was just removed.",+ "Phone 375x812: full-height sheet, name above a 44px input, footer pinned, no horizontal overflow (dark theme). Light theme checked at 1280.",+ "Invalid entry 'auth14 admin page' blocked the whole save with the shared validator's message on that row and aria-invalid; native browser URL validation is disabled so Pulse's message shows. GET /api/guests/metadata confirmed nothing was written.",+ "Valid save of one addition, one correction and one removal wrote all three through PUT /api/guests/metadata, showed 'Saved 3 links.', closed the panel, returned focus to the trigger, and the table link icons updated without reload. This is not physical-device, vSphere-estate or release acceptance.",+ "Re-checked after renaming the row-reuse helper (identifier only): the editor opened with 31 rows, a draft survived three seconds of live ticks, and submitting saved docs-wiki-01 through PUT /api/guests/metadata and closed the panel."+ ],+ "interactions": [+ "Clicked Edit links; typed into three inputs over several live inventory ticks without losing focus or values; footer counted 3 unsaved changes and the trigger showed (unsaved).",+ "Pressed Enter to submit with one invalid value, corrected it, pressed Enter again; toggled All / Without a link; closed via the header button and reopened.",+ "Selected a node's guests from the nodes table, then reopened the editor to confirm scope follows the table filter."+ ]+}diff --git a/frontend-modern/src/components/Workloads/WorkloadPanel.tsx b/frontend-modern/src/components/Workloads/WorkloadPanel.tsxindex dcd3c1da11..971c1b401f 100644--- a/frontend-modern/src/components/Workloads/WorkloadPanel.tsx+++ b/frontend-modern/src/components/Workloads/WorkloadPanel.tsx@@ -32,6 +32,7 @@ import { GuestDrawer } from './GuestDrawer';import { GuestRow } from './GuestRow';import { NodeDrawer } from './NodeDrawer';import { buildWorkloadSummaryGroupScope } from './workloadSelectors';+import { getWorkloadGuestMetadataRecord } from './workloadWebLinksModel';import type { WorkloadsState } from './useWorkloadsState';import type { WorkloadTableMetric } from './workloadMetricHistoryModel';@@ -550,15 +551,8 @@ export function WorkloadPanel(props: WorkloadPanelProps) {const detailControlsId = createMemo(() =>buildSummaryDisclosureControlsId(guestId()),);- const metadata = () => {- const byId = props.guestMetadata();- for (const metadataId of metadataIdCandidates()) {- if (metadataId && byId[metadataId]) {- return byId[metadataId];- }- }- return byId[`${guest().instance}:${guest().node}:${guest().vmid}`];- };+ const metadata = () =>+ getWorkloadGuestMetadataRecord(guest(), props.guestMetadata());const parentNode = () => node() ?? props.guestParentNodeMap()[guestId()];const parentNodeOnline = () => {const pn = parentNode();diff --git a/frontend-modern/src/components/Workloads/WorkloadWebLinksDialog.tsx b/frontend-modern/src/components/Workloads/WorkloadWebLinksDialog.tsxnew file mode 100644index 0000000000..3b58606e30--- /dev/null+++ b/frontend-modern/src/components/Workloads/WorkloadWebLinksDialog.tsx@@ -0,0 +1,294 @@+import { For, Show, createMemo, createSignal, createUniqueId, type Component } from 'solid-js';+import Link2Icon from 'lucide-solid/icons/link-2';+import XIcon from 'lucide-solid/icons/x';+import { GuestMetadataAPI } from '@/api/guestMetadata';+import { ActionIconButton, Button } from '@/components/shared/Button';+import { Dialog } from '@/components/shared/Dialog';+import { FilterSegmentedControl } from '@/components/shared/FilterToolbar';+import { formControlDense } from '@/components/shared/Form';+import { StatusDot } from '@/components/shared/StatusDot';+import { TABLE_CARD_HEADER_CLEAR_BUTTON_CLASS } from '@/components/shared/TableCardHeader';+import { notificationStore } from '@/stores/notifications';+import { presentationPolicyIsReadOnly } from '@/stores/sessionPresentationPolicy';+import type { WorkloadGuest } from '@/types/workloads';+import { dispatchResourceMetadataChanged } from '@/utils/resourceMetadataEvents';+import { getSimpleStatusIndicator } from '@/utils/status';+import {+ buildWorkloadWebLinkRows,+ filterWorkloadWebLinkRows,+ formatWorkloadWebLinkCount,+ getWorkloadWebLinkChanges,+ getWorkloadWebLinkPlaceholder,+ getWorkloadWebLinkValue,+ keepStableWorkloadWebLinkRows,+ validateWorkloadWebLinkChanges,+ type WorkloadGuestMetadataMap,+ type WorkloadWebLinkDrafts,+ type WorkloadWebLinkFilter,+ type WorkloadWebLinkRow,+} from './workloadWebLinksModel';++export interface WorkloadWebLinksActionProps {+ guests: () => WorkloadGuest[];+ guestMetadata: () => WorkloadGuestMetadataMap;+}++/**+ * Table-header entry point for setting many web links at once. Drafts live+ * here rather than in the dialog so closing it by accident keeps typed links.+ */+export const WorkloadWebLinksAction: Component<WorkloadWebLinksActionProps> = (props) => {+ const formId = `workload-web-links-${createUniqueId()}`;+ const [open, setOpen] = createSignal(false);+ const [filter, setFilter] = createSignal<WorkloadWebLinkFilter>('all');+ const [drafts, setDrafts] = createSignal<WorkloadWebLinkDrafts>({});+ const [errors, setErrors] = createSignal<Record<string, string>>({});+ const [saving, setSaving] = createSignal(false);+ let triggerRef: HTMLButtonElement | undefined;++ // Rows only track live inventory while the dialog is open, so a closed+ // editor adds no per-tick work to the workloads table.+ const rows = createMemo<WorkloadWebLinkRow[]>(+ (previous) =>+ open()+ ? keepStableWorkloadWebLinkRows(+ previous,+ buildWorkloadWebLinkRows(props.guests(), props.guestMetadata()),+ )+ : previous,+ [],+ );+ const visibleRows = createMemo(() => filterWorkloadWebLinkRows(rows(), filter()));+ const linkedCount = createMemo(() => rows().filter((row) => row.savedUrl).length);+ const changes = createMemo(() => getWorkloadWebLinkChanges(rows(), drafts()));++ const setDraft = (metadataId: string, value: string) => {+ setDrafts((current) => ({ ...current, [metadataId]: value }));+ if (errors()[metadataId]) {+ setErrors(({ [metadataId]: _cleared, ...rest }) => rest);+ }+ };++ const discardChanges = () => {+ setDrafts({});+ setErrors({});+ };++ const focusFirstError = (failed: Record<string, string>) => {+ const firstId = rows().find((row) => failed[row.metadataId])?.metadataId;+ if (!firstId) return;+ queueMicrotask(() =>+ Array.from(document.querySelectorAll<HTMLInputElement>(`#${formId} input`))+ .find((input) => input.dataset.metadataId === firstId)+ ?.focus(),+ );+ };++ const save = async () => {+ const pending = changes();+ if (pending.length === 0 || saving()) return;++ const invalid = validateWorkloadWebLinkChanges(pending);+ if (Object.keys(invalid).length > 0) {+ setErrors(invalid);+ setFilter('all');+ focusFirstError(invalid);+ return;+ }++ setSaving(true);+ const failed: Record<string, string> = {};+ let savedCount = 0;+ for (const change of pending) {+ try {+ await GuestMetadataAPI.updateMetadata(change.metadataId, { customUrl: change.url });+ dispatchResourceMetadataChanged({+ metadataKind: 'guest',+ metadataId: change.metadataId,+ customUrl: change.url,+ });+ setDrafts(({ [change.metadataId]: _saved, ...rest }) => rest);+ savedCount += 1;+ } catch (error) {+ failed[change.metadataId] =+ error instanceof Error && error.message ? error.message : 'Could not save this link.';+ }+ }+ setSaving(false);+ setErrors(failed);++ if (Object.keys(failed).length === 0) {+ notificationStore.success(`Saved ${formatWorkloadWebLinkCount(savedCount)}.`);+ setOpen(false);+ return;+ }+ focusFirstError(failed);+ };++ return (+ <Show when={!presentationPolicyIsReadOnly()}>+ <button+ ref={triggerRef}+ type="button"+ class={`${TABLE_CARD_HEADER_CLEAR_BUTTON_CLASS} min-h-6 gap-1`}+ aria-haspopup="dialog"+ onClick={() => setOpen(true)}+ >+ <Link2Icon class="h-3.5 w-3.5" aria-hidden="true" />+ Edit links+ <Show when={changes().length > 0}>+ <span class="text-amber-600 dark:text-amber-400">(unsaved)</span>+ </Show>+ </button>+ <Dialog+ isOpen={open()}+ onClose={() => setOpen(false)}+ layout="drawer-right"+ panelClass="max-w-full sm:max-w-2xl"+ ariaLabelledBy={`${formId}-title`}+ returnFocus={() => triggerRef}+ >+ <div class="flex h-full min-h-0 flex-col" data-testid="workload-web-links">+ <header class="flex shrink-0 items-start justify-between gap-3 border-b border-border bg-surface px-4 py-3">+ <div class="min-w-0">+ <h2 id={`${formId}-title`} class="text-base font-semibold text-base-content">+ Web links+ </h2>+ <p class="text-xs text-muted">+ Add the address you open in your browser for each guest. Pulse shows it as a link+ beside the guest.+ </p>+ </div>+ <ActionIconButton+ type="button"+ onClick={() => setOpen(false)}+ label="Close web links"+ title="Close"+ tone="muted"+ size="md"+ >+ <XIcon class="h-5 w-5" aria-hidden="true" />+ </ActionIconButton>+ </header>++ <div class="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-border px-4 py-2">+ <p class="text-xs text-muted" data-testid="workload-web-links-summary">+ {linkedCount()} of {rows().length} in this view have a link+ </p>+ <FilterSegmentedControl+ aria-label="Show guests"+ value={filter()}+ onChange={(value) => setFilter(value as WorkloadWebLinkFilter)}+ options={[+ { value: 'all', label: 'All' },+ { value: 'missing', label: 'Without a link' },+ ]}+ />+ </div>++ <form+ id={formId}+ noValidate+ class="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4"+ onSubmit={(event) => {+ event.preventDefault();+ void save();+ }}+ >+ <Show+ when={visibleRows().length > 0}+ fallback={+ <p class="py-6 text-center text-sm text-muted">+ {rows().length === 0+ ? 'No guests in this view.'+ : 'Every guest in this view has a link.'}+ </p>+ }+ >+ <ul class="divide-y divide-border">+ <For each={visibleRows()}>+ {(row) => {+ const inputId = `${formId}-${row.metadataId.replace(/[^a-zA-Z0-9_-]/g, '_')}`;+ const errorId = `${inputId}-error`;+ const status = () => getSimpleStatusIndicator(row.status);+ const error = () => errors()[row.metadataId];+ return (+ <li class="flex flex-col gap-1.5 py-2.5 sm:flex-row sm:items-start sm:gap-3">+ <div class="min-w-0 sm:w-52 sm:shrink-0 sm:pt-1.5">+ <label+ for={inputId}+ class="flex items-center gap-1.5 text-sm font-medium text-base-content"+ >+ <StatusDot+ variant={status().variant}+ ariaLabel={status().label}+ title={status().label}+ size="xs"+ />+ <span class="break-all">{row.name}</span>+ </label>+ <Show when={row.detail}>+ <p class="pl-3 text-[11px] text-muted">{row.detail}</p>+ </Show>+ </div>+ <div class="min-w-0 flex-1">+ <input+ id={inputId}+ data-metadata-id={row.metadataId}+ type="url"+ inputMode="url"+ autocomplete="off"+ spellcheck={false}+ class={formControlDense}+ placeholder={getWorkloadWebLinkPlaceholder(row)}+ value={getWorkloadWebLinkValue(row, drafts())}+ onInput={(event) => setDraft(row.metadataId, event.currentTarget.value)}+ disabled={saving()}+ aria-invalid={error() ? 'true' : undefined}+ aria-describedby={error() ? errorId : undefined}+ />+ <Show when={error()}>+ <p id={errorId} class="mt-1 text-xs text-red-600 dark:text-red-400">+ {error()}+ </p>+ </Show>+ </div>+ </li>+ );+ }}+ </For>+ </ul>+ </Show>+ </form>++ <footer class="flex shrink-0 flex-wrap items-center justify-between gap-2 border-t border-border bg-surface px-4 py-3">+ <p class="text-xs text-muted" role="status" aria-live="polite">+ {changes().length === 0+ ? 'No unsaved changes'+ : `${changes().length} unsaved ${changes().length === 1 ? 'change' : 'changes'}`}+ </p>+ <div class="flex items-center gap-2">+ <Show when={changes().length > 0}>+ <Button variant="ghost" size="sm" onClick={discardChanges} disabled={saving()}>+ Discard+ </Button>+ </Show>+ <Button+ type="submit"+ form={formId}+ variant="primary"+ size="sm"+ disabled={changes().length === 0}+ isLoading={saving()}+ >+ {changes().length > 1 ? `Save ${changes().length} links` : 'Save'}+ </Button>+ </div>+ </footer>+ </div>+ </Dialog>+ </Show>+ );+};++export default WorkloadWebLinksAction;diff --git a/frontend-modern/src/components/Workloads/WorkloadsSurface.tsx b/frontend-modern/src/components/Workloads/WorkloadsSurface.tsxindex d1d5824bce..456d239fee 100644--- a/frontend-modern/src/components/Workloads/WorkloadsSurface.tsx+++ b/frontend-modern/src/components/Workloads/WorkloadsSurface.tsx@@ -16,6 +16,7 @@ import {hasActiveWorkloadsFilters,} from './workloadsFilterModel';import { WorkloadsTable } from './WorkloadsTable';+import { WorkloadWebLinksAction } from './WorkloadWebLinksDialog';import type { WorkloadInventorySourceIssue } from './workloadInventorySourceIssues';import {useWorkloadsState,@@ -246,6 +247,12 @@ export function WorkloadsSurface(props: WorkloadsSurfaceComponentProps) {cancelWorkloadColumnResize={state.cancelWorkloadColumnResize}clearWorkloadColumnWidth={state.clearWorkloadColumnWidth}title={props.tableTitle}+ actions={+ <WorkloadWebLinksAction+ guests={state.filteredGuests}+ guestMetadata={state.guestMetadata}+ />+ }/></Show><Showdiff --git a/frontend-modern/src/components/Workloads/WorkloadsTable.tsx b/frontend-modern/src/components/Workloads/WorkloadsTable.tsxindex 4879760192..2f25d5598b 100644--- a/frontend-modern/src/components/Workloads/WorkloadsTable.tsx+++ b/frontend-modern/src/components/Workloads/WorkloadsTable.tsx@@ -73,6 +73,7 @@ type WorkloadsTableProps = Pick<| 'clearWorkloadColumnWidth'> & {title?: JSX.Element;+ actions?: JSX.Element;};export function WorkloadsTable(props: WorkloadsTableProps) {@@ -84,7 +85,7 @@ export function WorkloadsTable(props: WorkloadsTableProps) {data-summary-clear-surfacedata-testid="workloads-table-surface">- <TableCardHeader title={props.title} />+ <TableCardHeader title={props.title} actions={props.actions} /><TablewrapperRef={props.setTableWrapperRef}class={`platform-table workload-table table-fixed ${props.isMobile() ? `workload-table--mobile ${WORKLOAD_TABLE_MOBILE_MIN_WIDTH_CLASS}` : 'workload-table--desktop min-w-full'}${props.workloadManualColumnSizing() ? ' workload-table--manual-widths' : ''}`}diff --git a/frontend-modern/src/components/Workloads/__tests__/WorkloadWebLinksDialog.test.tsx b/frontend-modern/src/components/Workloads/__tests__/WorkloadWebLinksDialog.test.tsxnew file mode 100644index 0000000000..727ea6e2d9--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/WorkloadWebLinksDialog.test.tsx@@ -0,0 +1,197 @@+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 type { WorkloadGuest } from '@/types/workloads';+import { getWorkloadMetadataId } from '@/utils/workloads';+import {+ RESOURCE_METADATA_CHANGED_EVENT,+ type ResourceMetadataChangedDetail,+} from '@/utils/resourceMetadataEvents';+import { WorkloadWebLinksAction } from '../WorkloadWebLinksDialog';+import type { WorkloadGuestMetadataMap } from '../workloadWebLinksModel';++const { updateMetadataMock, successMock, readOnlyMock } = vi.hoisted(() => ({+ updateMetadataMock: vi.fn(),+ successMock: vi.fn(),+ readOnlyMock: vi.fn(() => false),+}));++vi.mock('@/api/guestMetadata', () => ({+ GuestMetadataAPI: { updateMetadata: updateMetadataMock },+}));++vi.mock('@/stores/notifications', () => ({+ notificationStore: { success: successMock, error: vi.fn(), info: vi.fn() },+}));++vi.mock('@/stores/sessionPresentationPolicy', () => ({+ presentationPolicyIsReadOnly: readOnlyMock,+}));++const makeGuest = (overrides: Partial<WorkloadGuest>): WorkloadGuest =>+ ({+ node: 'pve1',+ instance: 'cluster',+ status: 'running',+ type: 'lxc',+ ...overrides,+ }) as WorkloadGuest;++const auth = makeGuest({ id: 'auth', vmid: 107, name: 'auth-service-01' });+const billing = makeGuest({ id: 'billing', vmid: 108, name: 'billing-worker-01' });+const cache = makeGuest({ id: 'cache', vmid: 117, name: 'artifact-cache-01' });+const authId = getWorkloadMetadataId(auth);+const billingId = getWorkloadMetadataId(billing);+const cacheId = getWorkloadMetadataId(cache);++const renderAction = (metadata: WorkloadGuestMetadataMap = {}) => {+ const [guests] = createSignal([auth, billing, cache]);+ const [guestMetadata, setGuestMetadata] = createSignal(metadata);+ const events: ResourceMetadataChangedDetail[] = [];+ const onChanged = (event: Event) => {+ const detail = (event as CustomEvent<ResourceMetadataChangedDetail>).detail;+ events.push(detail);+ setGuestMetadata((current) => ({+ ...current,+ [detail.metadataId!]: { id: detail.metadataId!, customUrl: detail.customUrl },+ }));+ };+ window.addEventListener(RESOURCE_METADATA_CHANGED_EVENT, onChanged);+ render(() => <WorkloadWebLinksAction guests={guests} guestMetadata={guestMetadata} />);+ return {+ events,+ dispose: () => window.removeEventListener(RESOURCE_METADATA_CHANGED_EVENT, onChanged),+ };+};++const openEditor = () => {+ fireEvent.click(screen.getByRole('button', { name: /Edit links/ }));+ return within(screen.getByRole('dialog', { name: 'Web links' }));+};++describe('WorkloadWebLinksAction', () => {+ let harness: ReturnType<typeof renderAction> | undefined;++ beforeEach(() => {+ updateMetadataMock.mockReset();+ updateMetadataMock.mockResolvedValue({});+ successMock.mockReset();+ readOnlyMock.mockReturnValue(false);+ });++ afterEach(() => {+ harness?.dispose();+ harness = undefined;+ cleanup();+ });++ it('is absent from read-only sessions', () => {+ readOnlyMock.mockReturnValue(true);+ harness = renderAction();++ expect(screen.queryByRole('button', { name: /Edit links/ })).not.toBeInTheDocument();+ });++ it('lists every guest in the view with its saved link and a labelled input', () => {+ harness = renderAction({ [authId]: { id: authId, customUrl: 'https://auth.example' } });+ const dialog = openEditor();++ expect(dialog.getByTestId('workload-web-links-summary')).toHaveTextContent(+ '1 of 3 in this view have a link',+ );+ expect(dialog.getByLabelText(/auth-service-01/)).toHaveValue('https://auth.example');+ expect(dialog.getByLabelText(/artifact-cache-01/)).toHaveValue('');++ fireEvent.click(dialog.getByRole('button', { name: 'Without a link' }));+ expect(dialog.queryByLabelText(/auth-service-01/)).not.toBeInTheDocument();+ expect(dialog.getByLabelText(/billing-worker-01/)).toBeInTheDocument();+ });++ it('blocks the whole save on an invalid link and explains it on that row', async () => {+ harness = renderAction();+ const dialog = openEditor();++ fireEvent.input(dialog.getByLabelText(/artifact-cache-01/), {+ target: { value: 'https://cache.example' },+ });+ const billingInput = dialog.getByLabelText(/billing-worker-01/);+ fireEvent.input(billingInput, { target: { value: 'billing admin' } });+ fireEvent.click(dialog.getByRole('button', { name: 'Save 2 links' }));++ await waitFor(() => expect(billingInput).toHaveAttribute('aria-invalid', 'true'));+ expect(billingInput).toHaveAccessibleDescription(+ 'Enter a valid URL (for example: https://198.51.100.100:8080).',+ );+ expect(updateMetadataMock).not.toHaveBeenCalled();+ });++ it('saves additions and removals, notifies the table, and closes', async () => {+ harness = renderAction({ [authId]: { id: authId, customUrl: 'https://auth.example' } });+ const dialog = openEditor();++ fireEvent.input(dialog.getByLabelText(/auth-service-01/), { target: { value: '' } });+ fireEvent.input(dialog.getByLabelText(/artifact-cache-01/), {+ target: { value: ' https://cache.example ' },+ });+ expect(dialog.getByRole('status')).toHaveTextContent('2 unsaved changes');+ fireEvent.click(dialog.getByRole('button', { name: 'Save 2 links' }));++ await waitFor(() => expect(successMock).toHaveBeenCalledWith('Saved 2 links.'));+ expect(updateMetadataMock.mock.calls).toEqual([+ [cacheId, { customUrl: 'https://cache.example' }],+ [authId, { customUrl: '' }],+ ]);+ expect(harness.events).toEqual([+ { metadataKind: 'guest', metadataId: cacheId, customUrl: 'https://cache.example' },+ { metadataKind: 'guest', metadataId: authId, customUrl: '' },+ ]);+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Edit links' })).toBeInTheDocument();+ });++ it('keeps the editor open with the failure on the row that did not save', async () => {+ updateMetadataMock.mockImplementation(async (id: string) => {+ if (id === billingId) throw new Error('Permission denied');+ return {};+ });+ harness = renderAction();+ const dialog = openEditor();++ fireEvent.input(dialog.getByLabelText(/artifact-cache-01/), {+ target: { value: 'https://cache.example' },+ });+ fireEvent.input(dialog.getByLabelText(/billing-worker-01/), {+ target: { value: 'https://billing.example' },+ });+ fireEvent.click(dialog.getByRole('button', { name: 'Save 2 links' }));++ await waitFor(() =>+ expect(dialog.getByLabelText(/billing-worker-01/)).toHaveAccessibleDescription(+ 'Permission denied',+ ),+ );+ expect(successMock).not.toHaveBeenCalled();+ expect(screen.getByRole('dialog', { name: 'Web links' })).toBeInTheDocument();+ expect(dialog.getByRole('status')).toHaveTextContent('1 unsaved change');+ expect(dialog.getByRole('button', { name: 'Save' })).toBeEnabled();+ });++ it('keeps unsaved drafts when the editor is closed and flags them on the trigger', () => {+ harness = renderAction();+ const dialog = openEditor();++ fireEvent.input(dialog.getByLabelText(/artifact-cache-01/), {+ target: { value: 'https://cache.example' },+ });+ fireEvent.click(dialog.getByRole('button', { name: 'Close web links' }));++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Edit links/ })).toHaveTextContent('(unsaved)');++ const reopened = openEditor();+ expect(reopened.getByLabelText(/artifact-cache-01/)).toHaveValue('https://cache.example');+ fireEvent.click(reopened.getByRole('button', { name: 'Discard' }));+ expect(reopened.getByLabelText(/artifact-cache-01/)).toHaveValue('');+ expect(updateMetadataMock).not.toHaveBeenCalled();+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsxindex fc3877ae3a..653bcf4fe9 100644--- a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx+++ b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx@@ -10,6 +10,7 @@ import workloadsFilterSource from '../WorkloadsFilter.tsx?raw';import workloadsWorkloadTableSource from '../WorkloadsTable.tsx?raw';import metricDisplayModeSegmentedControlSource from '../MetricDisplayModeSegmentedControl.tsx?raw';import workloadPanelSource from '../WorkloadPanel.tsx?raw';+import workloadWebLinksDialogSource from '../WorkloadWebLinksDialog.tsx?raw';import workloadTableHeaderSource from '../WorkloadTableHeader.tsx?raw';import workloadsFilterModelSource from '../workloadsFilterModel.ts?raw';import workloadsControlsStateSource from '../useWorkloadsControlsState.ts?raw';@@ -1393,7 +1394,20 @@ describe('Workloads performance contract', () => {expect(workloadsWorkloadTableSource).toContain('data-summary-clear-surface');expect(workloadsWorkloadTableSource).toContain('data-testid="workloads-table-surface"');expect(workloadsWorkloadTableSource).toContain('TableCard');- expect(workloadsWorkloadTableSource).toContain('<TableCardHeader title={props.title} />');+ expect(workloadsWorkloadTableSource).toContain(+ '<TableCardHeader title={props.title} actions={props.actions} />',+ );+ expect(workloadsSource).toContain('<WorkloadWebLinksAction');+ expect(workloadsSource).toContain('guests={state.filteredGuests}');+ expect(workloadPanelSource).toContain(+ 'getWorkloadGuestMetadataRecord(guest(), props.guestMetadata())',+ );+ // The bulk link editor must not rebuild rows on inventory ticks while closed.+ expect(workloadWebLinksDialogSource).toContain('keepStableWorkloadWebLinkRows(');+ expect(workloadWebLinksDialogSource).toMatch(+ /open\(\)\s*\?\s*keepStableWorkloadWebLinkRows\(/,+ );+ expect(workloadWebLinksDialogSource).toContain(': previous,');expect(workloadsSource).toContain('<TableCardHeader title={props.tableTitle} />');expect(workloadsSource).toContain('title={props.tableTitle}');expect(workloadsWorkloadTableSource).toContain(diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadWebLinksModel.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadWebLinksModel.test.tsnew file mode 100644index 0000000000..11a19ac9a2--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/workloadWebLinksModel.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from 'vitest';+import type { WorkloadGuest } from '@/types/workloads';+import { getWorkloadMetadataId } from '@/utils/workloads';+import {+ buildWorkloadWebLinkRows,+ filterWorkloadWebLinkRows,+ getWorkloadGuestMetadataRecord,+ getWorkloadWebLinkChanges,+ getWorkloadWebLinkPlaceholder,+ keepStableWorkloadWebLinkRows,+ validateWorkloadWebLinkChanges,+} from '../workloadWebLinksModel';++const makeGuest = (overrides: Partial<WorkloadGuest> = {}): WorkloadGuest =>+ ({+ id: 'inst1-node1-100',+ vmid: 100,+ name: 'test-vm',+ node: 'node1',+ instance: 'inst1',+ status: 'running',+ type: 'qemu',+ ...overrides,+ }) as WorkloadGuest;++describe('workloadWebLinksModel', () => {+ it('reads stable metadata first and falls back to the legacy instance:node:vmid key', () => {+ const guest = makeGuest();+ const stableId = getWorkloadMetadataId(guest);++ expect(+ getWorkloadGuestMetadataRecord(guest, {+ 'inst1:node1:100': { id: 'inst1:node1:100', customUrl: 'https://legacy.example' },+ })?.customUrl,+ ).toBe('https://legacy.example');+ expect(+ getWorkloadGuestMetadataRecord(guest, {+ 'inst1:node1:100': { id: 'inst1:node1:100', customUrl: 'https://legacy.example' },+ [stableId]: { id: stableId, customUrl: 'https://stable.example' },+ })?.customUrl,+ ).toBe('https://stable.example');+ });++ it('builds name-sorted rows keyed by the save identity with type, ID and node detail', () => {+ const alpha = makeGuest({+ id: 'a',+ vmid: 101,+ name: 'alpha-10',+ ipAddresses: ['', '10.0.0.5'],+ });+ const beta = makeGuest({ id: 'b', vmid: 102, name: 'alpha-9', type: 'lxc', node: 'node2' });+ const rows = buildWorkloadWebLinkRows([alpha, beta, alpha], {+ [getWorkloadMetadataId(alpha)]: {+ id: getWorkloadMetadataId(alpha),+ customUrl: ' https://alpha.example ',+ },+ });++ expect(rows.map((row) => row.name)).toEqual(['alpha-9', 'alpha-10']);+ expect(rows[1]).toMatchObject({+ metadataId: getWorkloadMetadataId(alpha),+ savedUrl: 'https://alpha.example',+ addressHint: '10.0.0.5',+ });+ expect(rows[1].detail).toContain('101');+ expect(rows[1].detail).toContain('node1');+ expect(rows[0].detail).toContain('node2');+ expect(rows[0].savedUrl).toBe('');+ });++ it('reports only real changes, treating an emptied field as a removal', () => {+ const rows = buildWorkloadWebLinkRows(+ [makeGuest({ id: 'a', name: 'a', vmid: 1 }), makeGuest({ id: 'b', name: 'b', vmid: 2 })],+ {},+ );+ const [a, b] = rows;+ const withSaved = [{ ...a, savedUrl: 'https://a.example' }, b];++ expect(+ getWorkloadWebLinkChanges(withSaved, {+ [a.metadataId]: ' https://a.example ',+ [b.metadataId]: '',+ }),+ ).toEqual([]);+ expect(+ getWorkloadWebLinkChanges(withSaved, {+ [a.metadataId]: '',+ [b.metadataId]: ' https://b.example',+ }),+ ).toEqual([+ { metadataId: a.metadataId, name: 'a', url: '' },+ { metadataId: b.metadataId, name: 'b', url: 'https://b.example' },+ ]);+ });++ it('validates added links with the shared web-interface rules but never blocks a removal', () => {+ expect(+ validateWorkloadWebLinkChanges([+ { metadataId: 'ok', name: 'ok', url: 'http://10.0.0.5:8080' },+ { metadataId: 'bad', name: 'bad', url: 'admin page' },+ { metadataId: 'ftp', name: 'ftp', url: 'ftp://files.example' },+ { metadataId: 'gone', name: 'gone', url: '' },+ ]),+ ).toEqual({+ bad: 'Enter a valid URL (for example: https://198.51.100.100:8080).',+ ftp: 'URL must start with http:// or https://.',+ });+ });++ it('filters to guests without a saved link, ignoring unsaved drafts', () => {+ const rows = buildWorkloadWebLinkRows(+ [makeGuest({ id: 'a', name: 'a', vmid: 1 }), makeGuest({ id: 'b', name: 'b', vmid: 2 })],+ {},+ );+ const withSaved = [{ ...rows[0], savedUrl: 'https://a.example' }, rows[1]];++ expect(filterWorkloadWebLinkRows(withSaved, 'missing').map((row) => row.name)).toEqual(['b']);+ expect(filterWorkloadWebLinkRows(withSaved, 'all')).toHaveLength(2);+ });++ it('keeps unchanged row objects across inventory ticks so inputs are not remounted', () => {+ const guest = makeGuest({ ipAddresses: ['10.0.0.5'] });+ const first = buildWorkloadWebLinkRows([guest], {});+ const tick = buildWorkloadWebLinkRows([{ ...guest, cpu: 0.9 } as WorkloadGuest], {});++ expect(tick[0]).not.toBe(first[0]);+ expect(keepStableWorkloadWebLinkRows(first, tick)).toBe(first);++ const renamed = buildWorkloadWebLinkRows([{ ...guest, name: 'renamed' }], {});+ const merged = keepStableWorkloadWebLinkRows(first, renamed);+ expect(merged).not.toBe(first);+ expect(merged[0].name).toBe('renamed');+ });++ it('suggests the guest address as a placeholder, bracketing IPv6', () => {+ const [row] = buildWorkloadWebLinkRows([makeGuest()], {});++ expect(getWorkloadWebLinkPlaceholder(row)).toBe('https://');+ expect(getWorkloadWebLinkPlaceholder({ ...row, addressHint: '10.0.0.5' })).toBe(+ 'http://10.0.0.5',+ );+ expect(getWorkloadWebLinkPlaceholder({ ...row, addressHint: 'fd00::5' })).toBe(+ 'http://[fd00::5]',+ );+ });+});diff --git a/frontend-modern/src/components/Workloads/workloadWebLinksModel.ts b/frontend-modern/src/components/Workloads/workloadWebLinksModel.tsnew file mode 100644index 0000000000..4d48792b00--- /dev/null+++ b/frontend-modern/src/components/Workloads/workloadWebLinksModel.ts@@ -0,0 +1,148 @@+import type { GuestMetadata } from '@/api/guestMetadata';+import {+ normalizeWebInterfaceUrl,+ validateWebInterfaceCustomUrl,+} from '@/components/shared/webInterfaceUrlFieldModel';+import type { WorkloadGuest } from '@/types/workloads';+import { getWorkloadTypeLabel } from '@/utils/workloadTypePresentation';+import {+ getWorkloadMetadataId,+ getWorkloadMetadataIdCandidates,+ resolveWorkloadType,+} from '@/utils/workloads';+import { getWorkloadDisplayId } from './guestRowModel';++export type WorkloadGuestMetadataMap = Record<string, GuestMetadata>;++/**+ * Saved metadata for a workload row. Stable identities win over the legacy+ * instance:node:vmid key that v5 data volumes still carry.+ */+export const getWorkloadGuestMetadataRecord = (+ guest: WorkloadGuest,+ byId: WorkloadGuestMetadataMap,+): GuestMetadata | undefined => {+ for (const metadataId of getWorkloadMetadataIdCandidates(guest)) {+ if (metadataId && byId[metadataId]) {+ return byId[metadataId];+ }+ }+ return byId[`${guest.instance}:${guest.node}:${guest.vmid}`];+};++export type WorkloadWebLinkFilter = 'all' | 'missing';++export interface WorkloadWebLinkRow {+ metadataId: string;+ name: string;+ detail: string;+ status: string;+ addressHint: string;+ savedUrl: string;+}++/** Draft URLs keyed by metadata ID; an empty string means remove the link. */+export type WorkloadWebLinkDrafts = Record<string, string>;++export interface WorkloadWebLinkChange {+ metadataId: string;+ name: string;+ url: string;+}++const getWorkloadWebLinkDetail = (guest: WorkloadGuest): string =>+ [getWorkloadTypeLabel(resolveWorkloadType(guest)), getWorkloadDisplayId(guest), guest.node]+ .map((part) => (part === undefined || part === null ? '' : String(part).trim()))+ .filter(Boolean)+ .join(' · ');++export const buildWorkloadWebLinkRows = (+ guests: readonly WorkloadGuest[],+ byId: WorkloadGuestMetadataMap,+): WorkloadWebLinkRow[] => {+ const rows: WorkloadWebLinkRow[] = [];+ const seen = new Set<string>();+ for (const guest of guests) {+ const metadataId = getWorkloadMetadataId(guest);+ if (!metadataId || seen.has(metadataId)) continue;+ seen.add(metadataId);+ rows.push({+ metadataId,+ name: guest.name,+ detail: getWorkloadWebLinkDetail(guest),+ status: guest.status,+ addressHint: guest.ipAddresses?.find((address) => address.trim())?.trim() ?? '',+ savedUrl: normalizeWebInterfaceUrl(getWorkloadGuestMetadataRecord(guest, byId)?.customUrl),+ });+ }+ return rows.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));+};++const sameWorkloadWebLinkRow = (a: WorkloadWebLinkRow, b: WorkloadWebLinkRow): boolean =>+ a.metadataId === b.metadataId &&+ a.name === b.name &&+ a.detail === b.detail &&+ a.status === b.status &&+ a.addressHint === b.addressHint &&+ a.savedUrl === b.savedUrl;++/**+ * Keeps unchanged row objects across live inventory ticks so keyed list+ * rendering does not remount an input while someone is typing in it.+ */+export const keepStableWorkloadWebLinkRows = (+ previous: readonly WorkloadWebLinkRow[],+ next: WorkloadWebLinkRow[],+): WorkloadWebLinkRow[] => {+ if (previous.length === 0) return next;+ const previousById = new Map(previous.map((row) => [row.metadataId, row]));+ const merged = next.map((row) => {+ const prior = previousById.get(row.metadataId);+ return prior && sameWorkloadWebLinkRow(prior, row) ? prior : row;+ });+ const unchanged =+ merged.length === previous.length && merged.every((row, index) => row === previous[index]);+ return unchanged ? (previous as WorkloadWebLinkRow[]) : merged;+};++export const filterWorkloadWebLinkRows = (+ rows: readonly WorkloadWebLinkRow[],+ filter: WorkloadWebLinkFilter,+): WorkloadWebLinkRow[] => (filter === 'missing' ? rows.filter((row) => !row.savedUrl) : [...rows]);++export const getWorkloadWebLinkValue = (+ row: WorkloadWebLinkRow,+ drafts: WorkloadWebLinkDrafts,+): string => drafts[row.metadataId] ?? row.savedUrl;++export const getWorkloadWebLinkChanges = (+ rows: readonly WorkloadWebLinkRow[],+ drafts: WorkloadWebLinkDrafts,+): WorkloadWebLinkChange[] =>+ rows.flatMap((row) => {+ const draft = drafts[row.metadataId];+ if (draft === undefined) return [];+ const url = normalizeWebInterfaceUrl(draft);+ return url === row.savedUrl ? [] : [{ metadataId: row.metadataId, name: row.name, url }];+ });++/** Validation errors keyed by metadata ID. Removing a link is always valid. */+export const validateWorkloadWebLinkChanges = (+ changes: readonly WorkloadWebLinkChange[],+): Record<string, string> => {+ const errors: Record<string, string> = {};+ for (const change of changes) {+ const error = change.url ? validateWebInterfaceCustomUrl(change.url) : null;+ if (error) errors[change.metadataId] = error;+ }+ return errors;+};++export const getWorkloadWebLinkPlaceholder = (row: WorkloadWebLinkRow): string => {+ if (!row.addressHint) return 'https://';+ const host = row.addressHint.includes(':') ? `[${row.addressHint}]` : row.addressHint;+ return `http://${host}`;+};++export const formatWorkloadWebLinkCount = (count: number): string =>+ `${count} ${count === 1 ? 'link' : 'links'}`;