fix(sync): ignore stale duplicate reading positions (#7231)

* fix(sync): ignore stale duplicate reading positions

Require a sibling copy's config to be newer than both this file's local
save and exact cloud record before applying its forward reading fraction.
This prevents an old duplicate from repeatedly restoring a ghost position
after a deliberate rewind or cloud-data purge, while preserving newer
sibling recovery and exact-file forward sync. Keep a fresh copy's initial
relocation from bumping its zero timestamp before a slow pull finishes;
subsequent reading changes still save normally.

Verified on origin/main a7c168ee5:
- 107 related tests passed across six suites; lint and format:check passed.
- Fresh-copy regression failed on the initial autosave without its guard;
  with the guard, initial relocation skips saving and the next turn saves.
- Restoring the old filter makes six duplicate-copy regression cases fail
  (including an unexpected goToFraction(0.6)); all eight pass with the fix.
- Linux Tauri CEF with a local EPUB and mocked cloud: baseline reopens
  saved page 11 at page 66; fix stays on page 11; newer sibling advances
  to page 66. Repeat with full page navigation had no page errors.
- Web desktop/mobile Chromium verified with mocked cloud responses.
- Android and iPadOS app verification not run.

Reported by noideaforeal on GitHub.
Fixes #7092

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): capture initial relocation before progress coalescing

Seed the fresh-copy autosave baseline from the first valid relocation event
in FoliateViewer, before animation-frame coalescing replaces it with a later
user destination. The hook retains that first location so subsequent early
navigation is persisted instead of being treated as already saved.

Verified: 115 related tests passed across seven files; lint/type checking
and format:check passed. Without the fix, the new coalesced-jump regression
fails with expected saveConfig once, received zero calls. Viewer coverage
also verifies both relocation events reach autosave before the final
progress update. Native app verification not repeated for this follow-up.

