From 3481f98bccf4e0ee11ce7a63f41556370c503c58 Mon Sep 17 00:00:00 2001 From: Timothy Date: Mon, 13 Jul 2026 23:47:43 +0200 Subject: [PATCH 1/2] fix(spa): clear dirty guard before saved navigation Fixes #344 Co-Authored-By: OpenAI Codex --- docs/spa-conventions.md | 9 +++++ web/src/mediaSources/useDirtyGuard.ts | 13 +++++-- .../RemoteConnectionEditScreen.test.tsx | 34 +++++++++++++++++++ .../screens/RemoteConnectionEditScreen.tsx | 3 +- 4 files changed, 56 insertions(+), 3 deletions(-) diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index 713171d49..f0f89b36e 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -327,6 +327,15 @@ draft to navigation. The shared module `web/src/navigationGuard.ts` is the seam: Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state value, so `canLeaveCurrentScreen()` sees the current dirtiness synchronously at click time. + +- **Successful save + same-callback navigation:** `useDirtyGuard` returns a `markClean` callback for + the narrow case where a successful save queues the new draft/baseline and immediately calls + `navigateToPath(...)` in that same promise callback. React has not committed the clean render before + the synthetic `popstate`, so call `markClean()` after the durable save succeeds and immediately before + navigating. Still queue the real clean draft/baseline state; the callback only transfers the synchronous + guard truth across that one event boundary. Do not replace it with a timer or a forced render. Screens + that remain mounted after saving do not need the callback. + ## 9. Review checklist — temporal semantics - **For every effect / timer / async completion, ask: *when* does it fire (mount, dependency change, diff --git a/web/src/mediaSources/useDirtyGuard.ts b/web/src/mediaSources/useDirtyGuard.ts index 4a772675d..6b4d387c0 100644 --- a/web/src/mediaSources/useDirtyGuard.ts +++ b/web/src/mediaSources/useDirtyGuard.ts @@ -8,11 +8,18 @@ // each keystroke. A single hook keeps the three editors (connection / libraries / path-replacements) // consistent instead of copy-pasting the guard block into each. -import { useEffect, useRef } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import { registerNavigationGuard } from '../navigationGuard'; -export function useDirtyGuard(dirty: boolean, prompt: string): void { +export function useDirtyGuard(dirty: boolean, prompt: string): () => void { const dirtyRef = useRef(dirty); + // A successful save may navigate in the same promise callback that queues the clean baseline. + // React has not rendered that baseline yet, so let the caller transfer the guard synchronously + // before dispatching the synthetic popstate. The normal render still owns the durable state. + const markClean = useCallback(() => { + dirtyRef.current = false; + }, []); + // Keep the ref current for the synchronous guard predicate. Updated in an effect (committed before // any user pop/nav gesture can fire) rather than during render. useEffect(() => { @@ -32,4 +39,6 @@ export function useDirtyGuard(dirty: boolean, prompt: string): void { window.addEventListener('beforeunload', handler); return () => window.removeEventListener('beforeunload', handler); }, [dirty]); + + return markClean; } diff --git a/web/src/screens/RemoteConnectionEditScreen.test.tsx b/web/src/screens/RemoteConnectionEditScreen.test.tsx index d2056fb08..a1c4cda18 100644 --- a/web/src/screens/RemoteConnectionEditScreen.test.tsx +++ b/web/src/screens/RemoteConnectionEditScreen.test.tsx @@ -82,6 +82,40 @@ describe('RemoteConnectionEditScreen', () => { expect(body.apiKey).toBe(''); // blank = retain existing key server-side }); + it.each(['jellyfin', 'emby'] as const)( + 'successful %s save navigates without triggering the dirty guard', + async (family) => { + const editPath = `/app/libraries/${family}/connection`; + window.history.replaceState(null, '', editPath); + installFetch(family, { + connection: { address: `http://${family}:8096`, hasApiKey: true }, + saveBody: { address: `http://${family}:9000`, hasApiKey: true } + }); + + const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false); + const onPopState = () => { + // Mirror App's dirty-guard veto: a rejected synthetic pop restores the editor path. + if (!canLeaveCurrentScreen()) { + window.history.pushState(null, '', editPath); + } + }; + window.addEventListener('popstate', onPopState); + + try { + render(); + const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement; + + fireEvent.change(address, { target: { value: `http://${family}:9000` } }); + fireEvent.click(screen.getByRole('button', { name: 'Save connection' })); + + await vi.waitFor(() => expect(window.location.pathname).toBe(`/app/libraries/${family}`)); + expect(confirmSpy).not.toHaveBeenCalled(); + } finally { + window.removeEventListener('popstate', onPopState); + } + } + ); + it('first connect (no stored key) requires an api key before Save enables', async () => { installFetch('jellyfin', { connection: { address: '', hasApiKey: false } }); diff --git a/web/src/screens/RemoteConnectionEditScreen.tsx b/web/src/screens/RemoteConnectionEditScreen.tsx index 2d193a0b0..4733e9bba 100644 --- a/web/src/screens/RemoteConnectionEditScreen.tsx +++ b/web/src/screens/RemoteConnectionEditScreen.tsx @@ -84,7 +84,7 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit const valid = addressValid && apiKeyValid; const dirty = JSON.stringify(draft) !== JSON.stringify(saved); - useDirtyGuard(dirty, DIRTY_PROMPT); + const markDirtyGuardClean = useDirtyGuard(dirty, DIRTY_PROMPT); if (loadError) { return ( @@ -129,6 +129,7 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit setSaved(next); setLoaded({ hasApiKey: connection.hasApiKey }); setSaving(false); + markDirtyGuardClean(); navigateToPath(familyRoute(family)); }) .catch((error: unknown) => { -- 2.47.3 From b9305fdee99d05209c1db6ebc48deb264e19680b Mon Sep 17 00:00:00 2001 From: Timothy Date: Tue, 14 Jul 2026 00:06:29 +0200 Subject: [PATCH 2/2] fix(spa): preserve remote drafts during save Disable and gate remote connection draft inputs while a save owns the current revision. Exercise the real App-owned route transition after a successful save so the regression proves the editor unmounts without a dirty prompt. Refs #344 Co-Authored-By: OpenAI Codex --- docs/spa-conventions.md | 7 ++- web/src/App.test.tsx | 53 +++++++++++++++++++ .../RemoteConnectionEditScreen.test.tsx | 36 +++++++++++++ .../screens/RemoteConnectionEditScreen.tsx | 14 ++++- 4 files changed, 106 insertions(+), 4 deletions(-) diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index f0f89b36e..c0507ed39 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -333,8 +333,11 @@ Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state v `navigateToPath(...)` in that same promise callback. React has not committed the clean render before the synthetic `popstate`, so call `markClean()` after the durable save succeeds and immediately before navigating. Still queue the real clean draft/baseline state; the callback only transfers the synchronous - guard truth across that one event boundary. Do not replace it with a timer or a forced render. Screens - that remain mounted after saving do not need the callback. + guard truth across that one event boundary. Only do this while the successful request still owns the + current draft: disable or otherwise gate draft mutations for the entire in-flight save, or revision-check + the completion before marking clean. Otherwise the completion can discard edits made after the request + started. Do not replace the callback with a timer or a forced render. Screens that remain mounted after + saving do not need the callback. ## 9. Review checklist — temporal semantics diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 3579f54c6..2407fcfd1 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -595,6 +595,32 @@ describe('ChicoryTV SPA scaffold', () => { confirmSpy.mockRestore(); }); + it('successful remote connection save clears App guard and mounts the source screen (#344)', async () => { + mockDashboardApi({ + jellyfinConnection: { address: 'http://jf:8096', hasApiKey: true }, + jellyfinState: { + isAuthorized: true, + isLocked: false, + servers: [{ id: 2, name: 'Test Jellyfin', address: 'http://jf:9000' }] + } + }); + window.history.replaceState(null, '', '/app/libraries/jellyfin/connection'); + render(); + + const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement; + fireEvent.change(address, { target: { value: 'http://jf:9000' } }); + + const confirmSpy = vi.mocked(window.confirm); + confirmSpy.mockClear(); + fireEvent.click(screen.getByRole('button', { name: 'Save connection' })); + + expect(await screen.findByRole('heading', { name: 'Jellyfin' })).toBeInTheDocument(); + expect(window.location.pathname).toBe('/app/libraries/jellyfin'); + expect(screen.getByRole('button', { name: 'Edit connection' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Save connection' })).not.toBeInTheDocument(); + expect(confirmSpy).not.toHaveBeenCalled(); + }); + it('opens the create-schedule dialog from the TopBar Add Schedule button', async () => { mockDashboardApi({ schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); @@ -2845,6 +2871,8 @@ function mockDashboardApi({ health = [], libraryScanStatusFailAfterTrigger = false, libraryScanStatuses = [], + jellyfinConnection = null, + jellyfinState = null, localLibraryDetail = null, libraryScanStatusesAfterMutation = null, libraryScanStatusSequence = null, @@ -2915,6 +2943,8 @@ function mockDashboardApi({ health?: unknown[]; libraryScanStatusFailAfterTrigger?: boolean; libraryScanStatuses?: unknown[]; + jellyfinConnection?: { address: string | null; hasApiKey: boolean } | null; + jellyfinState?: unknown; localLibraryDetail?: unknown; libraryScanStatusesAfterMutation?: unknown[] | null; libraryScanStatusSequence?: unknown[][] | null; @@ -2963,6 +2993,7 @@ function mockDashboardApi({ vi.spyOn(window, 'confirm').mockReturnValue(confirm); vi.spyOn(window, 'prompt').mockReturnValue(prompt); let currentLibraryScanStatuses = libraryScanStatuses; + let currentJellyfinConnection = jellyfinConnection; let currentChannelTemplates = channelTemplates; let currentScheduleItems = scheduleItems; const remainingSettingsGetFailures: Record = { ...settingsGetFailuresBeforeSuccess }; @@ -3133,6 +3164,28 @@ function mockDashboardApi({ return Promise.resolve(jsonResponse([])); } + if (path === '/api/v1/media-sources/jellyfin/connection') { + if ((init?.method ?? 'GET') === 'PUT') { + const body = JSON.parse(String(init?.body ?? '{}')) as { address?: string }; + currentJellyfinConnection = { address: body.address ?? null, hasApiKey: true }; + return Promise.resolve(jsonResponse(currentJellyfinConnection)); + } + + return Promise.resolve( + currentJellyfinConnection + ? jsonResponse(currentJellyfinConnection) + : jsonResponse(null, 404) + ); + } + + if (path === '/api/v1/media-sources/jellyfin') { + return Promise.resolve(jsonResponse(jellyfinState ?? { + isAuthorized: false, + isLocked: false, + servers: [] + })); + } + if (path === '/api/v1/media-sources') { if (remainingMediaSourcesFailures > 0) { remainingMediaSourcesFailures -= 1; diff --git a/web/src/screens/RemoteConnectionEditScreen.test.tsx b/web/src/screens/RemoteConnectionEditScreen.test.tsx index a1c4cda18..bfabcf980 100644 --- a/web/src/screens/RemoteConnectionEditScreen.test.tsx +++ b/web/src/screens/RemoteConnectionEditScreen.test.tsx @@ -13,6 +13,7 @@ function json(body: unknown, status = 200): Response { interface Options { connection: { address: string | null; hasApiKey: boolean }; + saveResponse?: Promise; saveStatus?: number; saveBody?: unknown; } @@ -28,6 +29,9 @@ function installFetch(family: string, options: Options) { } if (url.endsWith(`/api/v1/media-sources/${family}/connection`) && method === 'PUT') { putBodies.push(String(init?.body ?? '')); + if (options.saveResponse) { + return options.saveResponse; + } const status = options.saveStatus ?? 200; if (status >= 400) { return Promise.resolve(json({ title: 'Invalid', detail: 'Connection failed' }, status)); @@ -116,6 +120,38 @@ describe('RemoteConnectionEditScreen', () => { } ); + it('blocks draft edits while a save is in flight so the completion cannot discard newer input', async () => { + let resolveSave: (response: Response) => void = () => {}; + const saveResponse = new Promise((resolve) => { + resolveSave = resolve; + }); + const { putBodies } = installFetch('jellyfin', { + connection: { address: 'http://jf:8096', hasApiKey: true }, + saveResponse + }); + + render(); + const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement; + const apiKey = screen.getByPlaceholderText(/leave blank to keep/i) as HTMLInputElement; + + fireEvent.change(address, { target: { value: 'http://jf:9000' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save connection' })); + + await vi.waitFor(() => expect(putBodies).toHaveLength(1)); + expect(address).toBeDisabled(); + expect(apiKey).toBeDisabled(); + + // A synthetic event cannot bypass the same mutation gate used by the disabled controls. + fireEvent.change(address, { target: { value: 'http://jf:newer' } }); + fireEvent.change(apiKey, { target: { value: 'newer-key' } }); + expect(address.value).toBe('http://jf:9000'); + expect(apiKey.value).toBe(''); + + resolveSave(json({ address: 'http://jf:9000', hasApiKey: true })); + await vi.waitFor(() => expect(window.location.pathname).toBe('/app/libraries/jellyfin')); + expect(putBodies).toHaveLength(1); + }); + it('first connect (no stored key) requires an api key before Save enables', async () => { installFetch('jellyfin', { connection: { address: '', hasApiKey: false } }); diff --git a/web/src/screens/RemoteConnectionEditScreen.tsx b/web/src/screens/RemoteConnectionEditScreen.tsx index 4733e9bba..248278144 100644 --- a/web/src/screens/RemoteConnectionEditScreen.tsx +++ b/web/src/screens/RemoteConnectionEditScreen.tsx @@ -158,17 +158,27 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit Connection} subtitle={`${meta.label} server address and API key.`}>
setDraft((current) => ({ ...current, address: event.target.value }))} + onChange={(event) => { + if (!saving) { + setDraft((current) => ({ ...current, address: event.target.value })); + } + }} placeholder="http://192.168.1.50:8096" error={draft.address.trim() && !addressValid ? 'Enter a valid absolute http(s) URL' : null} /> setDraft((current) => ({ ...current, apiKey: event.target.value }))} + onChange={(event) => { + if (!saving) { + setDraft((current) => ({ ...current, apiKey: event.target.value })); + } + }} placeholder={hasApiKey ? 'Key is set — leave blank to keep, or enter a new key' : 'Enter an API key'} error={!apiKeyValid && draft.apiKey.length === 0 && !hasApiKey ? 'API key is required' : null} /> -- 2.47.3