Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions web/src/components/settings/SecretField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export interface SecretFieldProps {
hint?: string;
/** Extra line under the description, e.g. a save error for this field. */
status?: ReactNode;
/** Marks the row as holding an unsaved change, as `SettingField` does. */
dirty?: boolean;
disabled?: boolean;
restartRequired?: boolean;
/** The environment variable that sets this secret; disables the control. */
Expand Down Expand Up @@ -67,6 +69,7 @@ export function SecretField({
cleared = false,
hint,
status,
dirty,
disabled: disabledProp = false,
restartRequired = false,
managedByEnv,
Expand Down Expand Up @@ -104,6 +107,7 @@ export function SecretField({
<SettingFieldRow
label={label}
htmlFor={controlId}
dirty={dirty}
description={description}
descriptionId={hintId}
status={status}
Expand Down
65 changes: 65 additions & 0 deletions web/src/pages/admin-settings/CompatibilityProxiesSettings.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, expect, it, vi } from "vitest";

import CompatibilityProxiesSettings from "./CompatibilityProxiesSettings";

const SETTINGS = {
"jellyfin_compat.enabled": "true",
"jellyfin_compat.web_enabled": "true",
"jellyfin_compat.public_url": "https://media.example.com",
};

const { sensitiveStatus } = vi.hoisted(() => ({
sensitiveStatus: {
current: { configured: [], managed_by_env: [] } as {
configured: string[];
managed_by_env: string[];
managed_by_env_vars?: Record<string, string>;
},
},
}));

vi.mock("@/hooks/queries/admin/settings", () => ({
useAdminServerSettings: () => ({ data: SETTINGS, isLoading: false }),
useAdminSensitiveStatus: () => ({ data: sensitiveStatus.current, isError: false }),
useUpdateServerSettings: () => ({ mutateAsync: vi.fn(), isPending: false }),
useJellyfinCompatStatus: () => ({
data: { enabled: true, web_enabled: true, api_state: "running", web_state: "missing" },
isLoading: false,
}),
useInstallJellyfinCompatWeb: () => ({ mutate: vi.fn(), isPending: false }),
useRemoveJellyfinCompatWeb: () => ({ mutate: vi.fn(), isPending: false }),
useUpdateJellyfinCompatSettings: () => ({ mutate: vi.fn(), isPending: false }),
}));

vi.mock("@/hooks/useRestartKeys", () => ({ useRestartKeys: () => ({ has: () => false }) }));

beforeEach(() => {
sensitiveStatus.current = { configured: [], managed_by_env: [] };
});

it("stages nothing when the Jellyfin API is switched off and back on", async () => {
render(<CompatibilityProxiesSettings />);
const api = screen.getByRole("switch", { name: "Allow Jellyfin apps to connect" });
await userEvent.click(api);
await userEvent.click(api);

expect(screen.queryByText(/unsaved change/)).not.toBeInTheDocument();
});

it("takes back the Jellyfin Web switch-off once the environment sets the API switch", async () => {
const { rerender } = render(<CompatibilityProxiesSettings />);
await userEvent.click(screen.getByRole("switch", { name: "Allow Jellyfin apps to connect" }));
expect(screen.getByText("2 unsaved changes")).toBeInTheDocument();

// A restart with SILO_JELLYFIN_ENABLED set: the form drops the API draft.
sensitiveStatus.current = {
configured: [],
managed_by_env: ["jellyfin_compat.enabled"],
managed_by_env_vars: { "jellyfin_compat.enabled": "SILO_JELLYFIN_ENABLED" },
};
rerender(<CompatibilityProxiesSettings />);

expect(screen.queryByText(/unsaved change/)).not.toBeInTheDocument();
});
18 changes: 17 additions & 1 deletion web/src/pages/admin-settings/CompatibilityProxiesSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from "react";
import { useLayoutEffect, useMemo } from "react";
import {
AlertCircle,
CheckCircle2,
Expand Down Expand Up @@ -179,6 +179,22 @@ export default function CompatibilityProxiesSettings() {
const removeWeb = useRemoveJellyfinCompatWeb();
const updateCompatSettings = useUpdateJellyfinCompatSettings();
const status = statusQuery.data;
// Switching the API off also turns Jellyfin Web off (setJellyfinAPIEnabled),
// as the server's own Jellyfin settings endpoint does. That edit has no field
// here, so it stays only while an API switch-off is staged: flipping the
// switch back, switching off an API that is already off, or the environment
// taking the switch over (the form then drops its draft) takes it back.
// A layout effect, so the save bar never paints the extra count.
const webOffAlone =
form.isDirty("jellyfin_compat.web_enabled") &&
!(
form.isDirty("jellyfin_compat.enabled") &&
form.getValue("jellyfin_compat.enabled") === "false"
);
const { resetValue } = form;
useLayoutEffect(() => {
if (webOffAlone) resetValue("jellyfin_compat.web_enabled");
}, [webOffAlone, resetValue]);

if (form.isLoading || statusQuery.isLoading)
return (
Expand Down
107 changes: 107 additions & 0 deletions web/src/pages/admin-settings/PlaybackSettings.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";

import PlaybackSettings from "./PlaybackSettings";

window.HTMLElement.prototype.hasPointerCapture ??= () => false;
window.HTMLElement.prototype.setPointerCapture ??= () => {};
window.HTMLElement.prototype.releasePointerCapture ??= () => {};
window.HTMLElement.prototype.scrollIntoView ??= () => {};

const A = "/dev/dri/renderD128";
const B = "/dev/dri/renderD129";
const C = "/dev/dri/renderD130";

const { settings } = vi.hoisted(() => ({
settings: { current: {} as Record<string, string> },
}));

vi.mock("@/hooks/queries/admin/settings", () => ({
useAdminServerSettings: () => ({ data: settings.current, isLoading: false }),
useAdminSensitiveStatus: () => ({ data: { configured: [], managed_by_env: [] }, isError: false }),
useUpdateServerSettings: () => ({ mutateAsync: vi.fn(), isPending: false }),
}));
vi.mock("@/hooks/queries/admin/system", () => ({
useHWAccelDetection: () => ({
data: {
resolved: "vaapi",
render_device_details: [
{ path: A, description: "GPU A" },
{ path: B, description: "GPU B" },
{ path: C, description: "GPU C" },
],
},
isLoading: false,
}),
}));
vi.mock("@/hooks/queries/admin/nodes", () => ({
useAdminNodes: () => ({ data: [], isSuccess: true }),
}));
vi.mock("@/hooks/queries/admin/libraries", () => ({
useLibraryCapabilities: () => ({ data: { trickplay: false } }),
}));
vi.mock("@/hooks/queries/admin/markers", () => ({
useAdminMarkerCapabilities: () => ({ data: undefined }),
}));
vi.mock("@/hooks/queries/admin/trickplay", () => ({
useAdminTrickplayLibraries: () => ({ data: [], isSuccess: true }),
}));
vi.mock("@/hooks/useRestartKeys", () => ({ useRestartKeys: () => ({ has: () => false }) }));
vi.mock("./MarkerTasksCard", () => ({ MarkerTasksCard: () => null }));

const page = (
<MemoryRouter>
<PlaybackSettings />
</MemoryRouter>
);

async function openDevices() {
const transcoding = within(screen.getByRole("group", { name: "Transcoding" }));
await userEvent.click(transcoding.getByRole("button", { name: /Advanced/ }));
}

async function switchToNvenc() {
await userEvent.click(screen.getByRole("combobox", { name: "Hardware acceleration" }));
await userEvent.click(screen.getByRole("option", { name: "NVIDIA NVENC" }));
}

describe("hardware device picker kept for an unsaved change", () => {
beforeEach(() => {
// Disclosures remember being opened; start every case collapsed.
localStorage.clear();
settings.current = { "playback.hw_accel": "vaapi", "playback.hw_device": A };
});

it("under NVENC only takes the staged device back off", async () => {
render(page);
await openDevices();
await userEvent.click(screen.getByRole("switch", { name: "GPU B" }));
await switchToNvenc();

// A render path NVENC can't use can't be added, and the staged one can
// go back off.
expect(screen.getByRole("switch", { name: "GPU C" })).toBeDisabled();
await userEvent.click(screen.getByRole("switch", { name: "GPU B" }));

expect(screen.queryByRole("switch", { name: "GPU B" })).not.toBeInTheDocument();
expect(screen.getByText("1 unsaved change")).toBeInTheDocument();
});

it("can restore a saved list that differs from the staged one only in order", async () => {
const { rerender } = render(page);
await openDevices();
await userEvent.click(screen.getByRole("switch", { name: "GPU B" }));
// Someone else saves the same devices in the other order.
settings.current = { "playback.hw_accel": "vaapi", "playback.hw_device": `${B},${A}` };
rerender(page);
await switchToNvenc();

await userEvent.click(screen.getByRole("switch", { name: "GPU A" }));
await userEvent.click(screen.getByRole("switch", { name: "GPU A" }));

expect(screen.queryByRole("switch", { name: "GPU A" })).not.toBeInTheDocument();
expect(screen.getByText("1 unsaved change")).toBeInTheDocument();
});
});
76 changes: 60 additions & 16 deletions web/src/pages/admin-settings/PlaybackSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,41 @@ export default function PlaybackSettings() {
const hwDevice = form.getValue("playback.hw_device");
const hwDeviceEnv = form.envVar("playback.hw_device");
const selectedDevices = parseHWDeviceList(hwDevice);
const deviceRows = buildHWDeviceRows(hwDetection.data, hwDevice);
const detectedPaths = deviceRows.filter((row) => row.detected).map((row) => row.path);
// Saved paths keep their rows when the draft drops them, so switching off a
// device that detection doesn't list leaves its row in place. A toggle orders
// the list saved paths first, in their saved order, so switching a device
// back on restores the saved list.
const savedDevices = parseHWDeviceList(form.getPersistedValue("playback.hw_device"));
const deviceRows = buildHWDeviceRows(hwDetection.data, [...savedDevices, hwDevice].join(","));
const deviceOrder = [
...savedDevices,
...deviceRows.map((row) => row.path).filter((path) => !savedDevices.includes(path)),
];
// Balancing is QSV/VAAPI-only: NVENC addresses GPUs by CUDA index/UUID, so
// the multi-select picker is hidden for it (the server uses the first
// configured entry).
const isNvenc =
hwAccel === "nvenc" || (hwAccel === "auto" && hwDetection.data?.resolved === "nvenc");
const inventoriesDiverge = nodeInventoriesDiverge(hwDetection.data);
const showDevicePicker = hwAccel !== "none" && !isNvenc && deviceRows.length > 0;
// A device choice staged before switching acceleration keeps the picker in
// view, so Save never writes a value the admin can't see. Under a mode the
// picker doesn't apply to, it only takes the list back toward the saved one:
// any device can be switched off, and only saved devices on. NVENC reads the
// setting as a CUDA device, so render paths can't be added there.
const devicePickerApplies = hwAccel !== "none" && !isNvenc;
const hwDeviceDirty = form.isDirty("playback.hw_device");
const showDevicePicker = deviceRows.length > 0 && (devicePickerApplies || hwDeviceDirty);
const deviceChanged = (path: string) =>
selectedDevices.includes(path) !== savedDevices.includes(path);
// A staged list can match the saved devices and differ only in order, as
// after a refresh; its selected rows then carry the change.
const orderOnlyDraft = hwDeviceDirty && !deviceRows.some((row) => deviceChanged(row.path));
const deviceKeptForEdit = (path: string) =>
!devicePickerApplies &&
(deviceChanged(path) || (orderOnlyDraft && selectedDevices.includes(path)));
const deviceSwitchLocked = (path: string) =>
Comment thread
Quick104 marked this conversation as resolved.
Resolved
hwDeviceEnv != null ||
(!devicePickerApplies && !selectedDevices.includes(path) && !savedDevices.includes(path));

const nodes = useAdminNodes();
const trickplayExecution =
Expand Down Expand Up @@ -133,8 +159,12 @@ export default function PlaybackSettings() {
const anyDirty = (keys: readonly string[]) => keys.some((key) => isDirty(key));
const allRestart = (keys: readonly string[]) => keys.every((key) => restartKeys.has(key));

// Each of these rows also stays in view, marked as changed, while it holds
// an unsaved edit after its switch is turned off.
const throttleOn = form.getValue("enable_transcode_throttle") === "true";
const throttleSecondsKept = !throttleOn && isDirty("transcode_throttle_seconds");
const allow4KTranscode = form.getValue("allow_4k_transcode") === "true";
const preferLowerKept = !allow4KTranscode && isDirty("playback.prefer_lower_version_transcode");
// Every advanced transcoding key has one row, except the device picker,
// which renders only when it applies.
const transcodingAdvancedCount = TRANSCODING_ADVANCED_KEYS.length - (showDevicePicker ? 0 : 1);
Expand Down Expand Up @@ -279,9 +309,10 @@ export default function PlaybackSettings() {
onChange={(v) => form.setValue("allow_4k_transcode", v)}
restartRequired={restartKeys.has("allow_4k_transcode")}
/>
{allow4KTranscode && (
{(allow4KTranscode || preferLowerKept) && (
<SettingField
label={t("web.admin.settings.playback.transcoding.preferLower")}
dirty={preferLowerKept}
type="toggle"
description={t("web.admin.settings.playback.transcoding.preferLowerDescription")}
value={form.getValue("playback.prefer_lower_version_transcode")}
Expand Down Expand Up @@ -319,9 +350,10 @@ export default function PlaybackSettings() {
onChange={(v) => form.setValue("enable_transcode_throttle", v)}
restartRequired={restartKeys.has("enable_transcode_throttle")}
/>
{throttleOn && (
{(throttleOn || throttleSecondsKept) && (
<SettingField
label={t("web.admin.settings.playback.transcoding.bufferAhead")}
dirty={throttleSecondsKept}
type="number"
unit={t("web.admin.settings.playback.unitSeconds")}
value={form.getValue("transcode_throttle_seconds")}
Expand Down Expand Up @@ -390,6 +422,7 @@ export default function PlaybackSettings() {
{deviceRows.map((row, index) => (
<SettingFieldRow
key={row.path}
dirty={deviceKeptForEdit(row.path)}
// One note for the whole device list, on its first row.
managedByEnv={index === 0 ? hwDeviceEnv : undefined}
label={
Expand All @@ -413,17 +446,28 @@ export default function PlaybackSettings() {
<Switch
checked={selectedDevices.includes(row.path)}
aria-label={row.description}
disabled={hwDeviceEnv != null}
onCheckedChange={() =>
form.setValue(
"playback.hw_device",
toggleHWDevice(
form.getValue("playback.hw_device"),
row.path,
detectedPaths,
),
)
}
disabled={deviceSwitchLocked(row.path)}
onCheckedChange={() => {
const next = toggleHWDevice(
form.getValue("playback.hw_device"),
row.path,
deviceOrder,
);
// Back to the saved devices stages the saved string
// itself, so the form can tell it undoes the edit
// however that string is spaced, and keeps it staged
// while a save settles. An unset value is never in
// the snapshot, so outside a save that draft is
// dropped directly.
const saved = form.getPersistedValue("playback.hw_device");
if (next !== savedDevices.join(",")) {
form.setValue("playback.hw_device", next);
} else if (saved === "" && !form.isSaving) {
form.resetValue("playback.hw_device");
Comment thread
Quick104 marked this conversation as resolved.
Resolved
} else {
form.setValue("playback.hw_device", saved);
}
}}
/>
</SettingFieldRow>
))}
Expand Down
Loading
Loading