controller: de-duplicate the hardware toggles

The Hotspot, Bluetooth, Desktop, VNC and Throttle toggles had each been written
out longhand at four layers. Collapse the shared parts:

- useSubsystemToggle() replaces five near-identical hooks. This also fixes a
  latent bug: only useDesktop/useVnc restored state when a request failed, so a
  failed Bluetooth/Throttle/Hotspot toggle left  at null and — since the
  status poll sees no change — the toggle stayed disabled and read as
  unsupported until it remounted.
- SubsystemToggle renders all five, with the Desktop's stop confirmation and
  VNC's desktop gating as declared options rather than bespoke copies.
- The fallback UI's four update*/toggle* pairs become one config-driven
  implementation (-100 lines).
- _raise_for_action() centralises the 13 endpoint failure checks, including
  VNC's 409-vs-500 split.

Deliberately not shared: the six get_*_status_dict() builders (payloads
genuinely differ) and the per-subsystem mechanisms (nmcli/rfkill/sysfs/systemctl).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-07-29 18:21:03 -06:00 • committed by lrnselfreliance
parent 5313ab57ef
commit 07af0c9f28
5 changed files with 410 additions and 515 deletions

View file

@ -977,117 +977,120 @@ export function HelpHeader({
</div>
}
export function HotspotToggle() {
let {on, setHotspot} = useHotspot();
const disabled = on === null;
return <div style={{margin: '0.5em'}}>
<Toggle
label='WiFi Hotspot'
disabled={disabled}
checked={on === true}
onChange={checked => setHotspot(checked)}
/>
{disabled && <InfoPopup content='Hotspot is not supported on this server'/>}
</div>;
}
export function ThrottleToggle() {
let {on, setThrottle} = useThrottle();
const disabled = on === null;
return <div style={{margin: '0.5em'}}>
<Toggle
label='CPU Power-save'
disabled={disabled}
checked={on === true}
onChange={checked => setThrottle(checked)}
/>
{disabled && <InfoPopup content='CPU Power-save is not supported on this server'/>}
</div>;
}
export function BluetoothToggle() {
let {on, setBluetooth} = useBluetooth();
const disabled = on === null;
return <div style={{margin: '0.5em'}}>
<Toggle
label='Bluetooth'
disabled={disabled}
checked={on === true}
onChange={checked => setBluetooth(checked)}
/>
{disabled && <InfoPopup content='Bluetooth is not supported on this server'/>}
</div>;
}
export function DesktopToggle() {
let {on, setDesktop} = useDesktop();
// All the hardware toggles share this shape: a Toggle whose state comes from a
// subsystem hook, disabled when the status is unknown, with an InfoPopup explaining
// why it cannot be used. `confirmStop` asks before switching off.
function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, disabled = null, confirmStop = null}) {
const [confirmOpen, setConfirmOpen] = React.useState(false);
const disabled = on === null;
const unsupported = on === null;
const handleChange = (checked) => {
if (checked) {
setDesktop(true);
} else {
// Stopping the desktop kills any session on this WROLPi's own screen.
if (!checked && confirmStop) {
setConfirmOpen(true);
} else {
onChange(checked);
}
}
const handleConfirmStop = (e) => {
const handleConfirm = (e) => {
if (e) {
e.preventDefault()
}
setConfirmOpen(false);
setDesktop(false);
onChange(false);
}
const popup = unsupported ? unsupportedMessage : info;
return <div style={{margin: '0.5em'}}>
<Confirm
{confirmStop && <Confirm
open={confirmOpen}
onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)}
onConfirm={handleConfirmStop}
header='Stop the desktop'
content={"Anyone using this WROLPi's own screen will lose their session and the display will"
+ ' drop to a terminal. The desktop will return on the next reboot. Are you sure?'}
confirmButton='Stop'
/>
onConfirm={handleConfirm}
header={confirmStop.header}
content={confirmStop.content}
confirmButton={confirmStop.button}
/>}
<Toggle
label='Desktop'
disabled={disabled}
label={label}
disabled={disabled === null ? unsupported : disabled}
checked={on === true}
onChange={handleChange}
/>
{disabled && <InfoPopup content='The Desktop is not supported on this server'/>}
{popup && <InfoPopup content={popup}/>}
</div>;
}
export function HotspotToggle() {
const {on, setHotspot} = useHotspot();
return <SubsystemToggle
label='WiFi Hotspot'
on={on}
onChange={setHotspot}
unsupportedMessage='Hotspot is not supported on this server'
/>;
}
export function ThrottleToggle() {
const {on, setThrottle} = useThrottle();
return <SubsystemToggle
label='CPU Power-save'
on={on}
onChange={setThrottle}
unsupportedMessage='CPU Power-save is not supported on this server'
/>;
}
export function BluetoothToggle() {
const {on, setBluetooth} = useBluetooth();
return <SubsystemToggle
label='Bluetooth'
on={on}
onChange={setBluetooth}
unsupportedMessage='Bluetooth is not supported on this server'
/>;
}
export function DesktopToggle() {
const {on, setDesktop} = useDesktop();
return <SubsystemToggle
label='Desktop'
on={on}
onChange={setDesktop}
unsupportedMessage='The Desktop is not supported on this server'
// Stopping the desktop kills any session on this WROLPi's own screen.
confirmStop={{
header: 'Stop the desktop',
content: "Anyone using this WROLPi's own screen will lose their session and the display will"
+ ' drop to a terminal. The desktop will return on the next reboot. Are you sure?',
button: 'Stop',
}}
/>;
}
export function VncToggle() {
let {on, desktopRunning, setVnc} = useVnc();
const {on, desktopRunning, setVnc} = useVnc();
const unsupported = on === null;
// VNC serves the desktop session; it cannot be started without one. Stopping
// stays available so a running VNC server is never stranded on.
const blockedByDesktop = !desktopRunning && on !== true;
const disabled = unsupported || blockedByDesktop;
let info = null;
if (unsupported) {
info = 'VNC is not supported on this server';
} else if (blockedByDesktop) {
if (blockedByDesktop) {
info = 'Start the Desktop before starting VNC';
} else if (on === true && !desktopRunning) {
info = 'The Desktop is stopped, so VNC clients will see nothing';
}
return <div style={{margin: '0.5em'}}>
<Toggle
label='VNC'
disabled={disabled}
checked={on === true}
onChange={checked => setVnc(checked)}
/>
{info && <InfoPopup content={info}/>}
</div>;
return <SubsystemToggle
label='VNC'
on={on}
onChange={setVnc}
unsupportedMessage='VNC is not supported on this server'
info={info}
disabled={unsupported || blockedByDesktop}
/>;
}
export function Toggle({label, checked, disabled, onChange, icon, popupContent = null, info = null}) {

View file

@ -1024,276 +1024,140 @@ export const useBrowseFiles = () => {
return {browseFiles, openFolders, setOpenFolders, fetchFiles};
}
export const useHotspot = () => {
// Every hardware toggle works the same way: one field of the shared status object
// says whether the subsystem is on, and starting/stopping it is a Controller call.
// `on` is null when the status is unknown, which the UI renders as unsupported.
const useSubsystemToggle = ({
statusField,
onValue = 'on',
offValues = ['off'],
start,
stop,
errorTitle,
errorDescription,
refetchStatus = false,
}) => {
const [on, setOn] = useState(null);
const [inUse, setInUse] = useState(false);
const {status} = useContext(StatusContext);
// Hotspot is unsupported on Docker.
const {dockerized, hotspot_ssid} = status;
const {status, fetchStatus} = useContext(StatusContext);
const value = status?.[statusField];
useEffect(() => {
if (status && status['hotspot_status']) {
const {hotspot_status} = status;
if (hotspot_status === 'connected') {
setOn(true);
setInUse(false);
} else if (hotspot_status === 'in_use') {
setInUse(true);
setOn(false);
} else if (hotspot_status === 'disconnected' || hotspot_status === 'off') {
setOn(false);
setInUse(false);
} else {
setOn(null);
}
if (value === onValue) {
setOn(true);
} else if (offValues.includes(value)) {
setOn(false);
} else {
setOn(null);
}
}, [status]);
}, [value]);
const localSetHotspot = async (enable) => {
const setSubsystem = async (enable) => {
const previous = on;
setOn(null);
try {
if (enable) {
await startHotspot();
await start();
} else {
await stopHotspot();
await stop();
}
} catch (e) {
console.error('Hotspot error:', e);
console.error(`${errorTitle}:`, e);
toast({
type: 'error',
title: 'Hotspot Error',
description: e.message || 'Could not modify hotspot. See server logs.',
title: errorTitle,
description: e.message || errorDescription,
time: 5000,
});
// Nothing changed, so the status poll will not re-sync `on`; without this
// the toggle stays disabled and reads as unsupported until it remounts.
setOn(previous);
}
if (refetchStatus) {
await fetchStatus();
}
}
return {on, inUse, hotspotSsid: hotspot_ssid, setOn, setHotspot: localSetHotspot, dockerized};
return {on, setOn, setSubsystem};
}
export const useDownloads = () => {
const [onceDownloads, setOnceDownloads] = useState(null);
const [recurringDownloads, setRecurringDownloads] = useState(null);
const [pendingOnceDownloads, setPendingOnceDownloads] = useState(null);
export const useHotspot = () => {
const {status} = useContext(StatusContext);
// Hotspot is unsupported on Docker.
const {dockerized, hotspot_ssid, hotspot_status} = status;
const {on, setOn, setSubsystem} = useSubsystemToggle({
statusField: 'hotspot_status',
onValue: 'connected',
// The WiFi device being in use for a network is a kind of "off": the hotspot
// is not running, but starting it takes the user off that network.
offValues: ['disconnected', 'off', 'in_use'],
start: startHotspot,
stop: stopHotspot,
errorTitle: 'Hotspot Error',
errorDescription: 'Could not modify hotspot. See server logs.',
});
const fetchDownloads = async () => {
try {
const data = await getDownloads();
setOnceDownloads(data['once_downloads']);
setRecurringDownloads(data['recurring_downloads']);
setPendingOnceDownloads(data['pending_once_downloads']);
} catch (e) {
console.error(e);
// Display errors.
setOnceDownloads(undefined);
setRecurringDownloads(undefined);
setPendingOnceDownloads(undefined);
}
}
useRecurringTimeout(fetchDownloads, 3 * 1000);
return {onceDownloads, recurringDownloads, pendingOnceDownloads, fetchDownloads}
}
export const useConfigs = () => {
const [configs, setConfigs] = useState(null);
const [loading, setLoading] = useState(false);
const fetchConfigs = async () => {
setLoading(true);
console.log('fetching configs...');
try {
const data = await getConfigs();
setConfigs(data['configs']);
console.debug('fetching configs successful');
} catch (e) {
// Ignore SyntaxError because they happen when the API is down.
if (!(e instanceof SyntaxError)) {
console.error(e);
}
setConfigs(undefined);
} finally {
setLoading(false);
}
}
const importConfig = async (fileName) => {
try {
await postImportConfig(fileName);
} catch (e) {
console.error(e);
}
}
const saveConfig = async (fileName) => {
try {
await postDumpConfig(fileName);
} catch (e) {
console.error(e);
}
}
return {configs, loading, fetchConfigs, importConfig, saveConfig}
return {
on,
inUse: hotspot_status === 'in_use',
hotspotSsid: hotspot_ssid,
setOn,
setHotspot: setSubsystem,
dockerized,
};
}
export const useThrottle = () => {
const [on, setOn] = useState(null);
const {status, fetchStatus} = React.useContext(StatusContext);
const {on, setOn, setSubsystem} = useSubsystemToggle({
statusField: 'throttle_status',
onValue: 'powersave',
offValues: ['ondemand'],
start: enableThrottle,
stop: disableThrottle,
errorTitle: 'Throttle Error',
errorDescription: 'Could not modify throttle. See server logs.',
// The governor is read from sysfs, so refetch rather than wait for the poll.
refetchStatus: true,
});
useEffect(() => {
const throttleStatus = status?.throttle_status;
if (throttleStatus === 'powersave') {
setOn(true);
} else if (throttleStatus === 'ondemand') {
setOn(false);
} else {
setOn(null);
}
}, [status?.throttle_status]);
const localSetThrottle = async (enable) => {
setOn(null);
try {
if (enable) {
await enableThrottle();
} else {
await disableThrottle();
}
} catch (e) {
console.error('Throttle error:', e);
toast({
type: 'error',
title: 'Throttle Error',
description: e.message || 'Could not modify throttle. See server logs.',
time: 5000,
});
}
// Refetch status to get updated throttle state
await fetchStatus();
}
return {on, setOn, setThrottle: localSetThrottle};
return {on, setOn, setThrottle: setSubsystem};
}
export const useBluetooth = () => {
const [on, setOn] = useState(null);
const {status} = useContext(StatusContext);
const {on, setSubsystem} = useSubsystemToggle({
statusField: 'bluetooth_status',
start: unblockBluetooth,
stop: blockBluetooth,
errorTitle: 'Bluetooth Error',
errorDescription: 'Could not modify Bluetooth. See server logs.',
});
useEffect(() => {
const bluetoothStatus = status?.bluetooth_status;
if (bluetoothStatus === 'on') {
setOn(true);
} else if (bluetoothStatus === 'off') {
setOn(false);
} else {
setOn(null);
}
}, [status?.bluetooth_status]);
const localSetBluetooth = async (enable) => {
setOn(null);
try {
if (enable) {
await unblockBluetooth();
} else {
await blockBluetooth();
}
} catch (e) {
console.error('Bluetooth error:', e);
toast({
type: 'error',
title: 'Bluetooth Error',
description: e.message || 'Could not modify Bluetooth. See server logs.',
time: 5000,
});
}
}
return {on, setBluetooth: localSetBluetooth};
return {on, setBluetooth: setSubsystem};
}
export const useDesktop = () => {
const [on, setOn] = useState(null);
const {status} = useContext(StatusContext);
const {on, setSubsystem} = useSubsystemToggle({
statusField: 'desktop_status',
start: startDesktop,
stop: stopDesktop,
errorTitle: 'Desktop Error',
errorDescription: 'Could not start/stop the desktop. See server logs.',
});
useEffect(() => {
const desktopStatus = status?.desktop_status;
if (desktopStatus === 'on') {
setOn(true);
} else if (desktopStatus === 'off') {
setOn(false);
} else {
setOn(null);
}
}, [status?.desktop_status]);
const localSetDesktop = async (running) => {
const previous = on;
setOn(null);
try {
if (running) {
await startDesktop();
} else {
await stopDesktop();
}
} catch (e) {
console.error('Desktop error:', e);
toast({
type: 'error',
title: 'Desktop Error',
description: e.message || 'Could not start/stop the desktop. See server logs.',
time: 5000,
});
// The desktop did not change, so the status poll will not re-sync `on`;
// restore it or the toggle stays disabled.
setOn(previous);
}
}
return {on, setDesktop: localSetDesktop};
return {on, setDesktop: setSubsystem};
}
export const useVnc = () => {
const [on, setOn] = useState(null);
const {status} = useContext(StatusContext);
const {on, setSubsystem} = useSubsystemToggle({
statusField: 'vnc_status',
start: startVnc,
stop: stopVnc,
errorTitle: 'VNC Error',
errorDescription: 'Could not start/stop VNC. See server logs.',
});
// VNC serves the desktop session, so it cannot be started without one.
const desktopRunning = status?.desktop_status === 'on';
useEffect(() => {
const vncStatus = status?.vnc_status;
if (vncStatus === 'on') {
setOn(true);
} else if (vncStatus === 'off') {
setOn(false);
} else {
setOn(null);
}
}, [status?.vnc_status]);
const localSetVnc = async (running) => {
const previous = on;
setOn(null);
try {
if (running) {
await startVnc();
} else {
await stopVnc();
}
} catch (e) {
console.error('VNC error:', e);
toast({
type: 'error',
title: 'VNC Error',
description: e.message || 'Could not start/stop VNC. See server logs.',
time: 5000,
});
// The status poll will not re-sync `on` because VNC did not change.
setOn(previous);
}
}
return {on, desktopRunning, setVnc: localSetVnc};
return {on, desktopRunning: status?.desktop_status === 'on', setVnc: setSubsystem};
}
export const useSearchDirectories = (value) => {

View file

@ -0,0 +1,129 @@
import React from 'react';
import {act, renderHook, waitFor} from '@testing-library/react';
import {useBluetooth, useDesktop, useHotspot, useThrottle, useVnc} from './customHooks';
import {StatusContext} from '../contexts/contexts';
jest.mock('../api/controller', () => ({
unblockBluetooth: jest.fn().mockResolvedValue({}),
blockBluetooth: jest.fn().mockResolvedValue({}),
startHotspot: jest.fn().mockResolvedValue({}),
stopHotspot: jest.fn().mockResolvedValue({}),
startDesktop: jest.fn().mockResolvedValue({}),
stopDesktop: jest.fn().mockResolvedValue({}),
startVnc: jest.fn().mockResolvedValue({}),
stopVnc: jest.fn().mockResolvedValue({}),
enableThrottle: jest.fn().mockResolvedValue({}),
disableThrottle: jest.fn().mockResolvedValue({}),
getControllerStats: jest.fn().mockResolvedValue({}),
}));
jest.mock('react-semantic-toasts-2', () => ({toast: jest.fn()}));
const controllerApi = require('../api/controller');
const fetchStatus = jest.fn();
const makeWrapper = (status) => ({children}) => (
<StatusContext.Provider value={{status, fetchStatus}}>{children}</StatusContext.Provider>
);
beforeEach(() => {
jest.clearAllMocks();
Object.values(controllerApi).forEach(fn => fn.mockResolvedValue && fn.mockResolvedValue({}));
});
describe('subsystem toggle hooks', () => {
// Each hook reads a different status field with different values for on/off.
const cases = [
{
name: 'bluetooth', hook: useBluetooth, setter: 'setBluetooth',
status: {bluetooth_status: 'on'}, offStatus: {bluetooth_status: 'off'},
start: 'unblockBluetooth', stop: 'blockBluetooth',
},
{
name: 'desktop', hook: useDesktop, setter: 'setDesktop',
status: {desktop_status: 'on'}, offStatus: {desktop_status: 'off'},
start: 'startDesktop', stop: 'stopDesktop',
},
{
name: 'vnc', hook: useVnc, setter: 'setVnc',
status: {vnc_status: 'on'}, offStatus: {vnc_status: 'off'},
start: 'startVnc', stop: 'stopVnc',
},
{
name: 'throttle', hook: useThrottle, setter: 'setThrottle',
status: {throttle_status: 'powersave'}, offStatus: {throttle_status: 'ondemand'},
start: 'enableThrottle', stop: 'disableThrottle',
},
{
name: 'hotspot', hook: useHotspot, setter: 'setHotspot',
status: {hotspot_status: 'connected'}, offStatus: {hotspot_status: 'disconnected'},
start: 'startHotspot', stop: 'stopHotspot',
},
];
cases.forEach(({name, hook, setter, status, offStatus, start, stop}) => {
describe(name, () => {
it('reports on and off from the status field', async () => {
const {result} = renderHook(hook, {wrapper: makeWrapper(status)});
await waitFor(() => expect(result.current.on).toBe(true));
const {result: offResult} = renderHook(hook, {wrapper: makeWrapper(offStatus)});
await waitFor(() => expect(offResult.current.on).toBe(false));
});
it('reports unknown status as null so the UI can disable the toggle', async () => {
const {result} = renderHook(hook, {wrapper: makeWrapper({})});
await waitFor(() => expect(result.current.on).toBe(null));
});
it('starts and stops through the Controller', async () => {
const {result} = renderHook(hook, {wrapper: makeWrapper(offStatus)});
await waitFor(() => expect(result.current.on).toBe(false));
await act(async () => await result.current[setter](true));
expect(controllerApi[start]).toHaveBeenCalled();
await act(async () => await result.current[setter](false));
expect(controllerApi[stop]).toHaveBeenCalled();
});
it('restores the previous state when the request fails', async () => {
// Otherwise `on` stays null, and because the status poll sees no change
// the toggle is left disabled and reading as unsupported until remount.
controllerApi[stop].mockRejectedValue(new Error('boom'));
const {result} = renderHook(hook, {wrapper: makeWrapper(status)});
await waitFor(() => expect(result.current.on).toBe(true));
await act(async () => await result.current[setter](false));
expect(result.current.on).toBe(true);
});
});
});
it('throttle refetches status because the governor is read from sysfs', async () => {
const {result} = renderHook(useThrottle, {wrapper: makeWrapper({throttle_status: 'ondemand'})});
await waitFor(() => expect(result.current.on).toBe(false));
await act(async () => await result.current.setThrottle(true));
expect(fetchStatus).toHaveBeenCalled();
});
it('hotspot reports a WiFi device that is in use for a network', async () => {
const {result} = renderHook(useHotspot, {wrapper: makeWrapper({hotspot_status: 'in_use'})});
await waitFor(() => expect(result.current.inUse).toBe(true));
// In use means the hotspot is not running, but starting it leaves that network.
expect(result.current.on).toBe(false);
});
it('vnc exposes whether the desktop it serves is running', async () => {
const {result} = renderHook(useVnc, {wrapper: makeWrapper({vnc_status: 'off', desktop_status: 'on'})});
await waitFor(() => expect(result.current.desktopRunning).toBe(true));
const {result: stopped} = renderHook(useVnc, {wrapper: makeWrapper({vnc_status: 'off', desktop_status: 'off'})});
await waitFor(() => expect(stopped.current.desktopRunning).toBe(false));
});
});