Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: guard unsaved General settings (#5480)

[._.]/ Adam Eivy98cd74935a67
diff --git a/client/src/components/settings/GeneralTab.jsx b/client/src/components/settings/GeneralTab.jsx
index f2a480f564..362aec0455 100644
--- a/client/src/components/settings/GeneralTab.jsx
+++ b/client/src/components/settings/GeneralTab.jsx
@@ -2,8 +2,10 @@ import { useState, useEffect, useMemo } from 'react';
import { Save } from 'lucide-react';
import toast from '../ui/Toast';
import FormField from '../ui/FormField';
+import UnsavedChangesConfirm from '../ui/UnsavedChangesConfirm';
import BrailleSpinner from '../BrailleSpinner';
import ThemePickerPanel from '../ThemePickerPanel';
+import useUnsavedChangesGuard from '../../hooks/useUnsavedChangesGuard';
import { getSettings, updateSettings } from '../../services/api';
// Coordinate inputs are free text so a partially-typed "-" or "37." isn't
@@ -20,25 +22,39 @@ const parseCoord = (v) => {
export function GeneralTab() {
const [loading, setLoading] = useState(true);
const [timezone, setTimezone] = useState('');
+ const [savedTimezone, setSavedTimezone] = useState(null);
const [saving, setSaving] = useState(false);
const [lat, setLat] = useState('');
const [lon, setLon] = useState('');
+ const [savedLocation, setSavedLocation] = useState(null);
const [savingLocation, setSavingLocation] = useState(false);
const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
const allTimezones = useMemo(() => Intl.supportedValuesOf?.('timeZone') ?? [], []);
+ const timezoneDirty = savedTimezone !== null && timezone !== savedTimezone;
+ const locationDirty = savedLocation !== null
+ && (lat !== savedLocation.lat || lon !== savedLocation.lon);
+ const dirty = timezoneDirty || locationDirty;
+ const routeGuard = useUnsavedChangesGuard(dirty);
useEffect(() => {
getSettings({ silent: true })
.then(settings => {
- setTimezone(settings?.timezone || '');
- setLat(settings?.location?.lat != null ? String(settings.location.lat) : '');
- setLon(settings?.location?.lon != null ? String(settings.location.lon) : '');
+ const nextTimezone = settings?.timezone || '';
+ const nextLat = settings?.location?.lat != null ? String(settings.location.lat) : '';
+ const nextLon = settings?.location?.lon != null ? String(settings.location.lon) : '';
+ setTimezone(nextTimezone);
+ setSavedTimezone(nextTimezone);
+ setLat(nextLat);
+ setLon(nextLon);
+ setSavedLocation({ lat: nextLat, lon: nextLon });
})
.catch(() => toast.error('Failed to load settings'))
.finally(() => setLoading(false));
}, []);
const handleSaveLocation = async () => {
+ const submittedLat = lat;
+ const submittedLon = lon;
// Both-or-neither: weather needs a full pair, and a half-set pair would
// silently mix a custom value with the tool's default coordinate.
if (isBlank(lat) !== isBlank(lon)) {
@@ -62,6 +78,11 @@ export function GeneralTab() {
setSavingLocation(true);
try {
await updateSettings({ location: { lat: parsedLat, lon: parsedLon } }, { silent: true });
+ const nextLat = parsedLat === null ? '' : String(parsedLat);
+ const nextLon = parsedLon === null ? '' : String(parsedLon);
+ setSavedLocation({ lat: nextLat, lon: nextLon });
+ setLat(current => current === submittedLat ? nextLat : current);
+ setLon(current => current === submittedLon ? nextLon : current);
toast.success(parsedLat === null ? 'Location cleared' : `Location set to ${parsedLat}, ${parsedLon}`);
} catch (err) {
toast.error(err.message || 'Failed to save location');
@@ -71,6 +92,7 @@ export function GeneralTab() {
};
const handleSave = async (tz) => {
+ const submittedTimezone = timezone;
const tzToSave = tz || detectedTz;
if (!tzToSave) {
toast.error('Timezone is required.');
@@ -95,7 +117,8 @@ export function GeneralTab() {
setSaving(true);
try {
await updateSettings({ timezone: tzToSave }, { silent: true });
- setTimezone(tzToSave);
+ setSavedTimezone(tzToSave);
+ setTimezone(current => current === submittedTimezone ? tzToSave : current);
toast.success(`Timezone set to ${tzToSave}`);
} catch (err) {
toast.error(err.message || 'Failed to save timezone');
@@ -108,6 +131,13 @@ export function GeneralTab() {
return (
<div className="space-y-6">
+ <UnsavedChangesConfirm
+ guard={routeGuard}
+ when={!saving && !savingLocation}
+ question="Discard your unsaved General settings changes?"
+ label="Discard unsaved General settings changes"
+ onDiscard={routeGuard.proceed}
+ />
<div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
<h3 className="text-lg font-semibold text-white mb-4">Interface Theme</h3>
<ThemePickerPanel />
@@ -140,6 +170,9 @@ export function GeneralTab() {
<Save size={14} className="inline mr-1" />
{saving ? 'Saving...' : 'Save'}
</button>
+ {timezoneDirty && (
+ <span className="text-xs text-port-warning" role="status">Unsaved changes</span>
+ )}
{!timezone && (
<button
onClick={() => handleSave(detectedTz)}
@@ -208,6 +241,9 @@ export function GeneralTab() {
<Save size={14} className="inline mr-1" />
{savingLocation ? 'Saving...' : 'Save'}
</button>
+ {locationDirty && (
+ <span className="text-xs text-port-warning" role="status">Unsaved changes</span>
+ )}
</div>
</div>
</div>
diff --git a/client/src/components/settings/GeneralTab.test.jsx b/client/src/components/settings/GeneralTab.test.jsx
new file mode 100644
index 0000000000..cc67a58cd4
--- /dev/null
+++ b/client/src/components/settings/GeneralTab.test.jsx
@@ -0,0 +1,174 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { createMemoryRouter, RouterProvider } from 'react-router';
+
+vi.mock('../../services/api', () => ({
+ getSettings: vi.fn(),
+ updateSettings: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({
+ default: Object.assign(vi.fn(), {
+ success: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+vi.mock('../ThemePickerPanel', () => ({
+ default: () => <div>Theme picker</div>,
+}));
+
+import { getSettings, updateSettings } from '../../services/api';
+import { GeneralTab } from './GeneralTab';
+
+const SETTINGS = {
+ timezone: 'UTC',
+ location: { lat: 37.7749, lon: -122.4194 },
+};
+const CONFIRM = 'Discard your unsaved General settings changes?';
+
+const timezoneCard = () => screen.getByRole('heading', { name: 'Timezone' }).parentElement;
+const locationCard = () => screen.getByRole('heading', { name: 'Location' }).parentElement;
+
+const renderTab = async () => {
+ const router = createMemoryRouter([
+ { path: '/settings/general', element: <GeneralTab /> },
+ { path: '/settings/security', element: <div>Security settings</div> },
+ ], { initialEntries: ['/settings/general'] });
+ render(<RouterProvider router={router} />);
+ await screen.findByDisplayValue('UTC');
+ return router;
+};
+
+const navigate = (router, to) => act(async () => { await router.navigate(to); });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSettings.mockResolvedValue(SETTINGS);
+ updateSettings.mockResolvedValue({});
+});
+
+describe('GeneralTab unsaved changes', () => {
+ it('marks each edited section dirty, arms beforeunload, and clears when values are restored', async () => {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ await renderTab();
+
+ fireEvent.change(screen.getByLabelText('Timezone (IANA)'), {
+ target: { value: 'America/New_York' },
+ });
+ expect(within(timezoneCard()).getByText('Unsaved changes')).toBeInTheDocument();
+ expect(within(locationCard()).queryByText('Unsaved changes')).toBeNull();
+
+ fireEvent.change(screen.getByLabelText('Latitude (-90 to 90)'), {
+ target: { value: '40.7128' },
+ });
+ expect(within(locationCard()).getByText('Unsaved changes')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(add.mock.calls.some(([type]) => type === 'beforeunload')).toBe(true);
+ });
+
+ fireEvent.change(screen.getByLabelText('Timezone (IANA)'), {
+ target: { value: SETTINGS.timezone },
+ });
+ fireEvent.change(screen.getByLabelText('Latitude (-90 to 90)'), {
+ target: { value: String(SETTINGS.location.lat) },
+ });
+ expect(screen.queryByText('Unsaved changes')).toBeNull();
+ await waitFor(() => {
+ expect(remove.mock.calls.some(([type]) => type === 'beforeunload')).toBe(true);
+ });
+ });
+
+ it('keeps the current route and draft when navigation is canceled', async () => {
+ const router = await renderTab();
+ fireEvent.change(screen.getByLabelText('Timezone (IANA)'), {
+ target: { value: 'America/New_York' },
+ });
+
+ await navigate(router, '/settings/security');
+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
+
+ await waitFor(() => expect(screen.queryByText(CONFIRM)).toBeNull());
+ expect(router.state.location.pathname).toBe('/settings/general');
+ expect(screen.getByLabelText('Timezone (IANA)')).toHaveValue('America/New_York');
+ });
+
+ it('discards the draft and runs the parked Settings navigation', async () => {
+ const router = await renderTab();
+ fireEvent.change(screen.getByLabelText('Longitude (-180 to 180)'), {
+ target: { value: '-74.006' },
+ });
+
+ await navigate(router, '/settings/security');
+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Discard' }));
+
+ expect(await screen.findByText('Security settings')).toBeInTheDocument();
+ expect(router.state.location.pathname).toBe('/settings/security');
+ });
+
+ it('advances only the successful section baseline', async () => {
+ const router = await renderTab();
+ fireEvent.change(screen.getByLabelText('Timezone (IANA)'), {
+ target: { value: 'America/New_York' },
+ });
+ fireEvent.change(screen.getByLabelText('Latitude (-90 to 90)'), {
+ target: { value: '40.7128' },
+ });
+
+ await act(async () => {
+ fireEvent.click(within(timezoneCard()).getByRole('button', { name: 'Save' }));
+ });
+ expect(updateSettings).toHaveBeenCalledWith(
+ { timezone: 'America/New_York' },
+ { silent: true },
+ );
+ expect(within(timezoneCard()).queryByText('Unsaved changes')).toBeNull();
+ expect(within(locationCard()).getByText('Unsaved changes')).toBeInTheDocument();
+
+ await navigate(router, '/settings/security');
+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
+
+ await act(async () => {
+ fireEvent.click(within(locationCard()).getByRole('button', { name: 'Save' }));
+ });
+ expect(updateSettings).toHaveBeenLastCalledWith(
+ { location: { lat: 40.7128, lon: SETTINGS.location.lon } },
+ { silent: true },
+ );
+ expect(screen.queryByText('Unsaved changes')).toBeNull();
+ });
+
+ it('keeps a failed timezone save dirty and guarded', async () => {
+ updateSettings.mockRejectedValueOnce(new Error('timezone offline'));
+ const router = await renderTab();
+ fireEvent.change(screen.getByLabelText('Timezone (IANA)'), {
+ target: { value: 'America/New_York' },
+ });
+
+ await act(async () => {
+ fireEvent.click(within(timezoneCard()).getByRole('button', { name: 'Save' }));
+ });
+ expect(within(timezoneCard()).getByText('Unsaved changes')).toBeInTheDocument();
+
+ await navigate(router, '/settings/security');
+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();
+ });
+
+ it('keeps a failed location save dirty and guarded', async () => {
+ updateSettings.mockRejectedValueOnce(new Error('location offline'));
+ const router = await renderTab();
+ fireEvent.change(screen.getByLabelText('Longitude (-180 to 180)'), {
+ target: { value: '-74.006' },
+ });
+
+ await act(async () => {
+ fireEvent.click(within(locationCard()).getByRole('button', { name: 'Save' }));
+ });
+ expect(within(locationCard()).getByText('Unsaved changes')).toBeInTheDocument();
+
+ await navigate(router, '/settings/security');
+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();
+ });
+});