Merge remote-tracking branch 'origin/main' into feat/253-pr3-diff-scalar
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m21s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m12s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled
Build ErsatzTV Image / Build & test (.NET) (push) Has been cancelled
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Has been cancelled

# Conflicts:
#	docs/decisions.md
This commit was merged in pull request #270.
This commit is contained in:
2026-07-11 20:45:22 +02:00
103 changed files with 4634 additions and 314 deletions
+20 -3
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type DecoTemplateGroup = components['schemas']['DecoTemplateGroupResponseModel'];
@@ -46,8 +46,25 @@ export function getDecoTemplateItems(id: number): Promise<DecoTemplateItem[]> {
return request<DecoTemplateItem[]>(`/api/deco-templates/${id}/items`);
}
export function replaceDecoTemplate(id: number, body: ReplaceDecoTemplateRequest): Promise<DecoTemplateWithItems> {
return request<DecoTemplateWithItems>(`/api/deco-templates/${id}`, { body, method: 'PUT' });
/** Load deco template items together with the deco template's concurrency ETag (issue #253). */
export function getDecoTemplateItemsWithMeta(id: number): Promise<ResponseWithMeta<DecoTemplateItem[]>> {
return requestWithMeta<DecoTemplateItem[]>(`/api/deco-templates/${id}/items`);
}
/**
* Replace a deco template. Pass the last-seen ETag as `If-Match` to reject a stale overwrite with
* 412; the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function replaceDecoTemplate(
id: number,
body: ReplaceDecoTemplateRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<DecoTemplateWithItems>> {
return requestWithMeta<DecoTemplateWithItems>(`/api/deco-templates/${id}`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function messageFromDecoTemplateError(error: unknown, fallback = 'Unable to load deco templates'): string {
+7
View File
@@ -1094,6 +1094,7 @@ export interface components {
"buildStatus": null | components["schemas"]["PlayoutBuildStatusResponseModel"];
"decoId": null | number;
"decoName": null | string;
"isLocked": boolean;
};
"PlayoutScheduleKind": "None" | "Classic" | "Block" | "Sequential" | "Scripted" | "ExternalJson";
"PlayoutSettingsResponseModel": {
@@ -1154,6 +1155,7 @@ export interface components {
"shuffleScheduleItems": boolean;
"randomStartPoint": boolean;
"fixedStartTimeBehavior": components["schemas"]["FixedStartTimeBehavior"];
"version": number;
};
"RemoteConnectionResponseModel": {
"address": null | string;
@@ -1244,6 +1246,11 @@ export interface components {
"selectedName": null | string;
"firstRunPlaybackOrder": components["schemas"]["PlaybackOrder"];
"rerunPlaybackOrder": components["schemas"]["PlaybackOrder"];
};
"ResetAllPlayoutsResponseModel": {
"queuedPlayoutIds": Array<number>;
"skippedLocked": Array<number>;
"skippedUnsupported": Array<number>;
};
"ResolutionResponseModel": {
"id": number;
+20 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { scanLibrary, scanShow } from './libraries';
import { scanCollections, scanLibrary, scanShow } from './libraries';
function noContent(): Response {
return new Response(null, { status: 200 });
@@ -22,6 +22,25 @@ describe('libraries api client', () => {
expect(fetchMock).toHaveBeenCalledWith('/api/libraries/4/scan', expect.objectContaining({ method: 'POST' }));
});
it('scanLibrary appends ?deep=true for a deep scan', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await scanLibrary(4, true);
expect(fetchMock).toHaveBeenCalledWith('/api/libraries/4/scan?deep=true', expect.objectContaining({ method: 'POST' }));
});
it('scanCollections POSTs to the media-source scan-collections endpoint', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await scanCollections('jellyfin', 7);
expect(fetchMock).toHaveBeenCalledWith('/api/media-sources/jellyfin/7/scan-collections', expect.objectContaining({ method: 'POST' }));
});
it('scanCollections appends ?deep=true for a deep scan', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await scanCollections('plex', 3, true);
const { url } = lastCall(fetchMock);
expect(url).toBe('/api/media-sources/plex/3/scan-collections?deep=true');
});
it('scanShow POSTs the show id and deepScan flag', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await scanShow(4, { deepScan: true, showId: 42 });
+129 -9
View File
@@ -16,7 +16,7 @@ export type LibrariesScreenQueryState =
data: LibrariesScreenData;
error: string | null;
refresh: () => void;
scanLibrary: (libraryId: number) => Promise<void>;
scanLibrary: (libraryId: number, deep?: boolean) => Promise<void>;
scanningLibraryIds: Set<number>;
status: 'success';
}
@@ -42,8 +42,24 @@ export function getLibraryScanStatus(): Promise<LibraryScanStatus[]> {
);
}
export function scanLibrary(libraryId: number): Promise<void> {
return request<void>(`/api/libraries/${libraryId}/scan`, { method: 'POST' });
// Queues a library scan. `deep` requests a deep (force-metadata) scan — the API equivalent of the
// legacy Blazor "Deep Scan Library" button (#235 F9); omit or pass false for a quick scan. Returns
// 202 when queued, 404 (missing), 409 (already scanning), 422 (sync disabled) — see §3b.
export function scanLibrary(libraryId: number, deep = false): Promise<void> {
const query = deep ? '?deep=true' : '';
return request<void>(`/api/libraries/${libraryId}/scan${query}`, { method: 'POST' });
}
// Media-source families that support an external-collections scan (#235 F9). Matches the three
// media-source controllers #202 introduced.
export type CollectionsScanSource = 'emby' | 'jellyfin' | 'plex';
// Queues an external-collections scan for a Plex/Jellyfin/Emby media source — the API equivalent of
// the legacy Blazor "Scan Collections" button (#235 F9). `deep` requests a deep scan. Returns 202
// when queued, 404 (source missing), 409 (a collections scan is already running for that source).
export function scanCollections(source: CollectionsScanSource, sourceId: number, deep = false): Promise<void> {
const query = deep ? '?deep=true' : '';
return request<void>(`/api/media-sources/${source}/${sourceId}/scan-collections${query}`, { method: 'POST' });
}
export interface ScanShowParams {
@@ -51,9 +67,11 @@ export interface ScanShowParams {
deepScan?: boolean;
}
// Queues a scan of a single show (by id) within a library. Returns 200 on success, 404 when the
// show id doesn't exist in the library, 400 when the library doesn't support single-show
// scanning. Body keys are `showId` and `deepScan` (see LibrariesController.ScanShowRequest).
// Queues a scan of a single show (by id) within a library. Returns 202 when queued, 404 when the
// show id doesn't exist in the library, 409 when a scan is already running, and 422 when the
// library doesn't support single-show scanning / sync is disabled / the scan failed to start (all
// error bodies are ProblemDetails; #235 normalized the old conflated 400). Body keys are `showId`
// and `deepScan` (see LibrariesController.ScanShowRequest).
export function scanShow(libraryId: number, params: ScanShowParams): Promise<void> {
return request<void>(`/api/libraries/${libraryId}/scan-show`, {
body: { deepScan: params.deepScan ?? false, showId: params.showId },
@@ -297,9 +315,10 @@ export function useLibrariesScreenQuery(pollMs = 10000): LibrariesScreenQuerySta
});
}, []);
const triggerScan = useCallback((libraryId: number): Promise<void> => {
const triggerScan = useCallback((libraryId: number, deep = false): Promise<void> => {
if (pendingIdsRef.current.has(libraryId) || activeIdsRef.current.has(libraryId)) {
// Already pending or active - ignore the duplicate submission.
// Already pending or active - ignore the duplicate submission. Quick and deep scans share the
// same per-library lock, so both affordances gate on (and reconcile through) this one id set.
return Promise.resolve();
}
@@ -320,7 +339,7 @@ export function useLibrariesScreenQuery(pollMs = 10000): LibrariesScreenQuerySta
};
});
return scanLibrary(libraryId)
return scanLibrary(libraryId, deep)
.then(() => {
// 202 Accepted - a scan is genuinely queued. Poll scan-status; the pending flag is
// promoted to "active" once the scan appears there.
@@ -381,6 +400,107 @@ export function useLibrariesScreenQuery(pollMs = 10000): LibrariesScreenQuerySta
return { data: null, error: null, refresh, status: 'loading' };
}
// --- External collections scan (Plex/Jellyfin/Emby) ---
// A pending collections scan re-enables its button after this bound. Unlike library scans, an
// external-collections scan has NO authoritative "in progress" REST surface: /api/libraries/scan-status
// is library-keyed, and Blazor only ever observed collections locks through in-process IEntityLocker
// events (Are{X}CollectionsLocked) that have no HTTP mirror. So we can't reconcile "pending" against a
// live active set the way library scans do - we optimistically disable, then give up after this bound
// so a button can't wedge disabled forever. (A collections scan-status endpoint would let us reconcile
// properly - see the #91b follow-up note.)
const COLLECTIONS_PENDING_TIMEOUT_MS = 30000;
export interface CollectionsScanState {
error: string | null;
scan: (source: CollectionsScanSource, sourceId: number, deep: boolean) => Promise<void>;
scanningKeys: Set<string>;
}
// Stable key for a per-(family, source) collections scan, used by both the hook and the screen so the
// "is this row scanning?" lookup has exactly one definition.
export function collectionsScanKey(source: CollectionsScanSource, sourceId: number): string {
return `${source}:${sourceId}`;
}
export function useCollectionsScan(): CollectionsScanState {
const [scanningKeys, setScanningKeys] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
// Mirror kept in sync synchronously so scan() can guard double-submits without waiting for a render.
const scanningKeysRef = useRef<Set<string>>(new Set());
const timeoutsRef = useRef<Map<string, number>>(new Map());
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
// Identity is stable across the hook's life (we only .set/.delete entries, never reassign the
// Map), so capturing it here is the same instance the cleanup clears at unmount.
const timeouts = timeoutsRef.current;
return () => {
activeRef.current = false;
timeouts.forEach((timeoutId) => window.clearTimeout(timeoutId));
timeouts.clear();
};
}, []);
const clearKey = useCallback((key: string) => {
const timeoutId = timeoutsRef.current.get(key);
if (timeoutId !== undefined) {
window.clearTimeout(timeoutId);
timeoutsRef.current.delete(key);
}
const next = new Set(scanningKeysRef.current);
next.delete(key);
scanningKeysRef.current = next;
if (activeRef.current) {
setScanningKeys(next);
}
}, []);
const scan = useCallback(
(source: CollectionsScanSource, sourceId: number, deep: boolean): Promise<void> => {
const key = collectionsScanKey(source, sourceId);
if (scanningKeysRef.current.has(key)) {
// Already pending - ignore the duplicate submission (quick and deep share the source lock).
return Promise.resolve();
}
const pending = new Set(scanningKeysRef.current).add(key);
scanningKeysRef.current = pending;
setScanningKeys(pending);
setError(null);
const timeoutId = window.setTimeout(() => clearKey(key), COLLECTIONS_PENDING_TIMEOUT_MS);
timeoutsRef.current.set(key, timeoutId);
return scanCollections(source, sourceId, deep)
.then(() => {
// 202 Accepted - a scan is genuinely queued. Keep the button disabled until the bounded
// timeout expires (there is no completion signal to reconcile against).
})
.catch((err: unknown) => {
if (err instanceof ApiError && err.status === 409) {
// 409 Conflict - a collections scan is already running for this source. Benign: keep the
// optimistic pending flag (button stays disabled) with no error; it clears on the timeout.
return;
}
// 404 (source missing) / network error - nothing was queued, so re-enable and surface it.
clearKey(key);
if (activeRef.current) {
setError(messageFromLibrariesError(err, 'Unable to scan collections'));
}
});
},
[clearKey]
);
return { error, scan, scanningKeys };
}
function messageFromLibrariesError(error: unknown, fallback = 'Unable to load libraries'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
+19 -4
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type AddItemsToPlaylistRequest = components['schemas']['AddItemsToPlaylistRequest'];
@@ -41,13 +41,28 @@ export function getPlaylistItems(id: number): Promise<PlaylistItem[]> {
return request<PlaylistItem[]>(`/api/playlists/${id}/items`);
}
/** Load playlist items together with the playlist's concurrency ETag (issue #253). */
export function getPlaylistItemsWithMeta(id: number): Promise<ResponseWithMeta<PlaylistItem[]>> {
return requestWithMeta<PlaylistItem[]>(`/api/playlists/${id}/items`);
}
export function createPlaylist(body: CreatePlaylistRequest): Promise<Playlist> {
return request<Playlist>('/api/playlists', { body, method: 'POST' });
}
// PUT = rename + replace the full item list; returns the persisted (re-indexed) items.
export function updatePlaylist(id: number, body: ReplacePlaylistRequest): Promise<PlaylistItem[]> {
return request<PlaylistItem[]>(`/api/playlists/${id}`, { body, method: 'PUT' });
// PUT = rename + replace the full item list; returns the persisted (re-indexed) items. Pass the
// last-seen ETag as `If-Match` to reject a stale overwrite with 412; the resolved value carries
// the new ETag for a subsequent save (issue #253).
export function updatePlaylist(
id: number,
body: ReplacePlaylistRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<PlaylistItem[]>> {
return requestWithMeta<PlaylistItem[]>(`/api/playlists/${id}`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function deletePlaylist(id: number): Promise<void> {
+7 -2
View File
@@ -108,8 +108,13 @@ export function getPlayoutChannelStates(): Promise<PlayoutChannelState[]> {
return request<PlayoutChannelState[]>('/api/channels/state');
}
export function resetAllPlayouts(): Promise<void> {
return request<void>('/api/playouts/reset-all', { method: 'POST' });
export type ResetAllPlayoutsResult = components['schemas']['ResetAllPlayoutsResponseModel'];
// Queues a reset of every eligible playout. Returns 202 with a body reporting which playouts were
// queued vs skipped (locked, or an unsupported ExternalJson/None schedule kind) — #235 replaced the
// old silent skip. The caller may surface `skipped*` to explain why some playouts didn't reset.
export function resetAllPlayouts(): Promise<ResetAllPlayoutsResult> {
return request<ResetAllPlayoutsResult>('/api/playouts/reset-all', { method: 'POST' });
}
export function deletePlayout(playoutId: number): Promise<void> {
+20 -6
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
// FillerPreset is exported by ./pickers — import (don't re-export) to avoid a duplicate `export *`
// name in api/index.ts. LanguageCode/getLanguages moved to ./languages (also re-exported via
@@ -46,17 +46,31 @@ export function getScheduleItems(scheduleId: number): Promise<ScheduleItemsRespo
return request<ScheduleItemsResponse>(`/api/schedules/${scheduleId}/items`);
}
/** Load schedule items together with the schedule's concurrency ETag (issue #253). */
export function getScheduleItemsWithMeta(
scheduleId: number
): Promise<ResponseWithMeta<ScheduleItemsResponse>> {
return requestWithMeta<ScheduleItemsResponse>(`/api/schedules/${scheduleId}/items`);
}
export function addScheduleItem(scheduleId: number, body: ScheduleItemRequest): Promise<ScheduleItem> {
return request<ScheduleItem>(`/api/schedules/${scheduleId}/items`, { body, method: 'POST' });
}
// Destructive replace: the server deletes+recreates every item row (new ids) and triggers playout
// rebuilds. The editor batches all local draft edits into this single call. See docs/decisions.md.
// Positional in-place reconcile: the server reuses same-typed item rows (keeping fill-group state) and
// triggers playout rebuilds. The editor batches all local draft edits into this single call. Pass the
// last-seen ETag as `If-Match` to reject a stale overwrite with 412; the resolved value carries the new
// ETag for a subsequent save (issue #253). See docs/decisions.md.
export function replaceScheduleItems(
scheduleId: number,
body: ReplaceScheduleItemsRequest
): Promise<ScheduleItem[]> {
return request<ScheduleItem[]>(`/api/schedules/${scheduleId}/items`, { body, method: 'PUT' });
body: ReplaceScheduleItemsRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<ScheduleItem[]>> {
return requestWithMeta<ScheduleItem[]>(`/api/schedules/${scheduleId}/items`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function deleteScheduleItem(scheduleId: number, itemId: number): Promise<void> {
+20 -3
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type TemplateGroup = components['schemas']['TemplateGroupResponseModel'];
@@ -47,8 +47,25 @@ export function getTemplateItems(id: number): Promise<TemplateItem[]> {
return request<TemplateItem[]>(`/api/templates/${id}/items`);
}
export function replaceTemplate(id: number, body: ReplaceTemplateRequest): Promise<TemplateWithItems> {
return request<TemplateWithItems>(`/api/templates/${id}`, { body, method: 'PUT' });
/** Load template items together with the template's concurrency ETag (issue #253). */
export function getTemplateItemsWithMeta(id: number): Promise<ResponseWithMeta<TemplateItem[]>> {
return requestWithMeta<TemplateItem[]>(`/api/templates/${id}/items`);
}
/**
* Replace a template. Pass the last-seen ETag as `If-Match` to reject a stale overwrite with 412;
* the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function replaceTemplate(
id: number,
body: ReplaceTemplateRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<TemplateWithItems>> {
return requestWithMeta<TemplateWithItems>(`/api/templates/${id}`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function copyTemplate(id: number, body: CopyTemplateRequest): Promise<Template> {
@@ -185,4 +185,42 @@ describe('DecoTemplatesScreen', () => {
expect(screen.queryByText(/must start before it ends/)).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save deco template/ })).not.toBeDisabled();
});
it('shows a conflict dialog and reloads when the deco template changed elsewhere (412)', async () => {
window.history.pushState({}, '', '/app/deco-templates/4');
let putCount = 0;
const fetchMock = mockApi({
items: [{ decoId: 10, decoName: 'Sunrise', startTime: '06:00:00', endTime: '07:00:00' }],
onRequest: (url, method) => {
if (url === '/api/deco-templates/4' && method === 'PUT') {
putCount += 1;
if (putCount === 1) {
return new Response(
JSON.stringify({ status: 412, title: 'Precondition Failed', detail: 'stale' }),
{ headers: { 'Content-Type': 'application/json' }, status: 412 }
);
}
}
return null;
}
});
render(<DecoTemplatesScreen />);
await waitFor(() => expect(screen.getByDisplayValue('Bumpers')).toBeInTheDocument());
const itemsGetCount = () =>
fetchMock.mock.calls.filter(
([u, init]) => u === '/api/deco-templates/4/items' && (init?.method ?? 'GET') === 'GET'
).length;
const before = itemsGetCount();
fireEvent.click(screen.getByRole('button', { name: /Save deco template/ }));
// A 412 opens the "changed elsewhere" dialog rather than showing a generic save error.
expect(await screen.findByText(/Reload to get the latest version/i)).toBeInTheDocument();
// Reloading re-fetches the deco template items.
fireEvent.click(screen.getByRole('button', { name: /^Reload$/ }));
await waitFor(() => expect(itemsGetCount()).toBeGreaterThan(before));
});
});
+61 -22
View File
@@ -3,6 +3,7 @@ import { ArrowLeft, Check, FolderPlus, Plus, Trash2, TriangleAlert } from 'lucid
import { navigateToPath } from '../routing';
import { Badge, Button, Card, ConfirmDialog, Dialog, IconButton, Input, Select, Spinner } from '../components';
import {
ApiError,
createDecoTemplate,
createDecoTemplateGroup,
deleteDecoTemplate,
@@ -10,7 +11,7 @@ import {
getDecoGroups,
getDecoTemplate,
getDecoTemplateGroups,
getDecoTemplateItems,
getDecoTemplateItemsWithMeta,
getDecoTemplates,
getDecos,
messageFromDecoTemplateError,
@@ -477,6 +478,11 @@ function DecoTemplateEditor({ decoTemplateId }: { decoTemplateId: number }) {
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
// Concurrency ETag (issue #253): captured from the items GET, sent as If-Match on save, and
// replaced from the PUT response on every successful save.
const etagRef = useRef<string | null>(null);
const [addGroupId, setAddGroupId] = useState('');
const [addDecoId, setAddDecoId] = useState('');
@@ -487,34 +493,38 @@ function DecoTemplateEditor({ decoTemplateId }: { decoTemplateId: number }) {
useEffect(() => {
let active = true;
Promise.all([
getDecoTemplate(decoTemplateId),
getDecoTemplateItems(decoTemplateId),
getDecoGroups(),
getDecos()
])
.then(([decoTemplateData, items, groupData, decoData]) => {
// Read items + ETag FIRST, then the root metadata, mirroring BlockEditor (issue #253): the ETag
// must be no newer than every piece of versioned data the draft is built from.
void (async () => {
try {
const itemsMeta = await getDecoTemplateItemsWithMeta(decoTemplateId);
const [decoTemplateData, groupData, decoData] = await Promise.all([
getDecoTemplate(decoTemplateId),
getDecoGroups(),
getDecos()
]);
if (!active) {
return;
}
etagRef.current = itemsMeta.etag;
setDecoTemplate(decoTemplateData);
setDecoGroups(groupData);
setDecos(decoData);
setDraft({
name: decoTemplateData.name,
items: items.map(itemFromResponse)
items: itemsMeta.data.map(itemFromResponse)
});
})
.catch((error: unknown) => {
} catch (error) {
if (active) {
setLoadError(messageFromDecoTemplateError(error, 'Unable to load deco template'));
}
});
}
})();
return () => {
active = false;
};
}, [decoTemplateId]);
}, [decoTemplateId, reloadKey]);
if (loadError) {
return (
@@ -590,22 +600,40 @@ function DecoTemplateEditor({ decoTemplateId }: { decoTemplateId: number }) {
setSaving(true);
setSaveError(null);
try {
await replaceDecoTemplate(decoTemplateId, {
name: draft.name.trim(),
items: draft.items.map((item) => ({
decoId: item.decoId,
startTime: item.startTime,
endTime: item.endTime
}))
});
const { etag } = await replaceDecoTemplate(
decoTemplateId,
{
name: draft.name.trim(),
items: draft.items.map((item) => ({
decoId: item.decoId,
startTime: item.startTime,
endTime: item.endTime
}))
},
etagRef.current
);
etagRef.current = etag;
navigateToPath(BASE_PATH);
} catch (error) {
setSaveError(messageFromDecoTemplateError(error, 'Unable to save deco template'));
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
} else {
setSaveError(messageFromDecoTemplateError(error, 'Unable to save deco template'));
}
} finally {
setSaving(false);
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setDraft(null);
setDecoTemplate(null);
setReloadKey((key) => key + 1);
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
@@ -758,6 +786,17 @@ function DecoTemplateEditor({ decoTemplateId }: { decoTemplateId: number }) {
</table>
)}
</Card>
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This deco template was changed elsewhere since you opened it. Reload to get the latest version — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Deco template changed elsewhere"
tone="danger"
/>
</div>
);
}
+155 -1
View File
@@ -74,7 +74,14 @@ function mockApi(options: MockOptions = {}): MockHandle {
return Promise.resolve(jsonResponse(options.libraryScanStatuses ?? []));
}
if (/^\/api\/libraries\/\d+\/scan$/.test(url) && method === 'POST') {
if (/^\/api\/libraries\/\d+\/scan(\?deep=true)?$/.test(url) && method === 'POST') {
if (url in mutationFailures) {
return Promise.resolve(jsonResponse(mutationFailures[url], mutationFailures[url].status ?? 422));
}
return Promise.resolve(new Response(null, { status: 202 }));
}
if (/^\/api\/media-sources\/(plex|jellyfin|emby)\/\d+\/scan-collections(\?deep=true)?$/.test(url) && method === 'POST') {
if (url in mutationFailures) {
return Promise.resolve(jsonResponse(mutationFailures[url], mutationFailures[url].status ?? 422));
}
@@ -369,6 +376,153 @@ describe('LibrariesScreen', () => {
expect(await screen.findByText('No media sources returned')).toBeInTheDocument();
});
describe('deep scan + external collections (#91b Libraries.razor parity)', () => {
// A remote source with two sync-enabled libraries (deep-scan available) plus an External
// Collections row; a Local source (no deep, no collections row); and a remote source with NO
// sync-enabled libraries (no External Collections row).
function paritySources(): unknown[] {
return [
mediaSource({
id: 30,
kind: 'Local',
libraries: [library({ id: 31, mediaKind: 'Movies', name: 'Movies' })],
name: 'Local'
}),
mediaSource({
connectionAddress: 'https://plex.example.test',
id: 40,
kind: 'Plex',
libraries: [library({ id: 41, mediaKind: 'Shows', name: 'TV Shows' })],
name: 'Plex Server'
}),
mediaSource({
connectionAddress: 'https://jellyfin.example.test',
id: 50,
kind: 'Jellyfin',
libraries: [],
name: 'Jellyfin Home'
})
];
}
it('deep-scans a remote library via POST /api/libraries/{id}/scan?deep=true', async () => {
const handle = mockApi({ mediaSources: paritySources() });
render(<LibrariesScreen />);
await screen.findByText('TV Shows');
fireEvent.click(screen.getByRole('button', { name: 'Deep scan TV Shows' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/41/scan?deep=true', expect.objectContaining({ method: 'POST' }));
});
expect(fetchCount(handle, '/api/libraries/41/scan')).toBe(0);
});
it('offers a deep-scan button only for remote libraries, never Local', async () => {
mockApi({ mediaSources: paritySources() });
render(<LibrariesScreen />);
await screen.findByText('TV Shows');
// Local library "Movies" has a quick scan but no deep scan.
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Deep scan Movies' })).not.toBeInTheDocument();
// Remote library "TV Shows" has both.
expect(screen.getByRole('button', { name: 'Scan TV Shows' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Deep scan TV Shows' })).toBeInTheDocument();
});
it('renders an External Collections row only for remote sources with sync-enabled libraries', async () => {
mockApi({ mediaSources: paritySources() });
render(<LibrariesScreen />);
await screen.findByText('TV Shows');
expect(screen.getByRole('heading', { name: 'External Collections' })).toBeInTheDocument();
// Plex Server has a sync-enabled library → a collections row.
expect(screen.getByRole('button', { name: 'Scan Plex Server collections' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Deep scan Plex Server collections' })).toBeInTheDocument();
// Jellyfin Home has no sync-enabled library → no collections row; Local never gets one.
expect(screen.queryByRole('button', { name: 'Scan Jellyfin Home collections' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Scan Local collections' })).not.toBeInTheDocument();
});
it('omits the External Collections section entirely when no remote source has sync-enabled libraries', async () => {
mockApi({
mediaSources: [
mediaSource({ id: 30, kind: 'Local', libraries: [library({ id: 31, name: 'Movies' })], name: 'Local' })
]
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
expect(screen.queryByRole('heading', { name: 'External Collections' })).not.toBeInTheDocument();
});
it('queues a quick collections scan via POST /api/media-sources/{family}/{id}/scan-collections', async () => {
const handle = mockApi({ mediaSources: paritySources() });
render(<LibrariesScreen />);
await screen.findByRole('button', { name: 'Scan Plex Server collections' });
fireEvent.click(screen.getByRole('button', { name: 'Scan Plex Server collections' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/media-sources/plex/40/scan-collections', expect.objectContaining({ method: 'POST' }));
});
// The button is optimistically disabled while the scan is pending.
expect(screen.getByRole('button', { name: 'Scan Plex Server collections' })).toBeDisabled();
});
it('queues a deep collections scan with ?deep=true', async () => {
const handle = mockApi({ mediaSources: paritySources() });
render(<LibrariesScreen />);
await screen.findByRole('button', { name: 'Deep scan Plex Server collections' });
fireEvent.click(screen.getByRole('button', { name: 'Deep scan Plex Server collections' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/media-sources/plex/40/scan-collections?deep=true', expect.objectContaining({ method: 'POST' }));
});
});
it('treats a 409 "already scanning" collections response as benign (button stays disabled, no error)', async () => {
mockApi({
mediaSources: paritySources(),
mutationFailures: { '/api/media-sources/plex/40/scan-collections': { status: 409 } }
});
render(<LibrariesScreen />);
await screen.findByRole('button', { name: 'Scan Plex Server collections' });
fireEvent.click(screen.getByRole('button', { name: 'Scan Plex Server collections' }));
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Scan Plex Server collections' })).toBeDisabled();
});
expect(screen.queryByText(/Unable to scan collections/)).not.toBeInTheDocument();
expect(screen.queryByText(/Request failed/)).not.toBeInTheDocument();
});
it('surfaces a collections scan failure and re-enables the button', async () => {
mockApi({
mediaSources: paritySources(),
mutationFailures: { '/api/media-sources/plex/40/scan-collections': { status: 404 } }
});
render(<LibrariesScreen />);
await screen.findByRole('button', { name: 'Scan Plex Server collections' });
fireEvent.click(screen.getByRole('button', { name: 'Scan Plex Server collections' }));
expect(await screen.findByText('Request failed with status 404')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Plex Server collections' })).not.toBeDisabled();
});
});
describe('hub wiring (slice S5)', () => {
it('Add Source menu navigates to the local-new and each family route', async () => {
const pushSpy = vi.spyOn(window.history, 'pushState');
+102 -2
View File
@@ -6,11 +6,13 @@ import {
Film,
Folder,
HardDrive,
Library,
MonitorPlay,
Music,
Plus,
Radio,
RefreshCw,
ScanSearch,
Server,
Settings,
TriangleAlert
@@ -25,7 +27,10 @@ import {
StatusDot
} from '../components';
import {
collectionsScanKey,
useCollectionsScan,
useLibrariesScreenQuery,
type CollectionsScanSource,
type LibraryScanStatus,
type MediaSource,
type MediaSourceLibrary
@@ -41,6 +46,7 @@ import {
export function LibrariesScreen() {
const query = useLibrariesScreenQuery();
const collectionsScan = useCollectionsScan();
if (query.status === 'loading') {
return <LibrariesLoadingState />;
@@ -60,6 +66,21 @@ export function LibrariesScreen() {
);
const scanStatusesByLibraryId = new Map(query.data.scanStatuses.map((status) => [status.libraryId, status]));
// External Collections mirrors Blazor Libraries.razor's second table: one row per Plex/Jellyfin/Emby
// source that has at least one sync-enabled library. GetAllMediaSourcesForApiHandler already filters
// each source's `libraries` to sync-enabled entries (ShouldIncludeLibrary), so a remote source with a
// non-empty `libraries` list is exactly the `Libraries.Any(ShouldSyncItems)` filter GetExternalCollections
// applies - no separate endpoint needed.
const collectionsRows = query.data.sources
.map((source) => {
const family = parseRemoteFamily(source.kind);
if (family === null || source.libraries.length === 0) {
return null;
}
return { family, name: source.name, sourceId: source.id };
})
.filter((row): row is { family: CollectionsScanSource; name: string; sourceId: number } => row !== null);
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
@@ -97,10 +118,81 @@ export function LibrariesScreen() {
/>
))}
</div>
{collectionsRows.length > 0 && (
<ExternalCollectionsSection
error={collectionsScan.error}
onScanCollections={collectionsScan.scan}
rows={collectionsRows}
scanningKeys={collectionsScan.scanningKeys}
/>
)}
</div>
);
}
// External Collections table (parity with Blazor Libraries.razor's second table). Each row is a
// remote source with sync-enabled libraries; the quick/deep buttons queue that source's collections
// scan. There is no scan-status poll surface for collections (see useCollectionsScan), so a row's
// "scanning" state is optimistic and bounded by a timeout rather than reconciled against a live set.
function ExternalCollectionsSection({
error,
onScanCollections,
rows,
scanningKeys
}: {
error: string | null;
onScanCollections: (source: CollectionsScanSource, sourceId: number, deep: boolean) => Promise<void>;
rows: Array<{ family: CollectionsScanSource; name: string; sourceId: number }>;
scanningKeys: Set<string>;
}) {
return (
<section className="ctv-library-source-card" aria-label="External collections">
<div className="ctv-library-source-head">
<span className="ctv-library-kind-icon"><Library aria-hidden="true" size={18} /></span>
<div>
<div className="ctv-library-source-title">
<h3>External Collections</h3>
</div>
<span>Sync Plex, Jellyfin, and Emby collections into ErsatzTV.</span>
</div>
</div>
{error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
)}
<div className="ctv-library-list" role="list" aria-label="External collections list">
{rows.map((row) => {
const scanning = scanningKeys.has(collectionsScanKey(row.family, row.sourceId));
return (
<div className="ctv-library-row" key={collectionsScanKey(row.family, row.sourceId)} role="listitem">
<span className={`ctv-library-kind-icon ctv-library-kind-${row.family}`}><Server aria-hidden="true" size={16} /></span>
<div className="ctv-library-row-main">
<strong>{row.name}</strong>
<span>{familyLabel(row.family)} collections</span>
</div>
<div className="ctv-library-row-status">
{scanning ? <Badge tone="accent" dot>Scanning</Badge> : <Badge tone="ok" dot>Idle</Badge>}
<IconButton disabled={scanning} onClick={() => void onScanCollections(row.family, row.sourceId, true)} size="sm" title={`Deep scan ${row.name} collections`}>
<ScanSearch aria-hidden="true" size={15} />
</IconButton>
<IconButton disabled={scanning} onClick={() => void onScanCollections(row.family, row.sourceId, false)} size="sm" title={`Scan ${row.name} collections`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
</div>
</div>
);
})}
</div>
</section>
);
}
// "Add Source" dropdown: Local library opens the create editor; each remote family opens its screen.
// Mirrors the AddToMenu popover pattern (click-outside + Escape close). Navigation goes through
// navigateToPath, which App's popstate owner turns into the right libraries sub-path (design §D.2).
@@ -203,7 +295,7 @@ function MediaSourceCard({
scanningLibraryIds,
source
}: {
onScanLibrary: (libraryId: number) => Promise<void>;
onScanLibrary: (libraryId: number, deep?: boolean) => Promise<void>;
scanStatusesByLibraryId: Map<number, LibraryScanStatus>;
scanningLibraryIds: Set<number>;
source: MediaSource;
@@ -250,6 +342,7 @@ function MediaSourceCard({
) : source.libraries.map((library) => (
<LibraryRow
key={library.id}
allowDeepScan={!isLocal}
editable={isLocal}
library={library}
onScanLibrary={onScanLibrary}
@@ -268,15 +361,17 @@ function MediaSourceCard({
}
function LibraryRow({
allowDeepScan,
editable,
library,
onScanLibrary,
scanStatus,
scanning
}: {
allowDeepScan: boolean;
editable: boolean;
library: MediaSourceLibrary;
onScanLibrary: (libraryId: number) => Promise<void>;
onScanLibrary: (libraryId: number, deep?: boolean) => Promise<void>;
scanStatus: LibraryScanStatus | null;
scanning: boolean;
}) {
@@ -300,6 +395,11 @@ function LibraryRow({
) : (
<Badge tone="ok" dot>Synced</Badge>
)}
{allowDeepScan && (
<IconButton disabled={disabled} onClick={() => void onScanLibrary(library.id, true)} size="sm" title={`Deep scan ${library.name}`}>
<ScanSearch aria-hidden="true" size={15} />
</IconButton>
)}
<IconButton disabled={disabled} onClick={() => void onScanLibrary(library.id)} size="sm" title={`Scan ${library.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
+38
View File
@@ -206,6 +206,44 @@ describe('PlaylistsScreen', () => {
});
});
it('shows a conflict dialog and reloads when the playlist changed elsewhere (412)', async () => {
let putCount = 0;
const fetchMock = mockApi({
onRequest: (url, method) => {
if (url === '/api/playlists/10' && method === 'PUT') {
putCount += 1;
if (putCount === 1) {
return new Response(
JSON.stringify({ status: 412, title: 'Precondition Failed', detail: 'stale' }),
{ headers: { 'Content-Type': 'application/json' }, status: 412 }
);
}
return jsonResponse([], 200);
}
return null;
}
});
render(<PlaylistsScreen />);
fireEvent.click(await screen.findByText('Bumps'));
expect(await screen.findByText('Favorites')).toBeInTheDocument();
const itemsGetCount = () =>
fetchMock.mock.calls.filter(([u, init]) => u === '/api/playlists/10/items' && (init?.method ?? 'GET') === 'GET')
.length;
const before = itemsGetCount();
fireEvent.click(screen.getByRole('button', { name: 'Save playlist' }));
// A 412 opens the "changed elsewhere" dialog rather than showing a generic save error.
expect(await screen.findByText(/Reload to get the latest version/i)).toBeInTheDocument();
// Reloading re-fetches the playlist items.
fireEvent.click(screen.getByRole('button', { name: /^Reload$/ }));
await waitFor(() => expect(itemsGetCount()).toBeGreaterThan(before));
});
it('disables the playback-order select for single media-item types', async () => {
mockApi();
render(<PlaylistsScreen />);
+47 -7
View File
@@ -18,6 +18,7 @@ import {
import { Badge, Button, Card, ConfirmDialog, Dialog, IconButton, Input, Select, Spinner, Switch } from '../components';
import type { SelectOption } from '../components';
import {
ApiError,
createPlaylist,
createPlaylistGroup,
deletePlaylist,
@@ -27,7 +28,7 @@ import {
getMultiCollections,
getPlaylistById,
getPlaylistGroups,
getPlaylistItems,
getPlaylistItemsWithMeta,
getPlaylists,
getSmartCollections,
messageFromPlaylistError,
@@ -379,17 +380,32 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
const [previewItems, setPreviewItems] = useState<PlaylistPreviewItem[] | null>(null);
const [previewMessage, setPreviewMessage] = useState<string | null>(null);
const [previewing, setPreviewing] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const activeRef = useRef(true);
// Concurrency ETag (issue #253): captured from the items GET, sent as If-Match on save, and
// replaced from the PUT response on every successful save.
const etagRef = useRef<string | null>(null);
useEffect(() => {
activeRef.current = true;
Promise.all([getPlaylistById(playlistId), getPlaylistItems(playlistId)])
.then(([playlist, loaded]) => {
// Read items + ETag FIRST, then the root metadata, so the ETag is never newer than the data
// the draft is built from (issue #253) — any resulting inconsistency fails safe via a 412 on
// save rather than a silent overwrite. These MUST be sequential, not Promise.all: a concurrent
// root read could return a stale name paired with the current items ETag, and a later save would
// then silently restore that stale name.
getPlaylistItemsWithMeta(playlistId)
.then(async (itemsMeta) => {
const playlist = await getPlaylistById(playlistId);
return [itemsMeta, playlist] as const;
})
.then(([itemsMeta, playlist]) => {
if (!activeRef.current) {
return;
}
const drafts = loaded.map(draftFromItem);
etagRef.current = itemsMeta.etag;
const drafts = itemsMeta.data.map(draftFromItem);
setName(playlist.name);
setItems(drafts);
setSelectedKey(drafts.length === 1 ? drafts[0].key : null);
@@ -404,7 +420,7 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
return () => {
activeRef.current = false;
};
}, [playlistId]);
}, [playlistId, reloadKey]);
const selectedItem = items.find((item) => item.key === selectedKey) ?? null;
const selectedType = selectedItem?.collectionType;
@@ -506,15 +522,28 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
setSaveError(null);
try {
await updatePlaylist(playlistId, buildRequest());
const { etag } = await updatePlaylist(playlistId, buildRequest(), etagRef.current);
etagRef.current = etag;
onSaved();
} catch (error) {
setSaveError(messageFromPlaylistError(error, 'Unable to save playlist'));
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
} else {
setSaveError(messageFromPlaylistError(error, 'Unable to save playlist'));
}
} finally {
setSaving(false);
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setState({ status: 'loading' });
setReloadKey((key) => key + 1);
};
const runPreview = async () => {
setPreviewing(true);
setPreviewMessage(null);
@@ -774,6 +803,17 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
)}
</Card>
)}
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This playlist was changed elsewhere since you opened it. Reload to get the latest version — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Playlist changed elsewhere"
tone="danger"
/>
</div>
);
}
+30
View File
@@ -267,6 +267,36 @@ describe('SchedulesScreen — error + dirty handling', () => {
expect((screen.getByRole('button', { name: /^Save$/ }) as HTMLButtonElement).disabled).toBe(false);
});
it('412 on Save opens the conflict dialog; Reload discards the draft and reloads', async () => {
let putCount = 0;
const handle = await renderReady({
onRequest: (url, method) => {
if (url === '/api/schedules/1/items' && method === 'PUT') {
putCount += 1;
return jsonResponse({ title: 'Precondition Failed', detail: 'stale' }, 412);
}
return null;
}
});
// Make dirty, then Save → 412.
fireEvent.click(screen.getByRole('button', { name: /Add item/ }));
const getsBefore = handle.requests.filter((r) => r.url === '/api/schedules/1/items' && r.method === 'GET').length;
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
// The conflict dialog appears (distinct from the generic save-error path).
await screen.findByText('Schedule changed elsewhere');
expect(putCount).toBe(1);
// Reload discards the draft and re-fetches the active schedule's items.
fireEvent.click(screen.getByRole('button', { name: /^Reload$/ }));
await waitFor(() =>
expect(handle.requests.filter((r) => r.url === '/api/schedules/1/items' && r.method === 'GET').length)
.toBeGreaterThan(getsBefore));
// Dialog closed; draft reset to the (single-item) server baseline.
await waitFor(() => expect(screen.queryByText('Schedule changed elsewhere')).toBeNull());
expect(within(screen.getByLabelText('Schedule lineup')).getAllByRole('listitem')).toHaveLength(1);
});
it('guards a schedule switch when dirty (confirm=false aborts)', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(false);
const handle = await renderReady({ schedules: [schedule, { ...schedule, id: 2, name: 'Late' }] });
+51 -6
View File
@@ -10,12 +10,13 @@ import {
Spinner
} from '../components';
import {
ApiError,
deleteSchedule,
getFillerPresetsByKind,
getLanguages,
getPlaylistGroups,
getRerunCollections,
getScheduleItems,
getScheduleItemsWithMeta,
getSchedules,
getGraphicsElements,
getWatermarks,
@@ -87,11 +88,16 @@ export function SchedulesScreen() {
const [mutationError, setMutationError] = useState<string | null>(null);
const [form, setForm] = useState<null | 'create' | 'edit'>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
// Opened when a save 412s because the schedule was changed elsewhere since it was loaded (#253).
const [conflictOpen, setConflictOpen] = useState(false);
const activeRef = useRef(true);
const dirtyRef = useRef(false);
const baselineRef = useRef<DraftItem[]>([]);
const itemSeq = useRef(0);
// Last-seen concurrency ETag: set from the items GET, replaced by every successful save's response
// ETag (a same-tab second save must use the new tag or it would 412 against its own write) (#253).
const etagRef = useRef<string | null>(null);
const setDirtyState = useCallback((value: boolean) => {
dirtyRef.current = value;
@@ -131,11 +137,13 @@ export function SchedulesScreen() {
// ---- Load items for the active schedule --------------------------------
const loadItems = useCallback((scheduleId: number) => {
const seq = ++itemSeq.current;
getScheduleItems(scheduleId)
.then((response) => {
getScheduleItemsWithMeta(scheduleId)
.then(({ data: response, etag }) => {
if (!activeRef.current || itemSeq.current !== seq) {
return;
}
// Only the current load owns the ETag (same stale-guard as the items below).
etagRef.current = etag;
// Defensive: array position becomes the persisted index on the next PUT, so ingest strictly by the
// server-provided `index` rather than trusting response row order (see #229 — the API now orders, but
// the SPA must not silently reshuffle the lineup if that guarantee ever regresses).
@@ -318,11 +326,14 @@ export function SchedulesScreen() {
}
setSaving(true);
setMutationError(null);
replaceScheduleItems(activeId, { items: items.map(normalizeForSave) })
.then((response) => {
replaceScheduleItems(activeId, { items: items.map(normalizeForSave) }, etagRef.current)
.then(({ data: response, etag }) => {
if (!activeRef.current) {
return;
}
// Load-bearing: a same-tab second save must use the ETag this write produced, or it would 412
// against its own change (#253).
etagRef.current = etag;
const drafts = [...response].sort((a, b) => a.index - b.index).map(fromResponse);
baselineRef.current = drafts;
setItems(drafts);
@@ -337,11 +348,35 @@ export function SchedulesScreen() {
if (!activeRef.current) {
return;
}
setMutationError(messageFromScheduleError(error, 'Unable to save schedule items'));
if (error instanceof ApiError && error.status === 412) {
// The schedule was changed elsewhere since we loaded it — force a reload rather than
// overwriting the fresher edit (#253). Distinct from all other errors.
setConflictOpen(true);
} else {
setMutationError(messageFromScheduleError(error, 'Unable to save schedule items'));
}
setSaving(false);
});
};
// Conflict "Reload": discard the dirty draft and re-run the load for the active schedule. loadItems
// already bumps itemSeq (stale-guard), re-seeds baselineRef, clears dirty, and captures the new ETag —
// so there's no separate reloadKey to invent (#253).
const reloadAfterConflict = () => {
setConflictOpen(false);
setMutationError(null);
if (activeId != null) {
// Mark not-loaded/loading before kicking off the reload so `canEdit` (itemsLoaded && !saving) is
// false for the whole conflict-reload window. Otherwise a slow reload GET would leave the rejected
// stale draft editable, and edits made during that window would be silently discarded when the
// reload re-seeds the baseline (issue #253 / #242 mutation gating). Set here (an event handler)
// rather than inside loadItems, which the activeId effect calls synchronously (react-hooks lint).
setItemsLoading(true);
setItemsLoaded(false);
loadItems(activeId);
}
};
// Opening the properties editor is blocked while the item draft is dirty (confirm-to-discard, same
// semantics as guardedSwitch). This is the smaller, fully-consistent fix for the shuffle-toggle
// normalization gap (#230 finding 2): if editing shuffleScheduleItems could change under a dirty
@@ -562,6 +597,16 @@ export function SchedulesScreen() {
onConfirm={onDeleteSchedule}
onCancel={() => setConfirmDelete(false)}
/>
<ConfirmDialog
open={conflictOpen}
title="Schedule changed elsewhere"
message="This schedule was changed elsewhere since you opened it. Reload to get the latest version — your unsaved changes will be discarded."
confirmLabel="Reload"
cancelLabel="Keep editing"
onConfirm={reloadAfterConflict}
onCancel={() => setConflictOpen(false)}
/>
</div>
);
}
+37
View File
@@ -242,4 +242,41 @@ describe('TemplatesScreen', () => {
expect(await screen.findByText(/overlaps/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save template/ })).toBeDisabled();
});
it('shows a conflict dialog and reloads when the template changed elsewhere (412)', async () => {
window.history.pushState({}, '', '/app/templates/4');
let putCount = 0;
const fetchMock = mockApi({
items: [{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '06:00:00' }],
onRequest: (url, method) => {
if (url === '/api/templates/4' && method === 'PUT') {
putCount += 1;
if (putCount === 1) {
return new Response(
JSON.stringify({ status: 412, title: 'Precondition Failed', detail: 'stale' }),
{ headers: { 'Content-Type': 'application/json' }, status: 412 }
);
}
}
return null;
}
});
render(<TemplatesScreen />);
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
const itemsGetCount = () =>
fetchMock.mock.calls.filter(([u, init]) => u === '/api/templates/4/items' && (init?.method ?? 'GET') === 'GET')
.length;
const before = itemsGetCount();
fireEvent.click(screen.getByRole('button', { name: /Save template/ }));
// A 412 opens the "changed elsewhere" dialog rather than showing a generic save error.
expect(await screen.findByText(/Reload to get the latest version/i)).toBeInTheDocument();
// Reloading re-fetches the template items.
fireEvent.click(screen.getByRole('button', { name: /^Reload$/ }));
await waitFor(() => expect(itemsGetCount()).toBeGreaterThan(before));
});
});
+57 -13
View File
@@ -3,6 +3,7 @@ import { ArrowLeft, Check, Copy, FolderPlus, Plus, Search, Trash2, TriangleAlert
import { navigateToPath } from '../routing';
import { Badge, Button, Card, ConfirmDialog, Dialog, IconButton, Input, Select, Spinner } from '../components';
import {
ApiError,
copyTemplate,
createTemplate,
createTemplateGroup,
@@ -12,7 +13,7 @@ import {
getBlocks,
getTemplate,
getTemplateGroups,
getTemplateItems,
getTemplateItemsWithMeta,
getTemplates,
messageFromTemplateError,
replaceTemplate,
@@ -554,6 +555,11 @@ function TemplateEditor({ templateId }: { templateId: number }) {
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
// Concurrency ETag (issue #253): captured from the items GET, sent as If-Match on save, and
// replaced from the PUT response on every successful save.
const etagRef = useRef<string | null>(null);
const [addGroupId, setAddGroupId] = useState('');
const [addBlockId, setAddBlockId] = useState('');
@@ -562,29 +568,38 @@ function TemplateEditor({ templateId }: { templateId: number }) {
useEffect(() => {
let active = true;
Promise.all([getTemplate(templateId), getTemplateItems(templateId), getBlockGroups(), getBlocks()])
.then(([templateData, items, groupData, blockData]) => {
// Read items + ETag FIRST, then the root metadata, mirroring BlockEditor (issue #253): the ETag
// must be no newer than every piece of versioned data the draft is built from.
void (async () => {
try {
const itemsMeta = await getTemplateItemsWithMeta(templateId);
const [templateData, groupData, blockData] = await Promise.all([
getTemplate(templateId),
getBlockGroups(),
getBlocks()
]);
if (!active) {
return;
}
etagRef.current = itemsMeta.etag;
setTemplate(templateData);
setBlockGroups(groupData);
setBlocks(blockData);
setDraft({
name: templateData.name,
items: items.map(itemFromResponse)
items: itemsMeta.data.map(itemFromResponse)
});
})
.catch((error: unknown) => {
} catch (error) {
if (active) {
setLoadError(messageFromTemplateError(error, 'Unable to load template'));
}
});
}
})();
return () => {
active = false;
};
}, [templateId]);
}, [templateId, reloadKey]);
if (loadError) {
return (
@@ -659,18 +674,36 @@ function TemplateEditor({ templateId }: { templateId: number }) {
setSaving(true);
setSaveError(null);
try {
await replaceTemplate(templateId, {
name: draft.name.trim(),
items: draft.items.map((item) => ({ blockId: item.blockId, startTime: item.startTime }))
});
const { etag } = await replaceTemplate(
templateId,
{
name: draft.name.trim(),
items: draft.items.map((item) => ({ blockId: item.blockId, startTime: item.startTime }))
},
etagRef.current
);
etagRef.current = etag;
navigateToPath(BASE_PATH);
} catch (error) {
setSaveError(messageFromTemplateError(error, 'Unable to save template'));
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
} else {
setSaveError(messageFromTemplateError(error, 'Unable to save template'));
}
} finally {
setSaving(false);
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setDraft(null);
setTemplate(null);
setReloadKey((key) => key + 1);
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
@@ -796,6 +829,17 @@ function TemplateEditor({ templateId }: { templateId: number }) {
</table>
)}
</Card>
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This template was changed elsewhere since you opened it. Reload to get the latest version — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Template changed elsewhere"
tone="danger"
/>
</div>
);
}