Reported by noideaforeal on GitHub (#7092).
Addresses CodeRabbit review on #7231.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): keep progress autosave in the primary view

Secondary views do not update the shared config location. Ignore their
initial baseline and persistence attempts so they cannot timestamp a fresh
copy before the primary view commits and reject a pending sibling pull.

Verified: 117 related tests across seven suites, pnpm lint and
pnpm format:check passed. Both new parallel-view cases fail without this
change with one unexpected saveConfig call from h1-view2, and pass with it.
Linux Tauri verification of the issue passed on e974df87c; this follow-up's
parallel ordering was exercised in hook tests, not the native app.

Reported by noideaforeal on GitHub (#7092).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(sync): gate the first pull locally (owner: confine the changes just in useProgressSync.ts)

Restore the autosave and viewer code. Keep the fresh-copy exception in
useProgressSync: capture the zero-timestamp initial location when its first
pull starts, and disregard its autosave timestamp only while unchanged.
Consume the exception on the first response or retry exhaustion. Later
reading changes and exact cloud timestamps still gate sibling progress.

Verified 116 related tests across seven suites, lint/type checking and
format:check. The slow-pull regression fails with the previous timestamp-only
gate: expected goToFraction(0.6), got no calls. It passes with this gate.

Actual Linux Tauri CEF, local EPUB and mocked cloud: the timestamp-only gate
with a 4.5s pull delay remains on page 1 after initial-page autosave; this
gate recovers page 66. Also verified saved page 11 survives a stale sibling
and a newer sibling still advances to page 66. Screenshots inspected.
Android and iPadOS app checks not run.

Reported by noideaforeal on GitHub (#7092).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(sync): expire first-pull exception after navigation

Clear the initial snapshot as soon as a committed location changes during
the first pull, so returning to that location cannot revive the exception
and allow an older sibling to override a saved rewind.

Verified 117 related tests across seven suites, lint/type checking and
format:check. The new round-trip test fails on ac9fa23f0 with an unexpected
goToFraction(0.6), and passes with this change. Production changes remain
confined to useProgressSync.ts.

Native Linux Tauri slow-pull and stale/newer sibling scenarios passed on
ac9fa23f0; this round-trip ordering is covered by the hook regression only.
Android and iPadOS app verification not run.

Reported by noideaforeal on GitHub (#7092).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(sync): capture fresh state before writing direction detection

Record a fresh copy's zero timestamp at mount, before document load can
update view settings and stamp updatedAt. Bind its baseline location when
progress first arrives, then retain the existing navigation invalidation.

Verified 118 related tests across seven suites, lint/type checking and
format:check. The new direction-detection test fails on 15eba5b32 with
expected goToFraction(0.6), no calls, and passes with this change.
Production changes remain confined to useProgressSync.ts.

This load ordering was verified in hook tests. Linux Tauri slow-pull and
stale/newer sibling checks passed on ac9fa23f0; native RTL/vertical checks,
Android and iPadOS verification not run.

Reported by noideaforeal on GitHub (#7092).

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-02 12:54:42 +08:00 • committed by GitHub
parent 212911d456
commit a2dd013a47
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 236 additions and 6 deletions

View file

@ -114,7 +114,12 @@ vi.mock('@/store/settingsStore', () => ({
}));
vi.mock('@/store/libraryStore', () => ({
useLibraryStore: h.makeStore({ library: [h.libraryBook] }),
useLibraryStore: h.makeStore({
library: [h.libraryBook],
getBookByHash: vi.fn((hash: string) =>
hash === h.libraryBook.hash ? h.libraryBook : undefined,
),
}),
}));
vi.mock('@/utils/serializer', () => ({
@ -187,6 +192,8 @@ beforeEach(() => {
h.getCFIFromXPointerMock.mockReset();
h.getCFIFromXPointerMock.mockResolvedValue('');
h.book.format = 'PDF';
h.config.location = 'cfi-loc';
h.config.updatedAt = 1000;
h.state.syncedConfigs = [];
h.state.progress = { location: 'cfi-loc' };
h.state.viewSettings = { proofreadRules: [] };
@ -909,6 +916,195 @@ describe('useProgressSync', () => {
});
});
describe('useProgressSync — duplicate copies (#7092)', () => {
const exact = (updatedAt = 2000) => ({
bookHash: 'h1',
metaHash: 'm1',
location: 'exact-location',
progress: [10, 100],
updatedAt,
});
const sibling = (updatedAt: number, current = 60) => ({
bookHash: 'h2',
metaHash: 'm1',
location: 'sibling-location',
progress: [current, 100],
updatedAt,
});
test.each([
1999, 2000,
])('ignores a sibling no newer than this file’s cloud save (%i)', async (updatedAt) => {
h.state.syncedConfigs = [sibling(updatedAt), exact()];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('ignores a sibling older than a local save even when it beats the cloud save', async () => {
h.state.syncedConfigs = [exact(500), sibling(999)];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('an old furthest copy does not mask a more recent eligible copy', async () => {
h.state.syncedConfigs = [sibling(1500, 90), sibling(3000, 40), exact()];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).toHaveBeenCalledWith(0.4);
expect(h.view.goTo).not.toHaveBeenCalled();
});
test('still restores a newer sibling by fraction on a first open', async () => {
h.state.syncedConfigs = [sibling(3000)];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).toHaveBeenCalledWith(0.6);
expect(h.view.goTo).not.toHaveBeenCalled();
});
test('an initial-page autosave does not block a slow first sibling pull', async () => {
h.config.updatedAt = 0;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
await advance(2000);
// Autosave stamps the unchanged initial page while the pull is pending.
h.config.updatedAt = 4000;
h.state.syncedConfigs = [sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).toHaveBeenCalledWith(0.6);
});
test('direction detection before the first relocation does not block sibling recovery', async () => {
h.config.location = '';
h.config.updatedAt = 0;
h.state.progress = null;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
// docLoadHandler detects RTL/vertical writing before the first relocate.
h.config.updatedAt = 4000;
h.config.location = 'cfi-start';
h.state.progress = { location: 'cfi-start', fraction: 0.01 };
rerender();
await advance(0);
h.state.syncedConfigs = [sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).toHaveBeenCalledWith(0.6);
});
test('the fresh-copy exception expires after the first response', async () => {
h.config.updatedAt = 0;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
h.config.updatedAt = 4000;
h.state.syncedConfigs = [];
rerender();
await advance(0);
await act(async () => {
for (const listener of h.eventListeners.get('sync-book-progress') ?? []) {
await listener(new CustomEvent('sync-book-progress', { detail: { bookKey: 'h1-view1' } }));
}
});
h.state.syncedConfigs = [sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('a saved move during the first pull still rejects an older sibling', async () => {
h.config.updatedAt = 0;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
await advance(2000);
h.config.location = 'user-destination';
h.config.updatedAt = 4000;
h.state.progress = { location: 'user-destination', fraction: 0.1 };
h.state.syncedConfigs = [sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('returning to the initial location does not revive the first-pull exception', async () => {
h.config.updatedAt = 0;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
h.config.location = 'user-destination';
h.config.updatedAt = 4000;
h.state.progress = { location: 'user-destination', fraction: 0.1 };
rerender();
await advance(0);
h.config.location = 'cfi-loc';
h.config.updatedAt = 5000;
h.state.progress = { location: 'cfi-loc', fraction: 0.05 };
h.state.syncedConfigs = [sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('a slow first pull still respects an exact cloud purge', async () => {
h.config.updatedAt = 0;
h.state.syncedConfigs = null;
const { rerender } = renderHook(() => useProgressSync('h1-view1'));
await advance(2000);
h.config.updatedAt = 5000;
h.state.syncedConfigs = [{ ...exact(4000), location: null, progress: null }, sibling(3000)];
rerender();
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('still applies the exact file’s forward location when a stale sibling is further', async () => {
h.cfiCompareMock.mockReturnValue(-1);
h.state.syncedConfigs = [sibling(1500, 90), exact()];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goTo).toHaveBeenCalledWith('exact-location');
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
test('a purged cloud position is not restored from an older copy', async () => {
h.state.syncedConfigs = [{ ...exact(4000), location: null, progress: null }, sibling(3000)];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
expect(h.view.goTo).not.toHaveBeenCalled();
});
test('does not move backward for a newer sibling', async () => {
h.state.progress = { location: 'cfi-loc', fraction: 0.8 };
h.state.syncedConfigs = [sibling(3000), exact()];
renderHook(() => useProgressSync('h1-view1'));
await advance(0);
expect(h.view.goToFraction).not.toHaveBeenCalled();
});
});
// Issue #5625. The Readest KOReader plugin pushes `progress` + `xpointer` and
// never a `location`, so the CREngine XPointer is the ONLY precise handle on
// the remote position. When converting it throws — a chapter whose XHTML isn't

View file

@ -68,6 +68,9 @@ export const useProgressSync = (bookKey: string) => {
const configPulled = useRef(false);
const hasPulledConfigOnce = useRef(false);
const initialPullConfig = useRef<{ location: BookConfig['location']; updatedAt: number } | null>(
null,
);
const pullAttempt = useRef(0);
const pullInFlight = useRef(false);
const pendingResumePull = useRef(false);
@ -144,6 +147,7 @@ export const useProgressSync = (bookKey: string) => {
// protects the cross-device case (a stale local push with an older
// updated_at will lose to a fresher server record).
configPulled.current = true;
initialPullConfig.current = null;
return;
}
const delay = PULL_RETRY_DELAYS_MS[pullAttempt.current]!;
@ -284,9 +288,28 @@ export const useProgressSync = (bookKey: string) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [progress?.location]);
// Writing-direction detection can stamp updatedAt before the first relocate.
useEffect(() => {
const config = getConfig(bookKey);
if (config && !config.updatedAt) {
initialPullConfig.current = { location: config.location, updatedAt: 0 };
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [bookKey]);
// Pull: pull progress once when the book is opened, with retry on failure
useEffect(() => {
if (!progress || hasPulledConfigOnce.current) return;
const config = getConfig(bookKey);
if (!progress) return;
if (!hasPulledConfigOnce.current && initialPullConfig.current) {
initialPullConfig.current.location = config?.location;
}
// A round trip is still a reading change; returning to the initial page
// must not revive the zero-timestamp exception while the pull is pending.
if (initialPullConfig.current && config?.location !== initialPullConfig.current.location) {
initialPullConfig.current = null;
}
if (hasPulledConfigOnce.current) return;
hasPulledConfigOnce.current = true;
pullWithRetry();
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -304,6 +327,8 @@ export const useProgressSync = (bookKey: string) => {
const applyRemoteProgress = async (syncedConfigs: BookConfig[]) => {
const config = getConfig(bookKey);
const book = getBookData(bookKey)?.book;
const initialConfig = initialPullConfig.current;
initialPullConfig.current = null;
if (!syncedConfigs || syncedConfigs.length === 0 || !config || !book) return;
const bookHash = bookKey.split('-')[0]!;
@ -360,11 +385,20 @@ export const useProgressSync = (bookKey: string) => {
if (exactConfig?.location && isMalformedLocationCfi(exactConfig.location)) {
exactConfig = { ...exactConfig, location: undefined };
}
// Furthest reading fraction among sibling copies (same metaHash, different
// book_hash). progress[0]/progress[1] compares across re-packaged copies
// of the same work; a CFI does not.
// Only a sibling newer than this file's local AND cloud saves may move
// it forward. Otherwise an old duplicate keeps pulling a deliberate
// rewind (or a purged position) back to its furthest page (#7092).
// Across different files only the reading fraction is comparable, not CFI.
// A fresh copy can autosave its initial page before the first pull lands.
// That timestamp is not a reading change. Once the location moves, use
// its current timestamp so a deliberate rewind still wins.
const localSavedAt =
initialConfig && config.location === initialConfig.location
? initialConfig.updatedAt
: (config.updatedAt ?? 0);
const savedAt = Math.max(localSavedAt, exactConfig?.updatedAt ?? 0);
const siblingFraction = matches
.filter((c) => c.bookHash !== bookHash)
.filter((c) => c.bookHash !== bookHash && (c.updatedAt ?? 0) > savedAt)
.reduce((best, c) => Math.max(best, getConfigFraction(c) ?? 0), 0);
const exactFraction = exactConfig ? (getConfigFraction(exactConfig) ?? 0) : 0;
const localFraction = getBookProgress(bookKey)?.fraction ?? getConfigFraction(config) ?? 0;