Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ jobs:
- name: Run regression test suite
run: npm test

- name: Admin StrictMode tests (React 18)
run: npm run test:admin

- name: Type checks
run: |
npm run test:ts:front
Expand Down Expand Up @@ -81,6 +84,38 @@ jobs:
test -f README.md
test -f LICENSE

react-19:
# Informational: the peer range is React ^18, like the Strapi 5 admin, and stays so. This job
# runs the admin StrictMode tests against React 19 (RFC strapi/strapi#25739) to see problems
# before Strapi moves; a failure here does not block a pull request.
name: Admin StrictMode tests on React 19 (informational)
runs-on: ubuntu-latest
timeout-minutes: 20
continue-on-error: true
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
cache: npm

- name: Install dependencies
run: npm ci --legacy-peer-deps

- name: Install React 19 (not saved)
run: npm install --no-save --legacy-peer-deps --ignore-scripts react@19 react-dom@19

- name: Show installed React version
run: node -p "'react ' + require('react/package.json').version + ', react-dom ' + require('react-dom/package.json').version"

- name: Admin StrictMode tests (React 19)
run: npm run test:admin

multi-process:
name: Multi-process coordination (SQLite + PostgreSQL)
runs-on: ubuntu-latest
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
## [Unreleased]

### Fixed

* The Online users widget, the Analytics page and the Configuration page no longer show "could not be loaded" after the component is mounted a second time. `useFetchClient` aborts the requests of an unmounted component; the widget and the Analytics page then skipped their next load because the aborted one still counted as running, and the Configuration page set the error of the aborted load after the next load had started. React StrictMode mounts every component twice in development, and React 19 and a future StrictMode admin do the same. Each load now belongs to one mount: an aborted or outdated load sets no state.

### Tests

* `npm run test:admin`: StrictMode tests for every admin entry point (no duplicate requests, no leaked timers, listeners, connections or observers after unmount, no console errors or warnings), also run against React 19 in an informational CI job.

## [4.14.1](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.14.0...v4.14.1) (2026-11-18)


Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,7 @@ Version 4.0.0 moved to Strapi 5 and its Document Service API. Upgrade Strapi its
```bash
npm ci --legacy-peer-deps
npm test # node --test tests/*.test.js tests/*.test.mjs
npm run test:admin # admin entry points in React.StrictMode (jsdom, fake network)
npm run test:concurrency # 8 processes on one database (SQLite; PostgreSQL with MSM_TEST_PG_URL)
npm run test:ts:front
npm run test:ts:back
Expand All @@ -968,6 +969,8 @@ npm run verify
npm run verify:runtime
```

`npm run test:admin` renders every admin entry point (the session dashboard and the admin panel sessions view with their dialogs, the Configuration and Analytics settings pages, the Online users widget and the Content Manager side panel) inside `React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, connection or observer left after unmount, and any console error or warning. A separate CI job runs the same tests against React 19 for information only: the plugin's peer range is React 18, like the Strapi 5 admin.

HTTP integration tests need Strapi host dependencies: set `SESSION_HTTP_STRAPI_NODE_MODULES` to the `node_modules` of a Strapi 5 host; without it they skip with a message. This repository's own `node_modules` works (its devDependencies include Strapi 5.62 and Users & Permissions), which is what CI uses:

```bash
Expand All @@ -990,7 +993,7 @@ Releases use Conventional Commits and semantic-release on Node.js 22 with npm Tr
Issues and pull requests are welcome.

