fix(settings): prevent deselecting last ladder and coalesce rapid toggles (#440)

This commit is contained in:
Yiling-J
2026-10-01 16:35:47 +08:00
committed by GitHub
parent fc7282581f
commit a21a0c9655
3 changed files with 429 additions and 177 deletions
+1 -1
View File
@@ -14,9 +14,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
- **settings**: Prevent deselecting the last resolution ladder in MP4 and HLS transcode settings, and ensure rapid consecutive toggles reliably coalesce and preserve all selections
- **share**: Fix an issue where videos with HLS enabled could play without watermark on public share links before watermark transcoding completed
- **webui**: Fix an issue where legacy portrait video transcodes were mislabeled in download menus and the video player (e.g. "1920p" instead of "1080p") by correctly deriving resolution labels from the long side
- **settings**: Fix an issue where rapid consecutive toggling of transcode resolution checkboxes could submit outdated selections or drop previous toggles
- **webui**: Fix an issue where the resolution selector in the video seekbar displayed vertical video resolutions by long side (e.g. "Auto (3840p)") instead of standard short side (e.g. "Auto (2160p)")
- **webui**: Fix an issue where 480p videos were mislabeled as 360p in the navigation bar and mobile file header download menus
- **share**: Fix an issue where public HLS playback and watermarked streams failed to load for shared version stacks and symlinks
@@ -91,6 +91,118 @@ const VALID_SETTINGS_TABS: readonly SettingsTab[] = [
'developer',
]
const ALL_VIDEO_LADDERS: VideoResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
const ALL_HLS_LADDERS: HlsResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
function useCoalescedLadderSettings<TLadder extends VideoResolutionLadder | HlsResolutionLadder>({
teamId,
settingKey,
field,
serverResolutions,
defaultResolutions,
}: {
teamId: string
settingKey: 'transcode.videoResolutions' | 'transcode.hlsResolutions'
field: 'videoResolutions' | 'hlsResolutions'
serverResolutions: TLadder[] | undefined
defaultResolutions: TLadder[]
}) {
const queryClient = useQueryClient()
const pendingResolutionsRef = useRef<TLadder[] | null>(null)
const [optimisticResolutions, setOptimisticResolutions] = useState<TLadder[] | null>(null)
const queueRef = useRef<Promise<void>>(Promise.resolve())
const isUpdatingRef = useRef<boolean>(false)
useEffect(() => {
if (!isUpdatingRef.current) {
pendingResolutionsRef.current = null
setOptimisticResolutions(null)
}
}, [serverResolutions])
const currentResolutions: TLadder[] =
optimisticResolutions ?? serverResolutions ?? defaultResolutions
const handleToggle = (ladder: TLadder) => {
const current =
pendingResolutionsRef.current ??
optimisticResolutions ??
serverResolutions ??
defaultResolutions
// If currently checked and it's the last remaining option, do not allow unselecting
if (current.includes(ladder) && current.length === 1) {
return
}
const updated = current.includes(ladder)
? current.filter((l) => l !== ladder)
: [...current, ladder]
if (updated.length === 0) return
pendingResolutionsRef.current = updated
setOptimisticResolutions(updated)
queryClient.setQueryData(
['teams', teamId, 'settings'],
(old: TeamSettingsResponse | undefined) => {
if (!old) return old
return {
...old,
transcode: {
...old.transcode,
[field]: updated,
},
}
},
)
isUpdatingRef.current = true
queueRef.current = queueRef.current
.then(async () => {
const target = pendingResolutionsRef.current
if (!target) return
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: {
key: settingKey,
value: target,
} as UpdateTeamSettingsRequest,
})
if (!res.ok) throw new Error('Failed to update settings')
await res.json()
if (pendingResolutionsRef.current === target) {
pendingResolutionsRef.current = null
isUpdatingRef.current = false
setOptimisticResolutions(null)
await queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
}
})
.catch((err) => {
console.error(err)
pendingResolutionsRef.current = null
isUpdatingRef.current = false
setOptimisticResolutions(null)
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.error(m.failed_update_settings())
})
}
return {
currentResolutions,
handleToggle,
}
}
function getTabFromHash(): SettingsTab {
if (typeof window === 'undefined') return 'general'
const hash = window.location.hash.replace(/^#/, '')
@@ -316,101 +428,24 @@ export function TeamSettingsPage() {
})
}
const pendingVideoResolutionsRef = useRef<VideoResolutionLadder[] | null>(null)
const [optimisticVideoResolutions, setOptimisticVideoResolutions] = useState<
VideoResolutionLadder[] | null
>(null)
const videoResolutionsQueueRef = useRef<Promise<void>>(Promise.resolve())
const isVideoResolutionsUpdatingRef = useRef<boolean>(false)
const { currentResolutions: currentVideoResolutions, handleToggle: handleVideoLadderToggle } =
useCoalescedLadderSettings({
teamId,
settingKey: 'transcode.videoResolutions',
field: 'videoResolutions',
serverResolutions: (settings as TeamSettingsResponse | undefined)?.transcode
?.videoResolutions,
defaultResolutions: DEFAULT_VIDEO_RESOLUTIONS,
})
const pendingHlsResolutionsRef = useRef<HlsResolutionLadder[] | null>(null)
const [optimisticHlsResolutions, setOptimisticHlsResolutions] = useState<
HlsResolutionLadder[] | null
>(null)
const hlsResolutionsQueueRef = useRef<Promise<void>>(Promise.resolve())
const isHlsResolutionsUpdatingRef = useRef<boolean>(false)
useEffect(() => {
if (!isVideoResolutionsUpdatingRef.current) {
pendingVideoResolutionsRef.current = null
setOptimisticVideoResolutions(null)
}
}, [settings])
useEffect(() => {
if (!isHlsResolutionsUpdatingRef.current) {
pendingHlsResolutionsRef.current = null
setOptimisticHlsResolutions(null)
}
}, [settings])
const handleVideoLadderToggle = (ladder: VideoResolutionLadder) => {
const current =
pendingVideoResolutionsRef.current ??
optimisticVideoResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.videoResolutions ??
DEFAULT_VIDEO_RESOLUTIONS
const updated = current.includes(ladder)
? current.filter((l) => l !== ladder)
: [...current, ladder]
if (updated.length === 0) return
pendingVideoResolutionsRef.current = updated
setOptimisticVideoResolutions(updated)
queryClient.setQueryData(
['teams', teamId, 'settings'],
(old: TeamSettingsResponse | undefined) => {
if (!old) return old
return {
...old,
transcode: {
...old.transcode,
videoResolutions: updated,
},
}
},
)
isVideoResolutionsUpdatingRef.current = true
videoResolutionsQueueRef.current = videoResolutionsQueueRef.current
.then(async () => {
const target = pendingVideoResolutionsRef.current
if (!target) return
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: {
key: 'transcode.videoResolutions',
value: target,
},
})
if (!res.ok) throw new Error('Failed to update settings')
await res.json()
if (pendingVideoResolutionsRef.current === target) {
pendingVideoResolutionsRef.current = null
isVideoResolutionsUpdatingRef.current = false
setOptimisticVideoResolutions(null)
await queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
}
})
.catch((err) => {
console.error(err)
pendingVideoResolutionsRef.current = null
isVideoResolutionsUpdatingRef.current = false
setOptimisticVideoResolutions(null)
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.error(m.failed_update_settings())
})
}
const { currentResolutions: currentHlsResolutions, handleToggle: handleHlsLadderToggle } =
useCoalescedLadderSettings({
teamId,
settingKey: 'transcode.hlsResolutions',
field: 'hlsResolutions',
serverResolutions: (settings as TeamSettingsResponse | undefined)?.transcode?.hlsResolutions,
defaultResolutions: DEFAULT_HLS_RESOLUTIONS,
})
const handleHardwareAccelerationChange = (value: HardwareAcceleration) => {
updateSettings({
@@ -449,74 +484,6 @@ export function TeamSettingsPage() {
})
}
const handleHlsLadderToggle = (ladder: HlsResolutionLadder) => {
const current =
pendingHlsResolutionsRef.current ??
optimisticHlsResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsResolutions ??
DEFAULT_HLS_RESOLUTIONS
const updated = current.includes(ladder)
? current.filter((l) => l !== ladder)
: [...current, ladder]
if (updated.length === 0) return
pendingHlsResolutionsRef.current = updated
setOptimisticHlsResolutions(updated)
queryClient.setQueryData(
['teams', teamId, 'settings'],
(old: TeamSettingsResponse | undefined) => {
if (!old) return old
return {
...old,
transcode: {
...old.transcode,
hlsResolutions: updated,
},
}
},
)
isHlsResolutionsUpdatingRef.current = true
hlsResolutionsQueueRef.current = hlsResolutionsQueueRef.current
.then(async () => {
const target = pendingHlsResolutionsRef.current
if (!target) return
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: {
key: 'transcode.hlsResolutions',
value: target,
},
})
if (!res.ok) throw new Error('Failed to update settings')
await res.json()
if (pendingHlsResolutionsRef.current === target) {
pendingHlsResolutionsRef.current = null
isHlsResolutionsUpdatingRef.current = false
setOptimisticHlsResolutions(null)
await queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
}
})
.catch((err) => {
console.error(err)
pendingHlsResolutionsRef.current = null
isHlsResolutionsUpdatingRef.current = false
setOptimisticHlsResolutions(null)
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.error(m.failed_update_settings())
})
}
if (isSettingsLoading || isMeLoading) {
return (
<div className="flex h-screen items-center justify-center">
@@ -542,12 +509,6 @@ export function TeamSettingsPage() {
currentVideoStrategy = VideoTranscodeStrategy.multi
}
const currentVideoResolutions: VideoResolutionLadder[] =
optimisticVideoResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.videoResolutions ??
DEFAULT_VIDEO_RESOLUTIONS
const ALL_VIDEO_LADDERS: VideoResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
const currentHardwareAcceleration =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settings as any)?.transcode?.hardwareAcceleration || HardwareAcceleration.off
@@ -555,11 +516,6 @@ export function TeamSettingsPage() {
const currentThreads = localThreads ?? serverThreads
const currentHlsEnabled =
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsEnabled ?? false
const currentHlsResolutions: HlsResolutionLadder[] =
optimisticHlsResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsResolutions ??
DEFAULT_HLS_RESOLUTIONS
const ALL_HLS_LADDERS: HlsResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
return (
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
@@ -1029,13 +985,21 @@ export function TeamSettingsPage() {
<div className="flex flex-wrap gap-4 pt-1">
{ALL_VIDEO_LADDERS.map((ladder) => {
const checked = currentVideoResolutions.includes(ladder)
const isLastSelected =
checked && currentVideoResolutions.length === 1
return (
<label
key={ladder}
className="flex items-center space-x-2 cursor-pointer text-sm"
className={cn(
'flex items-center space-x-2 text-sm',
isLastSelected
? 'cursor-not-allowed opacity-50'
: 'cursor-pointer',
)}
>
<Checkbox
checked={checked}
disabled={isLastSelected}
onCheckedChange={() => handleVideoLadderToggle(ladder)}
/>
<span>{ladder}</span>
@@ -1149,13 +1113,20 @@ export function TeamSettingsPage() {
<div className="flex flex-wrap gap-4 pt-1">
{ALL_HLS_LADDERS.map((ladder) => {
const checked = currentHlsResolutions.includes(ladder)
const isLastSelected = checked && currentHlsResolutions.length === 1
return (
<label
key={ladder}
className="flex items-center space-x-2 cursor-pointer text-sm"
className={cn(
'flex items-center space-x-2 text-sm',
isLastSelected
? 'cursor-not-allowed opacity-50'
: 'cursor-pointer',
)}
>
<Checkbox
checked={checked}
disabled={isLastSelected}
onCheckedChange={() => handleHlsLadderToggle(ladder)}
/>
<span>{ladder}</span>
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { cleanup, render, screen, within, fireEvent, waitFor, act } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -238,4 +238,285 @@ describe('TeamSettingsPage Transcode Settings', () => {
const lastPatch = patchCalls[patchCalls.length - 1]
expect(lastPatch.json.value).toEqual(['1080p', '1440p', '2160p'])
})
it('disables unselecting the last remaining video resolution ladder in MP4 selector', async () => {
mockGetSettings.mockResolvedValue({
ok: true,
json: async () => ({
transcode: {
videoStrategy: VideoTranscodeStrategy.multi,
videoResolutions: ['1080p'],
hardwareAcceleration: 'off',
threads: 0,
hlsEnabled: true,
hlsResolutions: ['480p', '720p', '1080p'],
},
}),
})
mockPatchSettings.mockResolvedValue({
ok: true,
json: async () => ({
transcode: {
videoResolutions: ['1080p', '720p'],
},
}),
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getAllByText('1080p').length).toBeGreaterThan(0)
})
const mp4Desc = screen.getByText(
'Select the target resolutions to generate for MP4 transcoding. Resolutions are only generated up to the source video resolution.',
)
const mp4Container = mp4Desc.closest('.space-y-3') as HTMLElement
expect(mp4Container).toBeDefined()
const label1080p = within(mp4Container).getByText('1080p').closest('label')!
const checkbox1080p = label1080p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox1080p).toBeDefined()
expect(checkbox1080p.getAttribute('aria-checked')).toBe('true')
expect(checkbox1080p.hasAttribute('disabled')).toBe(true)
expect(label1080p.className).toContain('cursor-not-allowed')
const label720p = within(mp4Container).getByText('720p').closest('label')!
const checkbox720p = label720p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox720p.getAttribute('aria-checked')).toBe('false')
expect(checkbox720p.hasAttribute('disabled')).toBe(false)
expect(label720p.className).toContain('cursor-pointer')
// Clicking the sole selected resolution must not unselect it or call patch
act(() => {
fireEvent.click(checkbox1080p)
})
expect(checkbox1080p.getAttribute('aria-checked')).toBe('true')
expect(mockPatchSettings).not.toHaveBeenCalled()
// Clicking 720p to add it works
act(() => {
fireEvent.click(checkbox720p)
})
expect(checkbox720p.getAttribute('aria-checked')).toBe('true')
await waitFor(() => {
expect(mockPatchSettings).toHaveBeenCalledWith(
expect.objectContaining({
json: {
key: 'transcode.videoResolutions',
value: ['1080p', '720p'],
},
}),
)
})
})
it('disables unselecting the last remaining HLS resolution ladder in HLS selector', async () => {
mockGetSettings.mockResolvedValue({
ok: true,
json: async () => ({
transcode: {
videoStrategy: VideoTranscodeStrategy.multi,
videoResolutions: ['720p', '1080p'],
hardwareAcceleration: 'off',
threads: 0,
hlsEnabled: true,
hlsResolutions: ['720p'],
},
}),
})
mockPatchSettings.mockResolvedValue({
ok: true,
json: async () => ({
transcode: {
hlsResolutions: ['720p', '1080p'],
},
}),
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getAllByText('720p').length).toBeGreaterThan(0)
})
const hlsDesc = screen.getByText(
'Select the target resolutions to generate for HLS streaming. Ladders are only generated up to the source video resolution.',
)
const hlsContainer = hlsDesc.closest('.space-y-3') as HTMLElement
expect(hlsContainer).toBeDefined()
const label720p = within(hlsContainer).getByText('720p').closest('label')!
const checkbox720p = label720p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox720p).toBeDefined()
expect(checkbox720p.getAttribute('aria-checked')).toBe('true')
expect(checkbox720p.hasAttribute('disabled')).toBe(true)
expect(label720p.className).toContain('cursor-not-allowed')
const label1080p = within(hlsContainer).getByText('1080p').closest('label')!
const checkbox1080p = label1080p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox1080p.getAttribute('aria-checked')).toBe('false')
expect(checkbox1080p.hasAttribute('disabled')).toBe(false)
expect(label1080p.className).toContain('cursor-pointer')
// Clicking the sole selected HLS resolution must not unselect it or call patch
act(() => {
fireEvent.click(checkbox720p)
})
expect(checkbox720p.getAttribute('aria-checked')).toBe('true')
expect(mockPatchSettings).not.toHaveBeenCalled()
})
it('keeps pending selections optimistically and serializes consecutive toggles for HLS resolutions without submitting stale arrays', async () => {
let resolveFirstPatch!: (value: unknown) => void
const firstPatchPromise = new Promise((resolve) => {
resolveFirstPatch = resolve
})
const patchCalls: PatchSettingsArgs[] = []
mockPatchSettings.mockImplementation(async (args: PatchSettingsArgs) => {
patchCalls.push(args)
if (patchCalls.length === 1) {
await firstPatchPromise
}
return {
ok: true,
json: async () => ({
transcode: {
hlsResolutions: args.json.value,
},
}),
}
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getAllByText('480p').length).toBeGreaterThan(1)
})
const hlsDesc = screen.getByText(
'Select the target resolutions to generate for HLS streaming. Ladders are only generated up to the source video resolution.',
)
const hlsContainer = hlsDesc.closest('.space-y-3') as HTMLElement
const label480p = within(hlsContainer).getByText('480p').closest('label')!
const checkbox480p = label480p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox480p.getAttribute('aria-checked')).toBe('true')
const label720p = within(hlsContainer).getByText('720p').closest('label')!
const checkbox720p = label720p.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox720p.getAttribute('aria-checked')).toBe('true')
// Click 480p to uncheck it
act(() => {
fireEvent.click(checkbox480p)
})
expect(checkbox480p.getAttribute('aria-checked')).toBe('false')
// Wait for the first PATCH request to be in-flight
await waitFor(() => {
expect(patchCalls.length).toBe(1)
})
expect(patchCalls[0].json.value).toEqual(['720p', '1080p', '1440p', '2160p'])
// Rapid consecutive click: Click 720p to uncheck it WHILE first patch is in-flight
act(() => {
fireEvent.click(checkbox720p)
})
expect(checkbox720p.getAttribute('aria-checked')).toBe('false')
// Resolve first patch so the queue advances
await act(async () => {
resolveFirstPatch({
ok: true,
json: async () => ({
transcode: {
hlsResolutions: ['720p', '1080p', '1440p', '2160p'],
},
}),
})
})
// Wait for the second queued patch to complete
await waitFor(() => {
expect(patchCalls.length).toBe(2)
})
// The second patch must not submit stale array with 480p present
expect(patchCalls[1].json.value).toEqual(['1080p', '1440p', '2160p'])
expect(patchCalls[1].json.value.includes('480p')).toBe(false)
expect(patchCalls[1].json.value.includes('720p')).toBe(false)
expect(toast.success).toHaveBeenCalled()
})
it('coalesces rapid consecutive toggles for HLS resolutions into a single PATCH', async () => {
const patchCalls: PatchSettingsArgs[] = []
mockPatchSettings.mockImplementation(async (args: PatchSettingsArgs) => {
patchCalls.push(args)
return {
ok: true,
json: async () => ({
transcode: {
hlsResolutions: args.json.value,
},
}),
}
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getAllByText('480p').length).toBeGreaterThan(1)
})
const hlsDesc = screen.getByText(
'Select the target resolutions to generate for HLS streaming. Ladders are only generated up to the source video resolution.',
)
const hlsContainer = hlsDesc.closest('.space-y-3') as HTMLElement
const label480p = within(hlsContainer).getByText('480p').closest('label')!
const checkbox480p = label480p.querySelector('button[role="checkbox"]') as HTMLElement
const label720p = within(hlsContainer).getByText('720p').closest('label')!
const checkbox720p = label720p.querySelector('button[role="checkbox"]') as HTMLElement
// Rapid synchronous clicks in the same event tick
act(() => {
fireEvent.click(checkbox480p)
fireEvent.click(checkbox720p)
})
// Both reflect optimistically
expect(checkbox480p.getAttribute('aria-checked')).toBe('false')
expect(checkbox720p.getAttribute('aria-checked')).toBe('false')
// Wait for the coalesced PATCH to complete
await waitFor(() => {
expect(patchCalls.length).toBeGreaterThanOrEqual(1)
})
const lastPatch = patchCalls[patchCalls.length - 1]
expect(lastPatch.json.value).toEqual(['1080p', '1440p', '2160p'])
})
})