From 3e51d76d6beb369c327aa881eca3fdac0853c066 Mon Sep 17 00:00:00 2001 From: sudacode Date: Sun, 22 Nov 2026 14:32:41 -0800 Subject: [PATCH] fix(aniskip): address review findings on chapter writes, lookups and request spacing - Never rewrite chapter-list after a failed read, or after the media changed while the read was pending (also for marker removal). - Install file-chapter windows before the AniSkip lookup so their prompt and skip key work at once; AniSkip windows are merged in without resetting prompts already shown. - A lookup superseded by a refresh or media change no longer writes the cache. - A same-media reload retries a lookup that failed transiently. - Serialize AniSkip request slots so late timers cannot release a burst. --- src/main/runtime/aniskip-metadata.ts | 22 ++-- src/main/runtime/aniskip-runtime.test.ts | 133 ++++++++++++++++++++++- src/main/runtime/aniskip-runtime.ts | 86 +++++++++++---- 3 files changed, 211 insertions(+), 30 deletions(-) diff --git a/src/main/runtime/aniskip-metadata.ts b/src/main/runtime/aniskip-metadata.ts index c219a8f4..6d5224ba 100644 --- a/src/main/runtime/aniskip-metadata.ts +++ b/src/main/runtime/aniskip-metadata.ts @@ -315,15 +315,21 @@ async function fetchJson(url: string): Promise { } let lastAniSkipRequestAt = 0; +let aniSkipRequestQueue: Promise = Promise.resolve(); -async function waitForAniSkipRequestSlot(): Promise { - const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now(); - if (waitMs > 0) { - lastAniSkipRequestAt += ANISKIP_MIN_REQUEST_GAP_MS; - await new Promise((resolve) => setTimeout(resolve, waitMs)); - return; - } - lastAniSkipRequestAt = Date.now(); +/** + * Resolves when the caller may send its AniSkip request. Callers are released + * one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous + * release, so timers that fire late cannot release a burst. + */ +function waitForAniSkipRequestSlot(): Promise { + const slot = aniSkipRequestQueue.then(async () => { + const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now(); + if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs)); + lastAniSkipRequestAt = Date.now(); + }); + aniSkipRequestQueue = slot; + return slot; } async function resolveMalIdFromTitle(title: string, season: number | null): Promise { diff --git a/src/main/runtime/aniskip-runtime.test.ts b/src/main/runtime/aniskip-runtime.test.ts index 3d3ec985..7e368b24 100644 --- a/src/main/runtime/aniskip-runtime.test.ts +++ b/src/main/runtime/aniskip-runtime.test.ts @@ -39,6 +39,9 @@ function createHarness(options?: { duration: options?.duration === undefined ? 1440 : options.duration, timePos: 0, chapterList: options?.chapterList ?? [], + chapterListFails: false, + // When set, chapter-list reads wait for it before answering. + chapterGate: null as Promise | null, }; const deps = { @@ -57,7 +60,11 @@ function createHarness(options?: { state.commands.push(command); }, requestMpvProperty: async (name) => { - if (name === 'chapter-list') return state.chapterList; + if (name === 'chapter-list') { + if (state.chapterGate) await state.chapterGate; + if (state.chapterListFails) throw new Error('property unavailable'); + return state.chapterList; + } if (name === 'duration') { if (state.duration === null) throw new Error('property unavailable'); return state.duration; @@ -394,3 +401,127 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => { ['keybind', 'TAB', 'script-message subminer-skip-intro'], ]); }); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +test('a failed chapter-list read leaves the file chapters untouched', async () => { + const harness = createHarness({ + chapterList: [{ time: 0, title: 'Prologue' }], + metadata: async () => { + harness.state.chapterListFails = true; + return readyMetadata(); + }, + }); + harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + + assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip'); + assert.equal(chapterListCommands(harness.state.commands).length, 0); +}); + +test('markers are not written into a file that replaced the one being read', async () => { + const gate = deferred(); + let calls = 0; + const harness = createHarness({ + metadata: async () => { + calls += 1; + if (calls === 1) { + harness.state.chapterGate = gate.promise; + return readyMetadata(); + } + return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }); + }, + }); + harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' }); + await flushAsync(); + // The marker write for a.mkv is waiting on its chapter-list read. + harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' }); + harness.state.chapterGate = null; + gate.resolve(); + await flushAsync(); + await flushAsync(); + + assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']); + assert.equal(chapterListCommands(harness.state.commands).length, 0); +}); + +test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => { + const lookup = deferred(); + const { runtime, state } = createHarness({ + chapterList: [ + { time: 0, title: 'Opening' }, + { time: 90, title: 'Episode' }, + ], + metadata: () => lookup.promise, + }); + runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + + assert.deepEqual(runtime.getSkipWindows(), { + intro: { start: 0, end: 90, source: 'chapters' }, + outro: null, + }); + runtime.handleTimePosChange({ time: 1 }); + assert.equal(state.osd.length, 1); + + lookup.resolve( + readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }), + ); + await flushAsync(); + + assert.deepEqual(runtime.getSkipWindows(), { + intro: { start: 0, end: 90, source: 'chapters' }, + outro: { start: 1330, end: 1420, source: 'aniskip' }, + }); + // The intro prompt already shown is not shown again. + runtime.handleTimePosChange({ time: 1.5 }); + assert.equal(state.osd.length, 1); +}); + +test('a lookup superseded by a refresh does not overwrite the cache', async () => { + const first = deferred(); + let calls = 0; + const { runtime, state } = createHarness({ + metadata: () => { + calls += 1; + return calls === 1 ? first.promise : Promise.resolve(readyMetadata()); + }, + }); + runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] }); + await flushAsync(); + first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' })); + await flushAsync(); + + runtime.handleMediaPathChange({ path: '/media/other.mkv' }); + await flushAsync(); + runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']); + assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' }); +}); + +test('a same-media reload retries a transient lookup failure', async () => { + let calls = 0; + const { runtime, state } = createHarness({ + metadata: async () => { + calls += 1; + return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {}); + }, + }); + runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES); + + runtime.handleMediaPathChange({ path: '/media/show.mkv' }); + await flushAsync(); + assert.equal(state.resolveCalls.length, 2); + assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' }); +}); diff --git a/src/main/runtime/aniskip-runtime.ts b/src/main/runtime/aniskip-runtime.ts index b6734fae..4c3257b2 100644 --- a/src/main/runtime/aniskip-runtime.ts +++ b/src/main/runtime/aniskip-runtime.ts @@ -81,6 +81,8 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { let currentDuration: number | null = null; // True once resolution for the current media has started (or finished). let resolutionStarted = false; + // True when the last AniSkip lookup for the current media failed in a retryable way. + let lastLookupFailed = false; let windows: AniSkipWindows = { intro: null, outro: null }; const promptShown: Record = { intro: false, outro: false }; let boundButtonKey: string | null = null; @@ -142,8 +144,15 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { } } + /** True while the given request generation still owns the given media. */ + function ownsPlayback(generation: number, mediaPath: string): boolean { + return generation === requestGeneration && mediaPath === currentMediaPath; + } + /** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */ async function setSkipChapters(): Promise { + const generation = requestGeneration; + const mediaPath = currentMediaPath; const markers: MpvChapter[] = []; for (const kind of ['intro', 'outro'] as const) { const window = windows[kind]; @@ -153,7 +162,10 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` }); } if (markers.length === 0) return; - const existing = (await readChapterList()) ?? []; + const existing = await readChapterList(); + // A failed read must not wipe the file's chapters, and a read that finished + // after the media changed must not write into the next file. + if (!existing || !ownsPlayback(generation, mediaPath)) return; const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers); chapters.sort((a, b) => { const aTime = typeof a.time === 'number' ? a.time : 0; @@ -165,8 +177,10 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { async function removeSkipChapters(): Promise { if (!deps.isMpvConnected()) return; + const generation = requestGeneration; + const mediaPath = currentMediaPath; const existing = await readChapterList(); - if (!existing) return; + if (!existing || !ownsPlayback(generation, mediaPath)) return; const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter)); if (filtered.length !== existing.length) { deps.sendMpvCommand(['set_property', 'chapter-list', filtered]); @@ -176,31 +190,57 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { function clearState(): void { requestGeneration += 1; resolutionStarted = false; + lastLookupFailed = false; windows = { intro: null, outro: null }; promptShown.intro = false; promptShown.outro = false; } - async function applyWindows(next: AniSkipWindows, malId: number | null): Promise { + function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void { + deps.logInfo( + `AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${ + window.source + }, MAL ${malId ?? '-'})`, + ); + } + + /** Installs the file-chapter windows, resetting the prompts. */ + function applyChapterWindows(next: AniSkipWindows): void { windows = next; promptShown.intro = false; promptShown.outro = false; - await setSkipChapters(); for (const kind of ['intro', 'outro'] as const) { const window = next[kind]; - if (!window) continue; - deps.logInfo( - `AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${ - window.source - }, MAL ${malId ?? '-'})`, - ); + if (window) logWindow(kind, window, null); } } + /** + * Fills the windows the chapters lacked from AniSkip, leaving the chapter + * windows (and whether their prompt was shown) untouched. + */ + async function mergeAniSkipWindows(lookup: AniSkipLookupResult): Promise { + const added: SkipWindowKind[] = []; + for (const kind of ['intro', 'outro'] as const) { + const interval = lookup[kind]; + if (windows[kind] || !interval) continue; + windows = { ...windows, [kind]: { ...interval, source: 'aniskip' } }; + promptShown[kind] = false; + added.push(kind); + } + if (added.length === 0) return; + for (const kind of added) { + const window = windows[kind]; + if (window) logWindow(kind, window, lookup.malId); + } + await setSkipChapters(); + } + /** Looks up AniSkip, using the cache for definitive answers. Null means a retryable failure. */ async function lookUpAniSkip( mediaPath: string, duration: number, + generation: number, ): Promise { const cached = lookupCache.get(mediaPath); if (cached) return cached; @@ -221,8 +261,9 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`); return null; } - // Every other status is definitive (a 404 or an unmatched title), so cache it. - lookupCache.set(mediaPath, result); + // Every other status is definitive (a 404 or an unmatched title), so cache it, + // unless a refresh or media change superseded this lookup while it ran. + if (generation === requestGeneration) lookupCache.set(mediaPath, result); if (metadata.lookupStatus !== 'ready') { deps.logInfo( `AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`, @@ -242,21 +283,18 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null, outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null, }; - if (next.intro && next.outro) { - await applyWindows(next, null); - return; - } + // Chapter windows work right away; AniSkip only fills what they lack. + applyChapterWindows(next); + if (next.intro && next.outro) return; if (isRemoteMediaPath(mediaPath)) { deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only'); - await applyWindows(next, null); return; } - const lookup = await lookUpAniSkip(mediaPath, duration); + const lookup = await lookUpAniSkip(mediaPath, duration, generation); if (isStale()) return; - if (!next.intro && lookup?.intro) next.intro = { ...lookup.intro, source: 'aniskip' }; - if (!next.outro && lookup?.outro) next.outro = { ...lookup.outro, source: 'aniskip' }; - await applyWindows(next, lookup?.malId ?? null); + lastLookupFailed = lookup === null; + if (lookup) await mergeAniSkipWindows(lookup); } /** Starts resolution once the current media has both a path and a known duration. */ @@ -342,6 +380,12 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) { function handleMediaPathChange({ path }: { path: string }): void { const nextPath = typeof path === 'string' ? path : ''; if (nextPath === currentMediaPath && resolutionStarted) { + if (lastLookupFailed) { + // The last lookup failed transiently; a reload is the retry. + clearState(); + maybeStartResolution(); + return; + } // Same-media reload: mpv rebuilt the chapter list, so re-apply markers. void setSkipChapters().catch(() => {}); return;