Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

refactor(web): upgrade xstate to v5 and port the app state machine (#5018)

Gabe Kangas7e19631e69c2
diff --git a/web/components/stores/ClientConfigStore.tsx b/web/components/stores/ClientConfigStore.tsx
index 32e6ab577d..57f374f17e 100644
--- a/web/components/stores/ClientConfigStore.tsx
+++ b/web/components/stores/ClientConfigStore.tsx
@@ -12,6 +12,7 @@ import appStateModel, {
AppStateEvent,
AppStateOptions,
makeEmptyAppState,
+ metaForSnapshot,
} from './application-state';
import { setLocalStorage, getLocalStorage } from '../../utils/localStorage';
import {
@@ -22,7 +23,6 @@ import {
MessageVisibilityEvent,
SocketEvent,
} from '../../interfaces/socket-events';
-import { mergeMeta } from '../../utils/helpers';
import { handleConnectedClientInfoMessage } from './eventhandlers/connected-client-info-handler';
import { ServerStatusServiceContext } from '../../services/status-service';
import { handleNameChangeEvent } from './eventhandlers/handleNameChangeEvent';
@@ -186,8 +186,8 @@ export const ClientConfigStore: FC = () => {
});
};
const sendEvent = (events: string[]) => {
- // console.debug('---- sending event:', event);
- appStateSend(events);
+ // xstate v5 sends single event objects, so fan out the batch.
+ events.forEach(event => appStateSend({ type: event }));
};
const handleStatusChange = (status: ServerStatus) => {
@@ -204,7 +204,7 @@ export const ClientConfigStore: FC = () => {
if (status.online && appState.matches('ready')) {
sendEvent([AppStateEvent.Online]);
- } else if (!status.online && !appState.matches('ready.offline')) {
+ } else if (!status.online && !appState.matches({ ready: 'offline' })) {
sendEvent([AppStateEvent.Offline]);
}
};
@@ -453,14 +453,17 @@ export const ClientConfigStore: FC = () => {
}, [accessToken]);
useEffect(() => {
- appStateService.onTransition(state => {
- const metadata = mergeMeta(state.meta) as AppStateOptions;
-
- // console.debug('--- APP STATE: ', state.value);
- // console.debug('--- APP META: ', metadata);
-
- setAppState(metadata);
- });
+ const applySnapshot = state => {
+ setAppState(metaForSnapshot(state));
+ };
+ const subscription = appStateService.subscribe(applySnapshot);
+ // Sync the current snapshot too: the hydration effect above runs first
+ // and can transition the machine (e.g. straight to online) before this
+ // subscription attaches. xstate v4's onTransition also fired on every
+ // event, transition or not, which papered over that ordering; v5's
+ // subscribe only fires on real transitions.
+ applySnapshot(appStateService.getSnapshot());
+ return () => subscription.unsubscribe();
}, []);
return null;
diff --git a/web/components/stores/application-state.ts b/web/components/stores/application-state.ts
index a512ffd7f7..5bcc5e5db9 100644
--- a/web/components/stores/application-state.ts
+++ b/web/components/stores/application-state.ts
@@ -10,7 +10,7 @@ map or install the VS Code plugin:
https://marketplace.visualstudio.com/items?itemName=statelyai.stately-vscode
*/
-import { createMachine } from 'xstate';
+import { createMachine, type AnyMachineSnapshot } from 'xstate';
export interface AppStateOptions {
chatAvailable: boolean;
@@ -70,8 +70,11 @@ const appStateModel =
/** @xstate-layout N4IgpgJg5mDOIC5QEMAOqDKAXZWwDoAbAe2QgEsA7KAYgCUBRAcQEkMAVBxgEUVFWKxyWcsUp8QAD0QBGAGwz8ABgCscpUoDsAZgAcKgEwrtATgA0IAJ6zNS-CZMLtcuQBY9Jg5t0BfHxbRMHDwiUgpqGgA5BgZuDAB9RlYOLgkBIRExCWkEGRVFVXUtPUNjcytEAxNXfB0DbSNNORMG119-EEDsXAISMipaABkAeQBBbli0wWFRcSQpWQVlNQ0dfSNTC2tc+vwZVwMZWxNbA5kDAz8A9G6QvvDaADFRlkGpjNns2VcCleL1spbRDaA74FS6ORVfYHTSObRXTo3YIEABOYCg5FgeBRA3ozDYnB47xmWXmOQOKj22hUnl02iajjk2iBCCqdgO2n2VRcbQhCK6yPwaIxWLAOIiz1exMyc1A5KMVJpBjpDJczIqCG0enwXk0MiUENMjiUBjk-KRPSFYDIlnwYkIVDANGGj0egxY0WlnzJiF0TXwulU9LqWhMMl0LIM7ipmguIIObU85qClrRNrtADMMw7KE7hpF3Z75ukSbKFgg5Pp7PSQdTXBp9uVtlHtDG464E7okx0BanrRBbVBiMQIAAjSxOyRYy3IDPYgAU2g0y4AlDReyE0wP8EOR+OwF7SXLff7A8ZNCHYeGWedW3qlDIWkz61rLgjKCO4BIN70wgND2W8o3pyyjKrCdZ6q4sYqMmtyouimLYv+xbTDKXyakuyiuHI+QmCoJquCo2FyCyS52PURzqI+mgqIYpqwYKW62vajoAehsJyFS+paPhfoRhqUa6PgTIuLoRznComiEWaPYWpu-bMVmOYHihHxHuWRQ6pCJz0sqGgNMBBjCfohiEUoIJ0kyDF9umu5jhObE+rkqh2BCLS8XhYa6K4wGUuGtEviYZ5qNZ8k2o5x4IJJnGmlUOixoG5kGCy+G1JyXgHGJJhKByrihQQsBigAbmKjzIOQhAAK5ohF5YXJx+q2MYbieFB4KkW0yj6NBfr6vU3n5fglWFSiGblVVNWqaW6H5HY4bNFJbhKI4HV3k0rgnNlS6xm+1wpngtU5NeGoALQXDqbVBct+g5Qofh+EAA */
createMachine({
id: 'appState',
+ types: {} as {
+ events: { type: string };
+ meta: AppStateOptions;
+ },
initial: 'loading',
- predictableActionArguments: true,
states: {
loading: {
meta: LOADING_STATE,
@@ -139,10 +142,22 @@ const appStateModel =
serverFailure: {
type: 'final',
},
- userfailure: {
- type: 'final',
- },
},
});
+// The runtime surface of a machine snapshot that the app consumes. xstate's
+// own declared getMeta() type recurses infinitely (TS2589 at every consumer,
+// even through AnyMachineSnapshot), so the usable contract is named once
+// here instead.
+interface MetaCarryingSnapshot {
+ getMeta(): Record<string, AppStateOptions>;
+}
+
+// Flattens a snapshot's per-state meta into the single AppStateOptions the
+// app consumes (nested states contribute one meta entry per active node).
+export function metaForSnapshot(snapshot: AnyMachineSnapshot): AppStateOptions {
+ const metaSnapshot = snapshot as unknown as MetaCarryingSnapshot;
+ return Object.assign({}, ...Object.values(metaSnapshot.getMeta()));
+}
+
export default appStateModel;
diff --git a/web/package-lock.json b/web/package-lock.json
index 2d17bc8d96..8a0d56936f 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -25,7 +25,7 @@
"@testing-library/react": "^16.3.0",
"@uiw/codemirror-theme-bbedit": "4.25.10",
"@uiw/react-codemirror": "4.25.10",
- "@xstate/react": "3.2.2",
+ "@xstate/react": "^6.1.0",
"antd": "6.5.0",
"autoprefixer": "^10.4.14",
"babel-plugin-dynamic-import-node": "^2.3.3",
@@ -56,7 +56,7 @@
"sharp": "0.34.5",
"ua-parser-js": "1.0.41",
"video.js": "^8.3.0",
- "xstate": "4.38.3",
+ "xstate": "^5.32.4",
"yaml": "2.9.0"
},
"devDependencies": {
@@ -10700,21 +10700,19 @@
}
},
"node_modules/@xstate/react": {
- "version": "3.2.2",
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/@xstate/react/-/react-6.1.0.tgz",
+ "integrity": "sha512-ep9F0jGTI63B/jE8GHdMpUqtuz7yRebNaKv8EMUaiSi29NOglywc2X2YSOV/ygbIK+LtmgZ0q9anoEA2iBSEOw==",
"license": "MIT",
"dependencies": {
"use-isomorphic-layout-effect": "^1.1.2",
- "use-sync-external-store": "^1.0.0"
+ "use-sync-external-store": "^1.2.0"
},
"peerDependencies": {
- "@xstate/fsm": "^2.0.0",
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
- "xstate": "^4.37.2"
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "xstate": "^5.28.0"
},
"peerDependenciesMeta": {
- "@xstate/fsm": {
- "optional": true
- },
"xstate": {
"optional": true
}
@@ -31297,7 +31295,9 @@
"license": "MIT"
},
"node_modules/xstate": {
- "version": "4.38.3",
+ "version": "5.32.4",
+ "resolved": "https://registry.npmjs.org/xstate/-/xstate-5.32.4.tgz",
+ "integrity": "sha512-E5WtDB8DBs2ZWliz2Ry9XfbSZTbBRcK/cwefBot04qQ/L5SLP16xpnTDU4/ZFXuXFhNxi7JP2RhuoGwBnM+S4A==",
"license": "MIT",
"funding": {
"type": "opencollective",
diff --git a/web/package.json b/web/package.json
index 8db6716c07..ef9c721b7b 100644
--- a/web/package.json
+++ b/web/package.json
@@ -44,7 +44,7 @@
"@testing-library/react": "^16.3.0",
"@uiw/codemirror-theme-bbedit": "4.25.10",
"@uiw/react-codemirror": "4.25.10",
- "@xstate/react": "3.2.2",
+ "@xstate/react": "^6.1.0",
"antd": "6.5.0",
"autoprefixer": "^10.4.14",
"babel-plugin-dynamic-import-node": "^2.3.3",
@@ -75,7 +75,7 @@
"sharp": "0.34.5",
"ua-parser-js": "1.0.41",
"video.js": "^8.3.0",
- "xstate": "4.38.3",
+ "xstate": "^5.32.4",
"yaml": "2.9.0"
},
"devDependencies": {
diff --git a/web/tests/applicationState.test.ts b/web/tests/applicationState.test.ts
new file mode 100644
index 0000000000..f14fbb7bea
--- /dev/null
+++ b/web/tests/applicationState.test.ts
@@ -0,0 +1,186 @@
+/*
+ Pins the externally observable contract of the application state machine
+ (components/stores/application-state.ts) after the xstate v4 -> v5 port, so a
+ future refactor (or replacement of xstate entirely) can prove parity against
+ this suite.
+
+ Meta is asserted through metaForSnapshot(), the same function the app
+ consumes it with (it flattens Object.values(snapshot.getMeta()) into one
+ object).
+*/
+
+import { createActor, SimulatedClock, type AnyActorRef } from 'xstate';
+import appStateModel, {
+ AppStateEvent,
+ metaForSnapshot,
+} from '../components/stores/application-state';
+
+const mergedMeta = metaForSnapshot;
+
+// Expected merged meta per state, spelled out as field values (the meta
+// constants for loading/goodbye are not exported from the module).
+const LOADING_META = {
+ chatAvailable: false,
+ chatLoading: false,
+ videoAvailable: false,
+ appLoading: true,
+};
+const OFFLINE_META = {
+ chatAvailable: false,
+ chatLoading: false,
+ videoAvailable: false,
+ appLoading: false,
+};
+const ONLINE_META = {
+ chatAvailable: true,
+ chatLoading: false,
+ videoAvailable: true,
+ appLoading: false,
+};
+const GOODBYE_META = {
+ chatAvailable: true,
+ chatLoading: false,
+ videoAvailable: false,
+ appLoading: false,
+};
+const CHAT_USER_DISABLED_META = { ...ONLINE_META, chatAvailable: false };
+
+const GOODBYE_TIMEOUT_MS = 300000;
+
+const actors: AnyActorRef[] = [];
+const startActor = (clock?: SimulatedClock) => {
+ const actor = createActor(appStateModel, clock ? { clock } : undefined);
+ actors.push(actor);
+ actor.start();
+ return actor;
+};
+
+afterEach(() => {
+ // Stop every actor so a goodbye-state 'after' timer never outlives a test.
+ actors.forEach(actor => actor.stop());
+ actors.length = 0;
+});
+
+describe('application state machine', () => {
+ test('starts in loading with the loading meta', () => {
+ const actor = startActor();
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.value).toBe('loading');
+ expect(snapshot.matches('loading')).toBe(true);
+ expect(snapshot.status).toBe('active');
+ expect(mergedMeta(snapshot)).toEqual(LOADING_META);
+ });
+
+ test('NEEDS_REGISTER while loading stays in loading', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.NeedsRegister });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.value).toBe('loading');
+ expect(mergedMeta(snapshot)).toEqual(LOADING_META);
+ });
+
+ test('LOADED moves to ready.offline with the offline meta, and both matches() forms agree', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Loaded });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.value).toEqual({ ready: 'offline' });
+ expect(snapshot.matches('ready')).toBe(true);
+ expect(snapshot.matches({ ready: 'offline' })).toBe(true);
+ expect(snapshot.matches('loading')).toBe(false);
+ expect(mergedMeta(snapshot)).toEqual(OFFLINE_META);
+ });
+
+ test('full online walk: offline -> online -> goodbye -> back online', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Loaded });
+
+ actor.send({ type: AppStateEvent.Online });
+ let snapshot = actor.getSnapshot();
+ expect(snapshot.matches({ ready: 'online' })).toBe(true);
+ expect(mergedMeta(snapshot)).toEqual(ONLINE_META);
+
+ actor.send({ type: AppStateEvent.Offline });
+ snapshot = actor.getSnapshot();
+ expect(snapshot.matches({ ready: 'goodbye' })).toBe(true);
+ expect(snapshot.matches('ready')).toBe(true);
+ expect(mergedMeta(snapshot)).toEqual(GOODBYE_META);
+
+ actor.send({ type: AppStateEvent.Online });
+ snapshot = actor.getSnapshot();
+ expect(snapshot.matches({ ready: 'online' })).toBe(true);
+ expect(mergedMeta(snapshot)).toEqual(ONLINE_META);
+ });
+
+ test('CHAT_USER_DISABLED while online keeps the online meta except chatAvailable', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Loaded });
+ actor.send({ type: AppStateEvent.Online });
+ actor.send({ type: AppStateEvent.ChatUserDisabled });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.matches({ ready: 'chatUserDisabled' })).toBe(true);
+ expect(mergedMeta(snapshot)).toEqual(CHAT_USER_DISABLED_META);
+ });
+
+ test('FAIL while loading reaches serverFailure and the machine is done', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Fail });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.matches('serverFailure')).toBe(true);
+ expect(snapshot.status).toBe('done');
+ });
+
+ test('ONLINE while loading is ignored without error', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Online });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.value).toBe('loading');
+ expect(snapshot.status).toBe('active');
+ expect(mergedMeta(snapshot)).toEqual(LOADING_META);
+ });
+
+ test('OFFLINE while ready.offline is ignored without error', () => {
+ const actor = startActor();
+ actor.send({ type: AppStateEvent.Loaded });
+ actor.send({ type: AppStateEvent.Offline });
+ const snapshot = actor.getSnapshot();
+
+ expect(snapshot.matches({ ready: 'offline' })).toBe(true);
+ expect(snapshot.status).toBe('active');
+ expect(mergedMeta(snapshot)).toEqual(OFFLINE_META);
+ });
+
+ test('goodbye falls back to offline after exactly 300000ms', () => {
+ const clock = new SimulatedClock();
+ const actor = startActor(clock);
+ actor.send({ type: AppStateEvent.Loaded });
+ actor.send({ type: AppStateEvent.Online });
+ actor.send({ type: AppStateEvent.Offline });
+ expect(actor.getSnapshot().matches({ ready: 'goodbye' })).toBe(true);
+
+ clock.increment(GOODBYE_TIMEOUT_MS - 1);
+ expect(actor.getSnapshot().matches({ ready: 'goodbye' })).toBe(true);
+
+ clock.increment(1);
+ const snapshot = actor.getSnapshot();
+ expect(snapshot.matches({ ready: 'offline' })).toBe(true);
+ expect(mergedMeta(snapshot)).toEqual(OFFLINE_META);
+ });
+
+ test('leaving goodbye via ONLINE cancels the delayed fallback', () => {
+ const clock = new SimulatedClock();
+ const actor = startActor(clock);
+ actor.send({ type: AppStateEvent.Loaded });
+ actor.send({ type: AppStateEvent.Online });
+ actor.send({ type: AppStateEvent.Offline });
+ actor.send({ type: AppStateEvent.Online });
+
+ clock.increment(GOODBYE_TIMEOUT_MS * 2);
+ expect(actor.getSnapshot().matches({ ready: 'online' })).toBe(true);
+ });
+});
diff --git a/web/utils/helpers.js b/web/utils/helpers.js
index 3b1137bc7e..f2c629f524 100644
--- a/web/utils/helpers.js
+++ b/web/utils/helpers.js
@@ -5,17 +5,6 @@ export function getDiffInDaysFromNow(timestamp) {
return (new Date() - time) / (24 * 3600 * 1000);
}
-// Take a nested object of state metadata and merge it into
-// a single flattened node.
-export function mergeMeta(meta) {
- return Object.keys(meta).reduce((acc, key) => {
- const value = meta[key];
- Object.assign(acc, value);
-
- return acc;
- }, {});
-}
-
export const isMobileSafariIos = () => {
try {
const ua = navigator.userAgent;
@@ -32,7 +21,7 @@ export const isMobileSafariIos = () => {
}
return browser.name === 'Mobile Safari' || browser.name === 'Safari';
- } catch (e) {
+ } catch {
return false;
}
};