Messages endpoint (#13247)

* Adds /api/status/ endpoint for admin-facing system messages

* update alerts menu

* right-align badges

* Rename SERVER_RESTART_REQUIRED to _SERVER_RESTART_REQUIRED

* Adjust API endpoint

- Move to /api/system/status/
- Make messages a sub-list
- Remove "system_state" from /api/

* move staff-only messages to new endpoint (and adjust UI accordingly)

* system dialogs staff only

* Reduce scope and revert most changes

* ignore reports in frontend

* clean up blob

---------

Co-authored-by: Matthias Mair <code@mjmair.com>
This commit is contained in:
OliverandMatthias Mair authored and GitHub committed 2026-11-12 11:14:01 +11:00
1 parent a0ec8e4c71
commit af5055b33e
11 files changed
+742 -157

No files matched your search

+2
View File
@@ -30,6 +30,8 @@ dist-ssr
/.nyc_output/
/coverage/
/flakiness-report/
/report/
/blob-report/
# Report generation
stats.html
+1
View File
@@ -57,6 +57,7 @@ export enum ApiEndpoints {
settings_global_list = 'settings/global/',
settings_user_list = 'settings/user/',
news = 'news/',
system_messages = 'system/messages/',
global_status = 'generic/status/',
custom_state_list = 'generic/status/custom/',
version = 'version/',
+69 -100
View File
@@ -1,56 +1,67 @@
import { ActionIcon, Alert, Group, Menu, Stack, Tooltip } from '@mantine/core';
import { IconCircleCheck, IconExclamationCircle } from '@tabler/icons-react';
import {
ActionIcon,
Alert,
Group,
Menu,
Stack,
Text,
Tooltip
} from '@mantine/core';
import {
IconAlertTriangle,
IconArrowRight,
IconCircleCheck,
IconExclamationCircle,
IconInfoCircle,
IconListDetails
} from '@tabler/icons-react';
import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import type { SettingsStateProps } from '@lib/types/Settings';
import { t } from '@lingui/core/macro';
import { useShallow } from 'zustand/react/shallow';
import { docLinks } from '../../defaults/links';
import { useServerApiState } from '../../states/ServerApiState';
import { useGlobalSettingsState } from '../../states/SettingsStates';
import { useUserState } from '../../states/UserState';
import type { ServerAPIProps } from '../../states/states';
interface AlertInfo {
key: string;
title: string;
code?: string;
message: string;
error?: boolean;
}
import {
ACTIONABLE_CLASSIFIERS,
type AdminMessage,
type AdminMessageClassifier,
classifierColor,
useAdminMessages
} from '../../hooks/UseAdminMessages';
/**
* The `Alerts` component displays a menu of alerts for staff users based on the server state
* and global settings. Alerts are shown as a dropdown menu with actionable items that can be dismissed.
* The `Alerts` component displays a menu of alerts for staff users, based on the
* system messages provided by the server (via the /api/system/messages/ endpoint).
*
* Only actionable messages (errors and warnings) are displayed here.
* Dismissed alerts are filtered out and will not reappear in the current session.
*
* @returns A dropdown menu of alerts for staff users or `null` if there are no alerts or the user is not a staff member.
*/
export function Alerts() {
const user = useUserState();
const [server] = useServerApiState(useShallow((state) => [state.server]));
const globalSettings = useGlobalSettingsState();
const { messages } = useAdminMessages();
const [dismissed, setDismissed] = useState<string[]>([]);
const alerts: ExtendedAlertInfo[] = useMemo(
const alerts: AdminMessage[] = useMemo(
() =>
getAlerts(server, globalSettings).filter(
(alert) => !dismissed.includes(alert.key)
messages.filter(
(msg) =>
ACTIONABLE_CLASSIFIERS.includes(msg.classifier) &&
!dismissed.includes(msg.key)
),
[server, dismissed, globalSettings]
[messages, dismissed]
);
const anyErrors: boolean = useMemo(
() => alerts.some((alert) => alert.error),
() => alerts.some((alert) => alert.classifier === 'error'),
[alerts]
);
function closeAlert(key: string) {
setDismissed([...dismissed, key]);
}
if (user.isStaff() && alerts.length > 0)
if (alerts.length > 0)
return (
<Menu withinPortal={true} position='bottom-end'>
<Menu.Target>
@@ -70,21 +81,47 @@ export function Alerts() {
<ServerAlert alert={alert} closeAlert={closeAlert} />
</Menu.Item>
))}
<Menu.Divider />
<Menu.Item
component={Link}
to='/settings/admin/home'
aria-label='alerts-view-all'
leftSection={<IconListDetails size={16} />}
rightSection={<IconArrowRight size={16} />}
>
<Text size='md'>{t`View all messages`}</Text>
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
return null;
}
function classifierIcon(classifier: AdminMessageClassifier) {
switch (classifier) {
case 'error':
return <IconExclamationCircle />;
case 'warning':
return <IconAlertTriangle />;
case 'info':
return <IconInfoCircle />;
case 'success':
default:
return <IconCircleCheck />;
}
}
export function ServerAlert({
alert,
closeAlert
}: { alert: ExtendedAlertInfo; closeAlert?: (key: string) => void }) {
}: { alert: AdminMessage; closeAlert?: (key: string) => void }) {
const actionable = ACTIONABLE_CLASSIFIERS.includes(alert.classifier);
return (
<Alert
withCloseButton={!!closeAlert}
color={alert.condition ? (alert.error ? 'red' : 'orange') : 'green'}
icon={alert.condition ? <IconExclamationCircle /> : <IconCircleCheck />}
color={classifierColor(alert.classifier)}
icon={classifierIcon(alert.classifier)}
title={
<Group gap='xs'>
{alert.code && `${alert.code}: `}
@@ -94,81 +131,13 @@ export function ServerAlert({
onClose={closeAlert ? () => closeAlert(alert.key) : undefined}
>
<Stack gap='xs'>
{!alert.condition && t`No issues detected`}
{alert.condition && alert.message}
{alert.condition && alert.code && errorCodeLink(alert.code)}
{alert.message}
{actionable && alert.code && errorCodeLink(alert.code)}
</Stack>
</Alert>
);
}
export type ExtendedAlertInfo = AlertInfo & {
condition: boolean;
};
export function getAlerts(
server: ServerAPIProps,
globalSettings: SettingsStateProps,
inactive = false
): ExtendedAlertInfo[] {
const n_migrations =
Number.parseInt(globalSettings.getSetting('_PENDING_MIGRATIONS')) ?? 0;
const allAlerts: ExtendedAlertInfo[] = [
{
key: 'debug',
title: t`Debug Mode`,
code: 'INVE-W4',
message: t`The server is running in debug mode.`,
condition: server?.debug_mode || false
},
{
key: 'worker',
title: t`Background Worker`,
code: 'INVE-W5',
message: t`The background worker process is not running.`,
condition: !server?.worker_running
},
{
key: 'restart',
title: t`Server Restart`,
code: 'INVE-W6',
message: t`The server requires a restart to apply changes.`,
condition: globalSettings.isSet('SERVER_RESTART_REQUIRED')
},
{
key: 'email',
title: t`Email settings`,
code: 'INVE-W7',
message: t`Email settings not configured.`,
condition: !server?.email_configured
},
{
key: 'migrations',
title: t`Database Migrations`,
code: 'INVE-W8',
message: t`There are pending database migrations.`,
condition: n_migrations > 0
},
{
key: 'cors',
title: t`CORS Settings`,
code: 'INVE-W16',
message: t`CORS is set to allow all origins.`,
condition: server?.system_state?.cors_allow_all || false
},
{
key: 'basic_auth',
title: t`Basic Authentication`,
code: 'INVE-W18',
message: t`Basic (username:password) authentication is enabled for the API.`,
condition: server?.system_state?.basic_auth_enabled || false
}
];
return allAlerts.filter((alert) => inactive || alert.condition);
}
export function errorCodeLink(code: string) {
return (
<a
@@ -0,0 +1,94 @@
import { ApiEndpoints } from '@lib/enums/ApiEndpoints';
import { apiUrl } from '@lib/functions/Api';
import { t } from '@lingui/core/macro';
import { useQuery } from '@tanstack/react-query';
import { api } from '../App';
import { useUserState } from '../states/UserState';
export type AdminMessageClassifier = 'error' | 'warning' | 'info' | 'success';
/**
* A staff-only system message, as returned in the `messages` array of the /api/system/messages/ endpoint.
*/
export interface AdminMessage {
key: string;
title: string;
message: string;
classifier: AdminMessageClassifier;
code?: string | null;
plugin?: string | null;
}
/** Response format of the /api/system/messages/ endpoint */
export interface AdminMessageResponse {
messages: AdminMessage[];
}
/** All classifiers, ordered most severe first */
export const ADMIN_MESSAGE_CLASSIFIERS: AdminMessageClassifier[] = [
'error',
'warning',
'info',
'success'
];
/** Classifiers which indicate that the administrator should take action */
export const ACTIONABLE_CLASSIFIERS: AdminMessageClassifier[] = [
'error',
'warning'
];
export function classifierColor(classifier: AdminMessageClassifier): string {
switch (classifier) {
case 'error':
return 'red';
case 'warning':
return 'orange';
case 'info':
return 'blue';
case 'success':
default:
return 'green';
}
}
export function classifierLabel(classifier: AdminMessageClassifier): string {
switch (classifier) {
case 'error':
return t`Error`;
case 'warning':
return t`Warning`;
case 'info':
return t`Info`;
case 'success':
default:
return t`Success`;
}
}
/**
* Fetch the list of staff-only system messages from the server.
* The query is only enabled for staff users (the endpoint is staff-only),
* so `messages` is always empty for non-staff users.
*/
export function useAdminMessages() {
const user = useUserState();
const isStaff = user.isStaff();
const query = useQuery<AdminMessageResponse | null>({
enabled: isStaff,
queryKey: ['admin-messages', user.userId()],
// System state changes infrequently, and checks may hit the database
staleTime: 60 * 1000,
refetchOnWindowFocus: false,
queryFn: async () =>
api
.get(apiUrl(ApiEndpoints.system_messages))
.then((response) => response.data ?? null)
});
return {
...query,
messages: isStaff ? (query.data?.messages ?? []) : []
};
}
@@ -1,43 +1,146 @@
import { StylishText } from '@lib/components/StylishText';
import { t } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
import { Accordion, SimpleGrid, Stack } from '@mantine/core';
import { type JSX, useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
import {
type ExtendedAlertInfo,
ServerAlert,
getAlerts
} from '../../../../components/nav/Alerts';
Accordion,
Alert,
Badge,
Chip,
Divider,
Group,
Loader,
SimpleGrid,
Stack,
Text
} from '@mantine/core';
import { useLocalStorage } from '@mantine/hooks';
import { type JSX, useMemo } from 'react';
import { ServerAlert } from '../../../../components/nav/Alerts';
import { QuickAction } from '../../../../components/settings/QuickAction';
import { useServerApiState } from '../../../../states/ServerApiState';
import { useGlobalSettingsState } from '../../../../states/SettingsStates';
import {
ADMIN_MESSAGE_CLASSIFIERS,
type AdminMessageClassifier,
classifierColor,
classifierLabel,
useAdminMessages
} from '../../../../hooks/UseAdminMessages';
function rankAlert(alert: ExtendedAlertInfo): number {
if (!alert.condition) return 0;
if (alert.error) return 2;
// Passing checks ('success') are hidden by default, to highlight actionable messages
const DEFAULT_VISIBLE_CLASSIFIERS: AdminMessageClassifier[] =
ADMIN_MESSAGE_CLASSIFIERS.filter((c) => c !== 'success');
return 1;
/**
* Selector allowing the user to toggle display of each message classifier.
*/
function ClassifierSelector({
selected,
onChange,
counts
}: Readonly<{
selected: AdminMessageClassifier[];
onChange: (value: AdminMessageClassifier[]) => void;
counts: Record<AdminMessageClassifier, number>;
}>): JSX.Element {
return (
<Chip.Group
multiple
value={selected}
onChange={(value) => onChange(value as AdminMessageClassifier[])}
>
<Group gap='xs' aria-label='admin-message-classifier-selector'>
{ADMIN_MESSAGE_CLASSIFIERS.map((classifier) => (
<Chip
key={classifier}
value={classifier}
color={classifierColor(classifier)}
size='sm'
aria-label={`admin-message-classifier-${classifier}`}
>
{classifierLabel(classifier)}
<Badge
ml={6}
size='xs'
color={
counts[classifier] > 0 ? classifierColor(classifier) : 'gray'
}
variant={counts[classifier] > 0 ? 'white' : 'light'}
aria-label={`admin-message-count-${classifier}`}
>
{counts[classifier]}
</Badge>
</Chip>
))}
</Group>
</Chip.Group>
);
}
function SystemMessages(): JSX.Element {
const { messages, isFetching, isError } = useAdminMessages();
const [selected, setSelected] = useLocalStorage<AdminMessageClassifier[]>({
key: 'admin-center-message-classifiers',
defaultValue: DEFAULT_VISIBLE_CLASSIFIERS
});
const counts = useMemo(() => {
const result = Object.fromEntries(
ADMIN_MESSAGE_CLASSIFIERS.map((c) => [c, 0])
) as Record<AdminMessageClassifier, number>;
messages.forEach((msg) => {
if (msg.classifier in result) result[msg.classifier] += 1;
});
return result;
}, [messages]);
// Server returns messages sorted by severity
const visible = useMemo(
() => messages.filter((msg) => selected.includes(msg.classifier)),
[messages, selected]
);
return (
<Stack gap='sm'>
<Group justify='flex-end' gap='sm'>
{isFetching && <Loader size='xs' />}
<ClassifierSelector
selected={selected}
onChange={setSelected}
counts={counts}
/>
</Group>
<Divider />
{isError && (
<Alert color='red' title={t`Error`}>
{t`Failed to load system messages`}
</Alert>
)}
{!isError && !isFetching && visible.length === 0 && (
<Text size='sm' c='dimmed'>
{t`No messages to display`}
</Text>
)}
<SimpleGrid
cols={{
base: 1,
'600px': 2,
'1200px': 3
}}
type='container'
spacing='sm'
aria-label='admin-message-list'
>
{visible.map((msg) => (
<ServerAlert key={msg.key} alert={msg} />
))}
</SimpleGrid>
</Stack>
);
}
export default function HomePanel(): JSX.Element {
const [server] = useServerApiState(useShallow((state) => [state.server]));
const globalSettings = useGlobalSettingsState();
const accElements = useMemo(() => {
const _alerts = getAlerts(server, globalSettings, true).sort(
(a, b) => rankAlert(b) - rankAlert(a)
);
return [
{
key: 'system-status',
text: t`System Status`,
elements: _alerts
}
];
}, [server, globalSettings]);
return (
<Stack gap='xs'>
<Accordion
@@ -55,31 +158,16 @@ export default function HomePanel(): JSX.Element {
<QuickAction />
</Accordion.Panel>
</Accordion.Item>
{accElements.map(
(item) =>
item.elements.length > 0 && (
<Accordion.Item key={item.key} value={item.key}>
<Accordion.Control>
<StylishText size='md'>{item.text}</StylishText>
</Accordion.Control>
<Accordion.Panel>
<SimpleGrid
cols={{
base: 1,
'600px': 2,
'1200px': 3
}}
type='container'
spacing='sm'
>
{item.elements.map((alert) => (
<ServerAlert alert={alert} />
))}
</SimpleGrid>
</Accordion.Panel>
</Accordion.Item>
)
)}
<Accordion.Item value='system-status'>
<Accordion.Control>
<StylishText size='md'>
<Trans>System Status</Trans>
</StylishText>
</Accordion.Control>
<Accordion.Panel>
<SystemMessages />
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
+77
View File
@@ -350,6 +350,83 @@ test('Settings - Admin', async ({ browser }) => {
await page.getByRole('button', { name: 'Submit' }).click();
});
test('Settings - Admin - System Status', async ({ browser }) => {
const page = await doCachedLogin(browser, {
user: adminuser,
url: 'settings/admin/home'
});
// Messages are loaded from the server (/api/system/messages/ endpoint)
await page.getByText('System Status').waitFor();
await page.getByLabel('admin-message-classifier-selector').waitFor();
const messages = page.getByLabel('admin-message-list').getByRole('alert');
await messages.filter({ hasText: 'Basic Authentication' }).waitFor();
const classifiers = ['error', 'warning', 'info', 'success'];
// Each classifier chip displays its message count as a badge
for (const c of classifiers) {
await expect(page.getByLabel(`admin-message-count-${c}`)).toHaveText(
/^\d+$/
);
}
// Toggle a classifier chip (the native checkbox input is visually hidden)
const toggle = async (c: string, checked: boolean) => {
const chip = page.getByLabel(`admin-message-classifier-${c}`);
await chip.dispatchEvent('click');
if (checked) await expect(chip).toBeChecked();
else await expect(chip).not.toBeChecked();
};
const count = async (c: string) =>
Number(await page.getByLabel(`admin-message-count-${c}`).textContent());
// Success messages are hidden by default
await expect(
page.getByLabel('admin-message-classifier-success')
).not.toBeChecked();
await expect(messages.filter({ hasText: 'No issues detected' })).toHaveCount(
0
);
const actionable = await messages.count();
const successCount = await count('success');
const total = actionable + successCount;
expect(total).toBeGreaterThanOrEqual(7);
// Show success messages
await toggle('success', true);
await expect(messages).toHaveCount(total);
// Hide all classifiers
for (const c of classifiers) {
await toggle(c, false);
}
await page.getByText('No messages to display').waitFor();
await expect(messages).toHaveCount(0);
// Restore the default selection
for (const c of ['error', 'warning', 'info']) {
await toggle(c, true);
}
await expect(messages).toHaveCount(actionable);
});
test('Settings - Admin - Alerts View All', async ({ browser }) => {
const page = await doCachedLogin(browser, { user: adminuser });
// Navbar alerts dropdown links through to the admin center
await page.getByLabel('open-alerts').click();
const viewAll = page.getByLabel('alerts-view-all');
await expect(viewAll).toHaveAttribute('href', /\/settings\/admin\/home$/);
await viewAll.click();
await page.waitForURL('**/settings/admin/home**');
await page.getByLabel('admin-message-classifier-selector').waitFor();
});
test('Settings - Admin - Background Tasks', async ({ browser }) => {
const page = await doCachedLogin(browser, {
user: adminuser,