fix(spa): preserve remote drafts during save
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 11s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 13s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m32s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 9m50s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

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 <codex@openai.com>
This commit is contained in:
2026-07-14 00:06:29 +02:00
co-authored by OpenAI Codex
parent 3481f98bcc
commit b9305fdee9
4 changed files with 106 additions and 4 deletions
+5 -2
View File
@@ -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
+53
View File
@@ -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(<App />);
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<string, number> = { ...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;
@@ -13,6 +13,7 @@ function json(body: unknown, status = 200): Response {
interface Options {
connection: { address: string | null; hasApiKey: boolean };
saveResponse?: Promise<Response>;
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<Response>((resolve) => {
resolveSave = resolve;
});
const { putBodies } = installFetch('jellyfin', {
connection: { address: 'http://jf:8096', hasApiKey: true },
saveResponse
});
render(<RemoteConnectionEditScreen family="jellyfin" />);
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 } });
+12 -2
View File
@@ -158,17 +158,27 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit
<Card title={<h3>Connection</h3>} subtitle={`${meta.label} server address and API key.`}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 480 }}>
<Input
disabled={saving}
label="Address"
value={draft.address}
onChange={(event) => 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}
/>
<Input
disabled={saving}
label="API key"
type="password"
value={draft.apiKey}
onChange={(event) => 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}
/>