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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: protect unsaved catalog ingredient edits (#5210)
[._.]/ Adam Eivy0fed423f5f9b
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex c92e904e5b..20cc86046a 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -12,6 +12,7 @@ import toast from '../components/ui/Toast';import FilePickerButton from '../components/ui/FilePickerButton';import Modal from '../components/ui/Modal.jsx';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair.jsx';+import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm.jsx';import {getCatalogIngredientDetails,updateCatalogIngredient,@@ -40,6 +41,7 @@ import MediaImage from '../components/MediaImage';import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';import TagPicker from '../components/TagPicker';import GenericIngredientFields from '../components/GenericIngredientFields';+import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';import { timeAgo, formatDateTime } from '../utils/formatters';@@ -111,6 +113,27 @@ export function buildGenerationPromptSeed(payload, typeDef, tags = []) {: seed;}+// Compare JSON-shaped editor values by value while ignoring object-key order.+// A catalog payload can arrive from a peer with the same fields in a different+// order; that is not an edit the user needs to save.+function stableSerialize(value) {+ return JSON.stringify(value, (_key, current) => {+ if (!current || typeof current !== 'object' || Array.isArray(current)) return current;+ return Object.keys(current).sort().reduce((sorted, key) => {+ sorted[key] = current[key];+ return sorted;+ }, {});+ });+}++function sameValue(left, right) {+ return stableSerialize(left) === stableSerialize(right);+}++function ingredientPayload(value) {+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};+}+export default function CatalogIngredient() {const { id } = useParams();const navigate = useNavigate();@@ -329,10 +352,23 @@ export default function CatalogIngredient() {});setSaving(false);if (!updated) return;- setRecord((prev) => ({ ...prev, ...updated }));+ const persistedName = typeof updated.name === 'string' ? updated.name : trimmedName;+ const persistedTags = Array.isArray(updated.tags) ? updated.tags : tags;+ const persistedPayload = Object.hasOwn(updated, 'payload')+ ? ingredientPayload(updated.payload)+ : ingredientPayload(payload);+ setRecord((prev) => ({+ ...prev,+ ...updated,+ name: persistedName,+ tags: persistedTags,+ payload: persistedPayload,+ }));+ setName(persistedName);// The server normalizes tags through the canonical table (casing/whitespace// collapse), so reflect the persisted set back into the chips.- if (Array.isArray(updated.tags)) setTags(updated.tags);+ setTags(persistedTags);+ setPayload({ ...persistedPayload });toast.success('Saved');refreshRevisions();};@@ -368,6 +404,19 @@ export default function CatalogIngredient() {setPayload((prev) => ({ ...prev, [key]: value }));};+ const isDirty = Boolean(record && (+ name !== (record.name || '')+ || !sameValue(tags, Array.isArray(record.tags) ? record.tags : [])+ || !sameValue(payload, ingredientPayload(record.payload))+ ));+ const routeGuard = useUnsavedChangesGuard(isDirty);+ const discardAndExit = useCallback(() => {+ // The parked route is leaving, so unmounting discards the local draft. Do+ // not clear isDirty before proceeding: the shared guard auto-proceeds when+ // a parked draft settles, which would race this explicit proceed call.+ routeGuard.proceed();+ }, [routeGuard]);+if (loading || !record) {return (<section className="h-full overflow-y-auto p-4 md:p-6">@@ -413,6 +462,13 @@ export default function CatalogIngredient() {return (<section className="h-full overflow-y-auto p-4 md:p-6">+ <UnsavedChangesConfirm+ guard={routeGuard}+ when={!saving}+ question="Discard your unsaved changes to this ingredient?"+ label={`Discard unsaved changes to ${record.name || 'this ingredient'}`}+ onDiscard={discardAndExit}+ /><div className="max-w-4xl mx-auto space-y-5"><header className="flex items-start justify-between gap-3 flex-wrap"><div className="flex items-start gap-3 min-w-0">@@ -437,6 +493,7 @@ export default function CatalogIngredient() {className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white text-sm font-medium">{saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} Save</button>+ {isDirty && <span className="text-xs text-port-warning" role="status">Unsaved changes</span>}{armedDelete ? (<span className="inline-flex items-center gap-1 text-sm"><span className="text-gray-400 px-1">Delete this ingredient?</span>diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxindex 10c898341a..234c0ec2e5 100644--- a/client/src/pages/CatalogIngredient.test.jsx+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -8,7 +8,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, waitFor, fireEvent } from '@testing-library/react';-import { MemoryRouter } from 'react-router';+import { createMemoryRouter, RouterProvider } from 'react-router';// Stable navigate mock — returning a fresh vi.fn() per call would change the// load effect's dependency identity every render and re-fire the fetch, which@@ -96,16 +96,36 @@ vi.mock('../components/pipeline/MediaJobThumb', async () => {vi.mock('../services/apiImageVideo', () => ({ listImageGallery: vi.fn(async () => []) }));vi.mock('../components/IngredientPicker', () => ({ default: () => null }));vi.mock('../components/MediaImage', () => ({ default: ({ src, alt }) => <img src={src} alt={alt} /> }));-vi.mock('../components/TagPicker', () => ({ default: () => <div data-testid="tag-picker" /> }));+vi.mock('../components/loraTraining/CharacterLoraChip', () => ({ default: () => null }));+vi.mock('../components/TagPicker', () => ({+ default: ({ value = [], onChange }) => (+ <button+ type="button"+ onClick={() => onChange(value.includes('example-tag')+ ? value.filter((tag) => tag !== 'example-tag')+ : [...value, 'example-tag'])}+ >+ Change tag+ </button>+ ),+}));vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));import CatalogIngredient, { buildGenerationPromptSeed } from './CatalogIngredient';-import { getCatalogIngredientDetails, unlinkCatalogIngredientRelation } from '../services/apiCatalog';+import { getCatalogIngredientDetails, unlinkCatalogIngredientRelation, updateCatalogIngredient } from '../services/apiCatalog';-const renderPage = () => render(<MemoryRouter><CatalogIngredient /></MemoryRouter>);+const renderPage = (path = '/catalog/character/cat-chr-1') => {+ const router = createMemoryRouter([+ { path: '/catalog', element: <div>Catalog index</div> },+ { path: '/catalog/:type/:id', element: <CatalogIngredient /> },+ ], { initialEntries: [path] });+ return { ...render(<RouterProvider router={router} />), router };+};beforeEach(() => {getCatalogIngredientDetails.mockImplementation(async () => detailsOf(CHAR_FIXTURE));+ updateCatalogIngredient.mockReset();+ unlinkCatalogIngredientRelation.mockReset();});describe('CatalogIngredient — character sheet', () => {@@ -144,6 +164,61 @@ describe('CatalogIngredient — character sheet', () => {await waitFor(() => expect(screen.queryByText('Example Place')).toBeNull());});+ describe('unsaved changes', () => {+ it('tracks name, tags, and payload edits in the unsaved indicator', async () => {+ renderPage();+ const nameInput = await screen.findByLabelText('Name');+ const descriptionInput = screen.getByDisplayValue('Sharp eyes, ink-stained cuffs.');+ const tagButton = screen.getByRole('button', { name: 'Change tag' });++ expect(screen.queryByText('Unsaved changes')).toBeNull();++ fireEvent.change(nameInput, { target: { value: 'Edited ingredient' } });+ expect(screen.getByText('Unsaved changes')).toBeTruthy();+ fireEvent.change(nameInput, { target: { value: CHAR_FIXTURE.name } });+ await waitFor(() => expect(screen.queryByText('Unsaved changes')).toBeNull());++ fireEvent.click(tagButton);+ expect(screen.getByText('Unsaved changes')).toBeTruthy();+ fireEvent.click(tagButton);+ await waitFor(() => expect(screen.queryByText('Unsaved changes')).toBeNull());++ fireEvent.change(descriptionInput, { target: { value: 'Edited description' } });+ expect(screen.getByText('Unsaved changes')).toBeTruthy();+ });++ it('confirms before the Back link discards dirty edits', async () => {+ const { router } = renderPage();+ const nameInput = await screen.findByLabelText('Name');+ fireEvent.change(nameInput, { target: { value: 'Edited ingredient' } });++ fireEvent.click(screen.getByRole('link', { name: /Back/ }));+ expect(await screen.findByText('Discard your unsaved changes to this ingredient?')).toBeTruthy();+ expect(screen.queryByText('Catalog index')).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));+ await waitFor(() => expect(screen.queryByText('Discard your unsaved changes to this ingredient?')).toBeNull());+ expect(router.state.location.pathname).toBe('/catalog/character/cat-chr-1');++ fireEvent.click(screen.getByRole('link', { name: /Back/ }));+ expect(await screen.findByText('Discard your unsaved changes to this ingredient?')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Discard' }));+ expect(await screen.findByText('Catalog index')).toBeTruthy();+ });++ it('clears the unsaved indicator after a successful save', async () => {+ updateCatalogIngredient.mockResolvedValue({ ...CHAR_FIXTURE, name: 'Saved ingredient' });+ renderPage();+ const nameInput = await screen.findByLabelText('Name');+ fireEvent.change(nameInput, { target: { value: 'Saved ingredient' } });+ expect(screen.getByText('Unsaved changes')).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateCatalogIngredient).toHaveBeenCalled());+ await waitFor(() => expect(screen.queryByText('Unsaved changes')).toBeNull());+ });+ });+it('renders grouped sheet sections with the enriched canon scalar fields', async () => {renderPage();await waitFor(() => expect(screen.getByDisplayValue('Sharp eyes, ink-stained cuffs.')).toBeTruthy());