Progress review fixes: in_progress totals, latest dashboard request, preview viewed

- The in_progress search filter skips the uncounted fast path and is part of
  the totals cache key, so Continue never reports All's (or the library's)
  count.
- The dashboard's Recently Viewed hook applies only its latest response, and
  clears the list when switching All/Continue until the new files arrive.
- POST /api/files/file returns `viewed`, so a preview can tell a file
  finished elsewhere from an older position this tab holds.
- The progress hook tests restore Blob, fetch and sendBeacon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-08 17:23:39 -06:00
parent 9db52da49c
commit 0eb831bc1d
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
5 changed files with 123 additions and 14 deletions

View file

@ -946,29 +946,41 @@ export const useChannels = () => {
export const useSearchRecentFiles = (inProgress = false) => {
const [searchFiles, setSearchFiles] = useState(null);
const [loading, setLoading] = useState(false);
// All and Continue share this hook; only the latest request may write, so a slow response for the
// previous mode cannot replace the current one.
const latestRequestRef = React.useRef(0);
const localSearchFiles = async () => {
const requestId = ++latestRequestRef.current;
setLoading(true);
try {
// `inProgress` returns only the files the user is part way through.
let [file_groups, total] = await filesSearch(
let [file_groups] = await filesSearch(
null, 12, null, null, null, [], false,
null, null, null, false, 'viewed', null, null, false, inProgress);
setSearchFiles(file_groups);
if (requestId === latestRequestRef.current) {
setSearchFiles(file_groups);
}
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get recent files',
time: 5000,
});
if (requestId === latestRequestRef.current) {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get recent files',
time: 5000,
});
}
} finally {
setLoading(false);
if (requestId === latestRequestRef.current) {
setLoading(false);
}
}
}
React.useEffect(() => {
// The other mode's files are not this mode's; show the placeholder until they arrive.
setSearchFiles(null);
localSearchFiles();
}, [inProgress]);

View file