- Bugs and feature ideas: [open an issue](https://github.com/Schero94/Magic-Sessionmanager/issues/new/choose) (templates included). Questions: [Discussions](https://github.com/Schero94/Magic-Sessionmanager/discussions).
- Pull requests: branch from `main`, write a failing test first, and use Conventional Commits (`fix:`, `feat:`, `docs:`; a breaking change needs a `BREAKING CHANGE:` footer). Before you push, run `npm run lint`, `npm run format:check`, `npm test`, both type checks and `npm run build && npm run verify`.
- Pull requests: branch from `main`, write a failing test first, and use Conventional Commits (`fix:`, `feat:`, `docs:`; a breaking change needs a `BREAKING CHANGE:` footer). Before you push, run `npm run lint`, `npm run format:check`, `npm test`, `npm run test:admin`, both type checks and `npm run build && npm run verify`.
- Use synthetic data only in tests, screenshots and issues: `*.example.test` addresses and IP addresses from `203.0.113.0/24`. Never paste real tokens.

---
Expand Down
27 changes: 21 additions & 6 deletions admin/src/components/OnlineUsersWidget.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ const OnlineUsersWidget = () => {
const [userCounts, setUserCounts] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const requestInProgress = useRef(false);
// The running load (an object per call) or null. One load at a time.
const requestInProgress = useRef(null);

/**
* Loads the count-only session statistics and user totals in parallel
Expand All @@ -232,19 +233,28 @@ const OnlineUsersWidget = () => {
* The loading state starts as true and "Try again" sets it before calling,
* so this function only clears it.
*
* The effect cleanup forgets the running load (useFetchClient aborts its
* requests on unmount). A load that is no longer current sets no state, and
* the next mount starts its own load instead of waiting for the aborted one:
* React StrictMode mounts, unmounts and mounts again, and before this the
* widget stayed on "Online users could not be loaded." after that remount.
*
* @param {{showLoading?: boolean}} [options] Whether this load owns the loading and error state.
* @returns {Promise<void>}
*/
const fetchStats = useCallback(
async ({ showLoading = true } = {}) => {
if (requestInProgress.current) return;
requestInProgress.current = true;
const request = {};
requestInProgress.current = request;
const isCurrent = () => requestInProgress.current === request;

try {
const [sessionResult, countResult] = await Promise.allSettled([
get('/magic-sessionmanager/sessions/stats'),
get('/magic-sessionmanager/users/stats'),
]);
if (!isCurrent()) return;
if (sessionResult.status === 'rejected') throw sessionResult.reason;
setStats(widgetStatsFromCounts(sessionResult.value?.data));
setLoadError(false);
Expand All @@ -262,12 +272,14 @@ const OnlineUsersWidget = () => {
}
} catch (error) {
// A request aborted because the widget unmounted is not a failure.
if (isCancelledRequest(error)) return;
if (!isCurrent() || isCancelledRequest(error)) return;
logSafeAdminError('onlineUsers.loadSessions', error);
if (showLoading) setLoadError(true);
} finally {
if (showLoading) setLoading(false);
requestInProgress.current = false;
if (isCurrent()) {
if (showLoading) setLoading(false);
requestInProgress.current = null;
}
}
},
[get]
Expand All @@ -279,7 +291,10 @@ const OnlineUsersWidget = () => {
const interval = setInterval(() => {
void fetchStats({ showLoading: false });
}, REFRESH_INTERVAL_MS);
return () => clearInterval(interval);
return () => {
clearInterval(interval);
requestInProgress.current = null;
};
}, [fetchStats]);

if (loading) {
Expand Down
28 changes: 22 additions & 6 deletions admin/src/pages/Analytics.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { PageShell, SectionCard, StatGrid, StatCard, EqualGrid } from '../compon
import Alert from '../components/PersistentAlert';
import ReadableText from '../components/ReadableText';
import { getTranslation } from '../utils/getTranslation';
import { logSafeAdminError } from '../utils/safeAdminLog.mjs';
import { isCancelledRequest, logSafeAdminError } from '../utils/safeAdminLog.mjs';

// ================ BAR LIST ================
// Label, track and count are three grid cells. The count never overlaps the
Expand Down Expand Up @@ -159,7 +159,8 @@ const AnalyticsPage = () => {
const [updatedAt, setUpdatedAt] = useState(null);
const [loadError, setLoadError] = useState(false);
const [forbidden, setForbidden] = useState(false);
const requestPendingRef = useRef(false);
// The running load (an object per call) or null. One load at a time.
const requestPendingRef = useRef(null);

/**
* Loads the aggregates over every session (computed on the server, no row
Expand All @@ -169,24 +170,36 @@ const AnalyticsPage = () => {
* above it. Failures are logged without response data. `get` is stable, so
* the callback is created once.
*
* The effect cleanup forgets the running load (useFetchClient aborts its
* requests on unmount). A load that is no longer current sets no state, and
* the next mount starts its own load: React StrictMode mounts, unmounts and
* mounts again, and before this the page showed "Analytics could not be
* loaded." for the aborted first load and skipped the second.
*
* @returns {Promise<void>}
*/
const fetchAnalytics = useCallback(async () => {
if (requestPendingRef.current) return;
requestPendingRef.current = true;
const request = {};
requestPendingRef.current = request;
const isCurrent = () => requestPendingRef.current === request;
try {
const { data } = await get(`/${pluginId}/sessions/analytics`);
if (!isCurrent()) return;
setAnalytics(analyticsFromServer(data));
setUpdatedAt(Date.now());
setLoadError(false);
} catch (err) {
if (!isCurrent() || isCancelledRequest(err)) return;
logSafeAdminError('analytics.load', err);
if (isForbidden(err)) setForbidden(true);
setLoadError(true);
} finally {
requestPendingRef.current = false;
setRefreshing(false);
setLoading(false);
if (isCurrent()) {
requestPendingRef.current = null;
setRefreshing(false);
setLoading(false);
}
}
}, [get]);

Expand All @@ -204,6 +217,9 @@ const AnalyticsPage = () => {
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- state updates run after await; the compiler cannot see through the callback
void fetchAnalytics();
return () => {
requestPendingRef.current = null;
};
}, [fetchAnalytics]);

if (loading) {
Expand Down
15 changes: 13 additions & 2 deletions admin/src/pages/Settings/hooks/useSettingsForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useFetchClient, useNotification } from '@strapi/strapi/admin';
import pluginId from '../../../pluginId';
import { areSettingsEqual } from '../../../utils/settingsEquality.mjs';
import { requireSuccessfulMutation } from '../../../utils/adminResponse.mjs';
import { logSafeAdminError } from '../../../utils/safeAdminLog.mjs';
import { isCancelledRequest, logSafeAdminError } from '../../../utils/safeAdminLog.mjs';
import { copyText } from '../../../utils/copyText.mjs';
import { formatSessionDate } from '../../../utils/sessionDates.mjs';
import {
Expand Down Expand Up @@ -87,6 +87,8 @@ export function useSettingsForm() {
// Server settings revision the draft is based on. Sent with every save so
// the server rejects it (409) when another administrator saved in between.
const revisionRef = useRef(null);
// Number of the latest settings load; older loads set no state.
const loadRequestRef = useRef(0);
useLayoutEffect(() => {
settingsRef.current = settings;
savedSettingsRef.current = savedSettings;
Expand Down Expand Up @@ -151,13 +153,21 @@ export function useSettingsForm() {
* failed response shows the retry state instead of an editable default
* draft (IA G).
*
* Only the latest load sets state, and a request aborted on unmount is not
* a failure. React StrictMode mounts, unmounts and mounts again: before
* this, the aborted first load set the error after the second load had
* started, and the page stayed on "Settings could not be loaded."
*
* @returns {Promise<void>}
*/
const fetchSettings = useCallback(async () => {
const request = loadRequestRef.current + 1;
loadRequestRef.current = request;
setLoading(true);
setLoadError(false);
try {
const response = await get(`/${pluginId}/settings`);
if (request !== loadRequestRef.current) return;
if (
!response?.data?.settings ||
typeof response.data.settings !== 'object' ||
Expand All @@ -173,10 +183,11 @@ export function useSettingsForm() {
setSavedSettings(nextSettings);
await fetchGeoIpStatus();
} catch (err) {
if (request !== loadRequestRef.current || isCancelledRequest(err)) return;
logSafeAdminError('settings.load', err);
setLoadError(true);
} finally {
setLoading(false);
if (request === loadRequestRef.current) setLoading(false);
}
}, [get, fetchGeoIpStatus]);

Expand Down
13 changes: 13 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* - Admin panel: ESM, browser globals, JSX, React Hooks recommended rules.
* - Server and Strapi entry files: CommonJS, Node globals, `strapi` as a readonly global.
* - Tests and scripts: Node globals, module type per file extension.
* - Admin StrictMode harness (tests/admin): JSX, Node and browser (jsdom) globals, React Hooks.
* - `eslint-config-prettier` last, so formatting stays with Prettier.
*
* eslint-plugin-jsx-a11y is not used: its latest release (6.10.2, 2024-10) declares
Expand Down Expand Up @@ -89,6 +90,18 @@ export default defineConfig([
},
},

// Admin StrictMode harness and tests: Node test runner with a jsdom window
{
files: ['tests/admin/**/*.{mjs,jsx}'],
extends: [reactHooks.configs.flat.recommended],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parserOptions: { ecmaFeatures: { jsx: true } },
globals: { ...globals.node, ...globals.browser },
},
},

// Playwright snippet: the page.evaluate callbacks run in the browser
{
files: ['tests/ui-field-fixture/check.js'],
Expand Down
Loading
Loading