@ -2,11 +2,12 @@ import React from 'react';
import {act, renderHook} from '@testing-library/react';
import {render, screen} from '../test-utils';
import {
usePages, useDriveTemperature, useDriveHealth, useSearchChannels, useSettings, useStatistics, useStatus,
useVideoExtras,
usePages, useDriveTemperature, useDriveHealth, useSearchChannels, useSearchRecentFiles, useSettings,
useStatistics, useStatus, useVideoExtras,
} from './customHooks';
import {
ApiDownError, getSettings, getStatistics, getStatus, getVideoComments, getVideoDescription, searchChannels,
ApiDownError, filesSearch, getSettings, getStatistics, getStatus, getVideoComments, getVideoDescription,
searchChannels,
} from '../api';
import {getControllerStats} from '../api/controller';
import {QueryContext, StatusContext} from '../contexts/contexts';
@ -48,6 +49,7 @@ jest.mock('../api', () => ({
getStatistics: jest.fn(),
getStatus: jest.fn(),
getSettings: jest.fn(),
filesSearch: jest.fn(),
}));
jest.mock('../api/controller', () => ({
@ -685,3 +687,52 @@ describe('useSettings loaded', () => {
expect(result.current.settings.media_directory).toBe('/media/wrolpi');
});
});
describe('useSearchRecentFiles', () => {
/** A filesSearch call the test resolves when it chooses. */
const deferred = () => {
let resolve;
const promise = new Promise(r => resolve = r);
return {promise, resolve};
};
beforeEach(() => {
filesSearch.mockReset();
});
test('switching modes shows only the new mode\'s files, even if the old response arrives last', async () => {
const all = deferred();
const continuing = deferred();
filesSearch.mockReturnValueOnce(all.promise).mockReturnValueOnce(continuing.promise);
const {result, rerender} = renderHook(({inProgress}) => useSearchRecentFiles(inProgress),
{initialProps: {inProgress: false}});
// Continue, before All's response arrives.
rerender({inProgress: true});
expect(filesSearch.mock.calls[1][15]).toBe(true);
await act(async () => continuing.resolve([[{primary_path: 'started.mp4'}], 1]));
await act(async () => all.resolve([[{primary_path: 'started.mp4'}, {primary_path: 'finished.mp4'}], 2]));
expect(result.current.searchFiles).toEqual([{primary_path: 'started.mp4'}]);
expect(result.current.loading).toBe(false);
});
test('switching modes clears the old files until the new ones arrive', async () => {
const continuing = deferred();
filesSearch.mockResolvedValueOnce([[{primary_path: 'a.mp4'}], 1]).mockReturnValueOnce(continuing.promise);
const {result, rerender} = renderHook(({inProgress}) => useSearchRecentFiles(inProgress),
{initialProps: {inProgress: false}});
await act(async () => {
});
expect(result.current.searchFiles).toEqual([{primary_path: 'a.mp4'}]);
rerender({inProgress: true});
// Not the All list, and not an empty list ("No results!"): nothing yet.
expect(result.current.searchFiles).toBeNull();
await act(async () => continuing.resolve([[], 0]));
expect(result.current.searchFiles).toEqual([]);
});
});

View file

@ -12,6 +12,9 @@ const sent = () => [
...global.fetch.mock.calls.map(([, init]) => init.body),
].map(i => JSON.parse(i));
const {Blob: realBlob, fetch: realFetch} = global;
const realSendBeacon = navigator.sendBeacon;
beforeEach(() => {
jest.useFakeTimers();
window.sessionStorage.clear();
@ -28,6 +31,9 @@ beforeEach(() => {
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
global.Blob = realBlob;
global.fetch = realFetch;
navigator.sendBeacon = realSendBeacon;
});
describe('getResumePosition', () => {
@ -56,6 +62,14 @@ describe('getResumePosition', () => {
expect(getResumePosition(PATH, fileGroup)).toBeNull();
});
test('a file finished on another device starts over in a preview, too', () => {
// The shape of POST /api/files/file, which the file browser and `?preview=` use.
const cached = {kind: 'time', seconds: 400, updated_at: 500};
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify({progress: 0.6, position: cached, updated_at: 500}));
const previewFile = {path: PATH, progress: 1, position: null, viewed: new Date(9000).toISOString()};
expect(getResumePosition(PATH, previewFile)).toBeNull();
});
test.each([
['finished', {progress: 1, position: null}],
['too early', {progress: 0.2, position: {kind: 'time', seconds: 5}}],

View file

@ -133,6 +133,8 @@ def _get_file_dict(session: Session, file: pathlib.Path) -> Dict:
tags=get_file_tag_names(session, file),
progress=file_group.progress if file_group else None,
position=file_group.position if file_group else None,
# When a finished file (no position) was finished; the preview compares it with its own position.
viewed=file_group.viewed if file_group else None,
)
@ -1348,7 +1350,7 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
# Count separately (and cache) so the page can use the datetime/id index.
if not search_str and not tag_names and not mimetypes and not model and not months \
and not from_year and not to_year and not any_tag and not url and not suffix \
and not path and not viewed_only:
and not path and not viewed_only and not in_progress:
count_stmt = 'SELECT COUNT(*) AS total FROM file_group'
count_params = dict()
elif fts_search:
@ -1371,7 +1373,7 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
'files', search_str=search_str, mimetypes=mimetypes, model=model,
tag_names=tag_names, months=months, from_year=from_year, to_year=to_year,
any_tag=any_tag, url=url, suffix=suffix, path=path, deep=deep,
viewed_only=viewed_only,
viewed_only=viewed_only, in_progress=in_progress,
)
total = cached_search_total(cache_key, lambda: count_file_groups(session, count_stmt, count_params))
results, total = handle_file_group_search_results(session, stmt, params, total=total)

View file

@ -78,6 +78,8 @@ async def test_progress_api(test_session, async_client, test_directory, make_fil
dict(file='videos/movie.mp4', skip_tracking=True)))
assert response.json['file']['progress'] == 0.4
assert response.json['file']['position'] == dict(kind='time', seconds=480.5)
# The preview dates a finished file by when it was viewed.
assert dates.strptime_ms(response.json['file']['viewed']) == fg.viewed
# Rewinding is allowed; the last write wins.
body = dict(file='videos/movie.mp4', progress=0.2, position=dict(kind='time', seconds=240))
@ -459,3 +461,31 @@ async def test_search_in_progress(test_session, async_client, test_directory, ma
# Without the filter every viewed file is returned.
request, response = await async_client.post('/api/files/search', content=json.dumps(dict(order='viewed')))
assert {i['primary_path'] for i in response.json['file_groups']} == {'started.mp4', 'finished.mp4', 'older.mp4'}
@pytest.mark.asyncio
async def test_search_in_progress_totals(test_session, async_client, test_directory, make_files_structure,
monkeypatch):
"""The total counts only files in progress, and is cached apart from the unfiltered total."""
from wrolpi.files import lib as files_lib
monkeypatch.setattr(files_lib, 'PYTEST', False) # Use the totals cache, as production does.
monkeypatch.setattr(files_lib, '_SEARCH_TOTALS_CACHE', dict())
started, finished, unviewed = make_files_structure(['started.mp4', 'finished.mp4', 'unviewed.mp4'])
for path, viewed, progress in ((started, dates.now(), 0.4), (finished, dates.now(), 1.0), (unviewed, None, None)):
fg = FileGroup.from_paths(test_session, path)
fg.viewed = viewed
fg.progress = progress
test_session.commit()
async def total(**body):
request, response = await async_client.post('/api/files/search', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
return response.json['totals']['file_groups']
# The dashboard's All and Continue, back to back.
assert await total(order='viewed') == 2
assert await total(order='viewed', in_progress=True) == 1
assert await total(order='viewed') == 2
# Without an order, the only filter is in_progress; it must not count the whole library.
assert await total(in_progress=True) == 1