Compare commits

..
19 Commits
Author SHA1 Message Date
sudacode 8e47e0d761 fix(anki): trim timing review clips to dialogue end
- Auto-adjust untouched clip ends after waveform analysis
- Document and test trailing-silence trimming behavior
2026-09-02 23:43:34 -07:00
sudacode dcd05ee4ea Merge remote-tracking branch 'origin/main' into t3code/media-timing-review 2026-09-02 22:54:30 -07:00
sudacode 56a2a25312 fix(anki): wait for media timing previews to fully finish
- Wait for mpv to drain audio before ending previews
- Notify the review modal when playback actually completes
2026-09-02 18:44:37 -07:00
sudacode c85db5e07e fix(mining): ignore stale captions and improve waveform contrast
- Use active parsed cue text and timings for overlay mining
- Normalize waveform levels against the clip's noise floor
2026-09-02 18:22:03 -07:00
sudacode f90ee78204 feat(mining): cache remote media windows during card creation
- Reuse one temporary download for timing review, audio, and screenshots
- Expire cached windows after inactivity and clean them up on exit
2026-09-02 01:21:26 -07:00
sudacode 760b3e1d3d test(immersion): wrap vocabulary fixture inserts in a transaction 2026-09-02 00:01:01 -07:00
sudacode 4d5ea8801f feat(anki): add Senren scene-switching field grouping
- Support auto, manual, and disabled Senren duplicate-card merges
- Group sentence, furigana, audio, picture, and miscInfo fields
2026-09-01 23:22:54 -07:00
sudacode b58f391b42 fix: handle notification changes and timing review text safely
- Dismiss stale overlay progress when notification mode changes
- Validate and forward combined timing review text
- Keep macOS timing preview socket paths within system limits
2026-08-30 02:49:37 -07:00
sudacode 90a5dcd2af fix(anki): move line boundary markers with added subtitle lines 2026-08-30 02:38:28 -07:00
sudacode 989122c006 test(anki): mock note deletion in manual update tests 2026-08-30 02:03:02 -07:00
sudacode ad1c1aea1b feat(anki): add multi-line subtitle selection to media timing review 2026-08-30 01:56:16 -07:00
sudacode 62d645e577 fix: apply CodeRabbit auto-fixes 2026-08-30 01:56:16 -07:00
sudacode f36e7f6182 feat(anki): add runtime toggle for media timing review
- Add session-only runtime option with live config hot-reload support
- Document the runtime palette toggle
2026-08-30 01:56:16 -07:00
sudacode 475f81d96d fix(anki): allow timing review cards without media
- Keep existing or create new cards without generating audio or images
- Refine timing review timeline expansion labels and boundary markers
2026-08-30 01:56:16 -07:00
sudacode 046ab59da9 fix(anki): clarify media timing review subtitle boundaries
- Compact the timing review layout
- Label mined subtitle line start and end boundaries
2026-08-30 01:56:16 -07:00
sudacode e91f031faa fix(anki): keep media timing review keyboard-focused
- Route modal keydown events before later modal handlers
- Restore focus and preserve visible focus styling
2026-08-30 01:56:16 -07:00
sudacode ec6a106748 fix(anki): prevent media timing review hangs and invalid ranges
- Reject stale or invalid timing actions
- Fall back to original timing when the renderer stops responding
2026-08-30 01:56:16 -07:00
sudacode ca27a4275f feat(anki): add waveform-guided timing controls
- Add speech-weighted waveform analysis and playback playhead
- Support dragging, sliding, and keyboard nudging for clip timing
2026-08-30 01:56:16 -07:00
sudacode 256eb5da1b feat(anki): add media timing review before card creation
- Add draggable timing previews with audio playback and exact media ranges
- Support cancellation choices, including deleting existing cards
2026-08-30 01:56:16 -07:00
22 changed files with 64 additions and 281 deletions
-31
View File
@@ -1,36 +1,5 @@
# Changelog
## v0.19.6 (2026-09-04)
### Added
- **Card Timing Review**:
- Optional pre-generation timing review for word, sentence, and audio cards, with a speech-weighted waveform that flattens background noise so dialogue edges stand out clearly.
- The clip end automatically snaps back to where the line's dialogue actually ends once the waveform loads, with drag and keyboard adjustments available.
- Audio preview includes a sweeping playhead that plays the clip to its true end, even on high-latency outputs like Bluetooth headphones.
- Previous and next subtitle lines can be pulled onto the card with `P`/`N` (or the Prev/Next steppers) and removed with Shift; the sentence preview and waveform markers update automatically.
- Cancelling lets you keep a card without media, and the review can be toggled on or off for the session.
- **Senren Field Grouping**:
- Enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, grouping sentence, furigana, audio, picture, and misc-info fields.
- Supports the same auto/manual/disabled modes as Kiku, including the manual merge modal; only one of Senren or Kiku can be enabled at a time.
### Changed
- **Remote Stream Mining Performance**: Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream at each step; the temporary file is cleaned up after ten minutes of inactivity or on exit.
- **TsukiHime Release Filtering**: The TsukiHime modal's Japanese and secondary-language tabs now filter the release list by the subtitle languages each release actually carries, and report when no release has subtitles for the active tab.
### Fixed
- **Subtitle & Mining Accuracy**:
- Broadcast-style captions that split one sentence across two on-screen rows (e.g. Crunchyroll Japanese subs) now merge into a single line for the sidebar and mined cards, while separate speakers, sound effects, and labeled turns still stay on their own lines.
- Mining from the overlay no longer pulls in a lingering row from the previous caption; the mined sentence and clip timing now match what's actually on screen.
- Multi-line copy and mining now select lines backward in timeline order after seeking, instead of in playback encounter order.
- Copying a subtitle, mining a sentence, or recording immersion stats no longer includes the separate furigana line that broadcast ASS captions place above a word.
- **Card Update Notifications**: Dismissed lingering overlay card-update progress when notification settings switch to OSD before an update finishes.
- **Overlay Stability on Hyprland**: Opening a modal window (timing review, Jimaku, session help, and others) while mpv is fullscreen no longer causes the overlay to flicker while the modal loads; the overlay now stays on screen untouched until the modal is ready.
- **Jellyfin Subtitle Sync**: Jellyfin subtitle files now load with zero mpv delay instead of inferring and saving an offset from Japanese and English cue timelines.
- **Secondary Subtitle Visibility**: Native mpv secondary subtitles stay hidden when switching secondary subtitle tracks during playback.
## v0.19.5 (2026-08-30)
### Fixed
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: anki
- Dismissed active overlay card-update progress when notification settings switch to OSD before an update finishes.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Broadcast-style Japanese caption tracks (Crunchyroll JA subs) that split one sentence across two positioned events now publish it as a single line, so `preserveLineBreaks: false` flattens it, the sidebar lists it once, and mined sentences are whole. Rows from two different speakers, sound effects, and labeled turns still stay on separate lines.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: jellyfin
- Jellyfin subtitle files now load with zero mpv delay instead of inferring and saving an offset from Japanese and English cue timelines.
+5
View File
@@ -0,0 +1,5 @@
type: added
area: mining
- Added optional pre-generation timing review for word, sentence, and audio cards with a compact speech-weighted waveform that flattens steady background noise so dialogue edges are easy to see, clearly labeled mined-line boundaries, a clip end that moves back to where the line's dialogue actually ends once the waveform loads (subtitles usually linger past speech), drag and keyboard adjustments, audio preview with a sweeping playhead that plays the clip to its true end even on high-latency outputs such as Bluetooth headphones, exact screenshot and AVIF timing, cancellation choices that include keeping a card without media, and a session-only runtime toggle.
- The timing review can pull any number of previous and next subtitle lines onto the card: `P`/`N` (or the Prev/Next steppers) add lines one at a time, Shift removes them, the sentence preview highlights exactly what the card will contain, and the clip range and line boundary markers on the waveform follow the added lines automatically.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: mining
- Mining from the overlay no longer copies a lingering row of the previous broadcast caption onto the card sentence. The mined line and its clip timing now come from the parsed cue the overlay is showing, falling back to mpv's live text only when the cue list cannot explain it.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: mining
- Multi-line copy and mining now select backward from the current subtitle in timeline order after seeking, instead of copying lines in playback encounter order. Jumping back to a short previous line also counts as a seek with external subtitle files, so that line becomes the current one.
+4
View File
@@ -0,0 +1,4 @@
type: changed
area: mining
- Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once into a temporary file and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream for every step. The temporary window is removed after ten minutes without use or on exit.
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Native mpv secondary subtitles stay hidden when switching secondary subtitle tracks during playback.
+5
View File
@@ -0,0 +1,5 @@
type: added
area: anki
- Senren note type support for duplicate-card field grouping: enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, with grouped sentence, furigana, audio, picture, and miscInfo entries.
- Senren field grouping supports the same auto/manual/disabled modes as Kiku, including the manual merge modal, and is mutually exclusive with Kiku (only one can be enabled at a time).
@@ -0,0 +1,4 @@
type: fixed
area: subtitles
- Copying the current subtitle, Anki sentence mining from recent lines, and immersion stats no longer include the separate furigana lines that broadcast-caption ASS files place above a word; recorders now use the same furigana-free text the overlay displays.
+4
View File
@@ -0,0 +1,4 @@
type: changed
area: overlay
- The TsukiHime modal's Japanese and secondary-language tabs now filter the release list by the subtitle languages each release carries, and report when no release has subtitles for the active tab.
-31
View File
@@ -1,36 +1,5 @@
# Changelog
## v0.19.6 (2026-09-04)
**Added**
- **Card Timing Review**:
- Optional pre-generation timing review for word, sentence, and audio cards, with a speech-weighted waveform that flattens background noise so dialogue edges stand out clearly.
- The clip end automatically snaps back to where the line's dialogue actually ends once the waveform loads, with drag and keyboard adjustments available.
- Audio preview includes a sweeping playhead that plays the clip to its true end, even on high-latency outputs like Bluetooth headphones.
- Previous and next subtitle lines can be pulled onto the card with `P`/`N` (or the Prev/Next steppers) and removed with Shift; the sentence preview and waveform markers update automatically.
- Cancelling lets you keep a card without media, and the review can be toggled on or off for the session.
- **Senren Field Grouping**:
- Enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, grouping sentence, furigana, audio, picture, and misc-info fields.
- Supports the same auto/manual/disabled modes as Kiku, including the manual merge modal; only one of Senren or Kiku can be enabled at a time.
**Changed**
- **Remote Stream Mining Performance**: Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream at each step; the temporary file is cleaned up after ten minutes of inactivity or on exit.
- **TsukiHime Release Filtering**: The TsukiHime modal's Japanese and secondary-language tabs now filter the release list by the subtitle languages each release actually carries, and report when no release has subtitles for the active tab.
**Fixed**
- **Subtitle & Mining Accuracy**:
- Broadcast-style captions that split one sentence across two on-screen rows (e.g. Crunchyroll Japanese subs) now merge into a single line for the sidebar and mined cards, while separate speakers, sound effects, and labeled turns still stay on their own lines.
- Mining from the overlay no longer pulls in a lingering row from the previous caption; the mined sentence and clip timing now match what's actually on screen.
- Multi-line copy and mining now select lines backward in timeline order after seeking, instead of in playback encounter order.
- Copying a subtitle, mining a sentence, or recording immersion stats no longer includes the separate furigana line that broadcast ASS captions place above a word.
- **Card Update Notifications**: Dismissed lingering overlay card-update progress when notification settings switch to OSD before an update finishes.
- **Overlay Stability on Hyprland**: Opening a modal window (timing review, Jimaku, session help, and others) while mpv is fullscreen no longer causes the overlay to flicker while the modal loads; the overlay now stays on screen untouched until the modal is ready.
- **Jellyfin Subtitle Sync**: Jellyfin subtitle files now load with zero mpv delay instead of inferring and saving an offset from Japanese and English cue timelines.
- **Secondary Subtitle Visibility**: Native mpv secondary subtitles stay hidden when switching secondary subtitle tracks during playback.
## v0.19.5 (2026-08-30)
**Fixed**
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
"version": "0.19.6",
"version": "0.19.5",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
-51
View File
@@ -1,51 +0,0 @@
## Highlights
### Added
- **Pre-Mining Timing Review**:
- Optional review step before creating word, sentence, or audio cards, with a speech-focused waveform that filters out steady background noise so dialogue is easy to spot.
- The clip end automatically snaps back to where dialogue actually ends, since subtitles often linger after speech stops.
- Drag or use the keyboard to adjust clip boundaries, and preview audio with a sweeping playhead that plays to the true end even on high-latency outputs like Bluetooth headphones.
- Pull extra previous or next subtitle lines onto the card with `P`/`N` (or the Prev/Next steppers); a live preview shows exactly what the card will contain.
- You can cancel and still keep the card without media, and the review can be toggled on or off for the session.
- **Senren Note Type Support**:
- Enable `ankiConnect.isSenren` to merge duplicate mined cards using Senren's scene-switching markup, combining sentence, furigana, audio, picture, and misc-info fields.
- Supports the same auto/manual/disabled grouping modes as Kiku, including the manual merge modal. Senren and Kiku are mutually exclusive, so only one can be enabled at a time.
### Changed
- **Remote Streaming Mining**: Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream for every step. No action needed; the temporary download is cleaned up automatically after ten minutes of inactivity.
- **TsukiHime Release Picker**: The Japanese and secondary-language tabs now filter releases down to ones that actually carry subtitles for that language, and tell you when none do.
### Fixed
- **Broadcast Caption Accuracy**:
- Japanese caption tracks split across two positioned lines (e.g. Crunchyroll) now merge into one, so mined sentences, the sidebar, and line-break settings treat them as a single line; lines from different speakers or sound effects still stay separate.
- Mining from the overlay no longer picks up a leftover line from the previous caption, so the mined sentence and clip timing match what's actually on screen.
- Copying or mining subtitles no longer includes the separate furigana line that some broadcast subtitle files place above kanji.
- **Multi-line Copy After Seeking**: Selecting multiple subtitle lines to copy or mine now selects backward in timeline order after a seek, rather than in playback encounter order.
- **Overlay Stability**:
- On Hyprland, opening a modal (timing review, Jimaku, session help, and others) over fullscreen mpv no longer makes the overlay flicker while the modal loads.
- Switching secondary subtitle tracks no longer causes mpv's native secondary subtitles to flash on screen.
- **Anki Update Notifications**: Switching notification settings to on-screen display while a card update is still in progress now correctly dismisses the old overlay progress indicator.
- **Jellyfin Subtitles**: Subtitle files now load with zero delay in mpv instead of Jellyfin inferring and applying a sync offset.
## What's Changed
- feat(anki): add media timing review before card creation by @ksyasuda in #203
- fix(jellyfin): stop inferring subtitle delays by @ksyasuda in #227
- feat(anki): support Senren scene-switching field grouping by @ksyasuda in #230
- fix(mining): copy multi-line subtitles backward from current line by @ksyasuda in #231
- fix(subtitles): keep native secondary subtitles hidden by @ksyasuda in #232
- fix(subtitles): drop ASS furigana from recorded cues by @ksyasuda in #233
- fix(subtitles): merge wrapped positioned caption rows by @ksyasuda in #234
- fix(tsukihime): filter releases by subtitle language by @ksyasuda in #235
## Installation
See the README and docs/installation guide for full setup steps.
## Assets
- Linux: `SubMiner.AppImage`
- macOS: `SubMiner-*.dmg` and `SubMiner-*.zip`
- Windows: `SubMiner-*.exe` and `SubMiner-*-win.zip`
- Optional extras: `subminer-assets.tar.gz` and the `subminer` launcher
Note: the `subminer` wrapper script uses Bun (`#!/usr/bin/env bun`), so `bun` must be installed and on `PATH`.
-60
View File
@@ -828,7 +828,6 @@ test('modal fallback reveal skips showing window when content is not ready', asy
setModalWindowBounds: () => {},
},
{
platform: 'darwin',
scheduleRevealFallback: (callback) => {
scheduledReveal = callback;
return { scheduled: true } as never;
@@ -1364,62 +1363,3 @@ test('modal placement reconcile cancels stale retry ladder after a newer visible
globalThis.clearTimeout = originalClearTimeout;
}
});
test('Linux keeps the dedicated modal window unmapped until the renderer opens the modal, then hides the overlay before revealing it', () => {
const mainWindow = createMockWindow();
mainWindow.visible = true;
const modalWindow = createMockWindow();
const order: string[] = [];
const hideMain = mainWindow.hide;
mainWindow.hide = () => {
order.push('main:hide');
hideMain();
};
const showModal = modalWindow.show;
modalWindow.show = () => {
order.push('modal:show');
showModal();
};
let revealScheduled = false;
const runtime = createOverlayModalRuntimeService(
{
getMainWindow: () => mainWindow as never,
getModalWindow: () => modalWindow as never,
createModalWindow: () => modalWindow as never,
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
setModalWindowBounds: () => {},
},
{
platform: 'linux',
scheduleRevealFallback: () => {
revealScheduled = true;
return { scheduled: true } as never;
},
clearRevealFallback: () => {},
},
);
const open = () =>
runtime.sendToActiveOverlayWindow(
'media-timing-review:open',
{ reviewId: 'review' },
{ restoreOnModalClose: 'media-timing-review', preferModalWindow: true },
);
assert.equal(open(), true);
assert.deepEqual(modalWindow.sent, [['media-timing-review:open', { reviewId: 'review' }]]);
assert.equal(revealScheduled, false);
assert.equal(modalWindow.getShowCount(), 0);
assert.equal(mainWindow.getHideCount(), 0);
// The open retry must not map the window before the renderer answers either.
assert.equal(open(), true);
assert.equal(modalWindow.getShowCount(), 0);
runtime.notifyOverlayModalOpened('media-timing-review');
assert.deepEqual(order, ['main:hide', 'modal:show']);
assert.equal(mainWindow.isVisible(), false);
assert.equal(modalWindow.isVisible(), true);
assert.equal(modalWindow.ignoreMouseEvents, false);
});
+5 -21
View File
@@ -90,12 +90,6 @@ export function createOverlayModalRuntimeService(
const platform = options.platform ?? process.platform;
const shouldPrimeModalWindow = platform === 'darwin' || platform === 'win32';
const reuseModalWindowAfterClose = platform === 'darwin';
// On Linux (Hyprland) every placement dispatch on a mapped window (resize, move, set_prop)
// blanks the still-visible overlay for a few frames while mpv is fullscreen. Revealing the
// dedicated modal window before its renderer has the modal open runs the placement ladder,
// and the open retry, against a visible overlay, which the user sees as flicker. Keep the
// window unmapped until the renderer acknowledges the open, then hide the overlay first.
const deferModalRevealUntilOpened = platform === 'linux';
const focusApplication = options.focusApplication ?? requestOverlayApplicationFocus;
const scheduleRevealFallback = (callback: () => void, delayMs: number): RevealFallbackHandle =>
(options.scheduleRevealFallback ?? globalThis.setTimeout)(callback, delayMs);
@@ -463,9 +457,7 @@ export function createOverlayModalRuntimeService(
deps.setModalWindowBounds(deps.getModalGeometry());
const wasVisible = modalWindow.isVisible();
if (!wasVisible) {
if (deferModalRevealUntilOpened) {
// notifyOverlayModalOpened reveals the window once the renderer has the modal open.
} else if (modalWindowPrimedForImmediateShow && isWindowReadyForIpc(modalWindow)) {
if (modalWindowPrimedForImmediateShow && isWindowReadyForIpc(modalWindow)) {
showModalWindow(modalWindow);
} else {
scheduleModalWindowReveal(modalWindow);
@@ -568,23 +560,15 @@ export function createOverlayModalRuntimeService(
}
const modalWindow = deps.getModalWindow();
const targetIsModalWindow =
modalWindow !== null && !modalWindow.isDestroyed() && targetWindow === modalWindow;
const handOffMainWindowToModal = (): void => {
setMainWindowMousePassthroughForModal(true);
setMainWindowVisibilityForModal(true);
};
if (targetIsModalWindow && deferModalRevealUntilOpened) {
handOffMainWindowToModal();
}
if (targetWindow.isVisible()) {
ensureModalWindowInteractive(targetWindow);
} else {
showModalWindow(targetWindow);
}
if (targetIsModalWindow && !deferModalRevealUntilOpened) {
handOffMainWindowToModal();
if (modalWindow && !modalWindow.isDestroyed() && targetWindow === modalWindow) {
setMainWindowMousePassthroughForModal(true);
setMainWindowVisibilityForModal(true);
}
};
+1 -3
View File
@@ -25,9 +25,7 @@ export async function openMediaTimingReviewModal(
{ waitForModalOpen: deps.waitForModalOpen, logWarn: deps.logWarn },
{
modal: MODAL,
// The review renderer regularly needs more than the 1.5 s the other modals allow; a
// premature retry re-sends the payload and reloads the waveform for nothing.
timeoutMs: 4_000,
timeoutMs: 1_500,
retryWarning:
'Media timing review did not acknowledge modal open; retrying the dedicated modal window.',
sendOpen: () =>
+3 -39
View File
@@ -78,8 +78,6 @@ async function startActiveMediaTimingReview(
options: {
maxMediaDuration?: number;
decisionTimeoutMs?: number;
generateWaveform?: () => Promise<number[]>;
play?: () => Promise<void>;
} = {},
) {
const previewCalls: Array<[number, number]> = [];
@@ -96,13 +94,12 @@ async function startActiveMediaTimingReview(
}),
getCurrentMediaPath: () => '/video/show.mkv',
getMpvExecutablePath: () => 'mpv',
generateWaveform: options.generateWaveform ?? (async () => []),
generateWaveform: async () => [],
decisionTimeoutMs: options.decisionTimeoutMs,
createPreviewSession: () => ({
start: async () => undefined,
play: async (startTime, endTime) => {
previewCalls.push([startTime, endTime]);
await options.play?.();
},
stop: async () => undefined,
onPlaybackEnded: () => undefined,
@@ -552,14 +549,14 @@ test('media timing review rejects stale and out-of-range actions before allowing
assert.deepEqual(
await runtime.previewRange({ reviewId: 'stale-review', startTime: 10, endTime: 12 }),
{ ok: false, stale: true, message: 'This timing review is no longer active.' },
{ ok: false, message: 'This timing review is no longer active.' },
);
assert.deepEqual(
runtime.resolveReview({
reviewId: 'stale-review',
decision: { action: 'confirm', startTime: 10, endTime: 12 },
}),
{ ok: false, stale: true, message: 'This timing review is no longer active.' },
{ ok: false, message: 'This timing review is no longer active.' },
);
assert.deepEqual(
runtime.resolveReview({
@@ -824,36 +821,3 @@ test('media timing review forwards the hidden player finishing a preview to the
playback.ended();
assert.deepEqual(endedReviewIds, [payload.reviewId]);
});
test('preview reports a stale review when the review ends during playback', async () => {
let endReview: (() => Promise<void>) | null = null;
const { runtime, payload, pendingDecision } = await startActiveMediaTimingReview({
play: async () => {
await endReview?.();
},
});
endReview = () => runtime.dispose();
assert.deepEqual(
await runtime.previewRange({ reviewId: payload.reviewId, startTime: 10, endTime: 12 }),
{ ok: false, stale: true, message: 'This timing review is no longer active.' },
);
await pendingDecision;
});
test('waveform reports a stale review when the review ends during analysis', async () => {
let endReview: (() => Promise<void>) | null = null;
const { runtime, payload, pendingDecision } = await startActiveMediaTimingReview({
generateWaveform: async () => {
await endReview?.();
return [0.1, 0.9, 0.2];
},
});
endReview = () => runtime.dispose();
assert.deepEqual(
await runtime.getWaveform({ reviewId: payload.reviewId, startTime: 8, endTime: 14 }),
{ ok: false, stale: true, message: 'This timing review is no longer active.' },
);
await pendingDecision;
});
+7 -31
View File
@@ -159,15 +159,6 @@ export function collectMediaTimingContextLines(options: {
return { previous, next };
}
/**
* Result for requests that name a review main has already resolved or disposed (decision
* watchdog, overlay teardown, duplicate modal). The renderer closes on it instead of
* leaving the user with controls that can never succeed.
*/
function staleReviewResult(): MediaTimingReviewActionResult {
return { ok: false, stale: true, message: 'This timing review is no longer active.' };
}
function isValidMediaTimingRange(
payload: MediaTimingReviewOpenPayload,
startTime: number,
@@ -452,7 +443,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
): Promise<MediaTimingReviewActionResult> {
const current = active;
if (!current || request.reviewId !== current.payload.reviewId) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
if (!isValidMediaTimingRange(current.payload, request.startTime, request.endTime)) {
return { ok: false, message: 'The selected preview range is invalid.' };
@@ -460,19 +451,11 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
try {
const previewSession = await previewFor(current, request);
if (active !== current) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
await previewSession.play(request.startTime, request.endTime);
// Playback spans the whole clip, so the review can end (watchdog, teardown) while
// it runs; reporting success would leave the modal open on a dead review.
if (active !== current) {
return staleReviewResult();
}
return { ok: true };
} catch (error) {
if (active !== current) {
return staleReviewResult();
}
return {
ok: false,
message: `Audio preview unavailable: ${error instanceof Error ? error.message : String(error)}`,
@@ -485,7 +468,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
): Promise<MediaTimingReviewWaveformResult> {
const current = active;
if (!current || request.reviewId !== current.payload.reviewId) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
if (
!Number.isFinite(request.startTime) ||
@@ -501,7 +484,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
try {
const window = await ensureWindow(current, request);
if (active !== current) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
const peaks = await deps.generateWaveform({
mediaPath: window?.media ?? current.waveformMedia,
@@ -511,18 +494,11 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
? { audioStreamIndex: current.audioStreamIndex }
: {}),
});
// ffmpeg decoding runs long enough for the review to end underneath it.
if (active !== current) {
return staleReviewResult();
}
if (peaks.length < 2 || peaks.some((peak) => !Number.isFinite(peak))) {
if (active !== current || peaks.length < 2 || peaks.some((peak) => !Number.isFinite(peak))) {
return { ok: false, message: 'Timing waveform is unavailable.' };
}
return { ok: true, peaks };
} catch {
if (active !== current) {
return staleReviewResult();
}
return { ok: false, message: 'Timing waveform is unavailable.' };
}
}
@@ -530,7 +506,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
async function stopPreview(reviewId: string): Promise<MediaTimingReviewActionResult> {
const current = active;
if (!current || reviewId !== current.payload.reviewId) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
try {
const previewSession = current.preview ? await current.preview.session : null;
@@ -547,7 +523,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
function resolveReview(request: MediaTimingReviewResolveRequest): MediaTimingReviewActionResult {
const current = active;
if (!current || request.reviewId !== current.payload.reviewId) {
return staleReviewResult();
return { ok: false, message: 'This timing review is no longer active.' };
}
if (request.decision.action === 'confirm') {
const { startTime, endTime, text } = request.decision;
+1 -11
View File
@@ -387,10 +387,6 @@ export function createMediaTimingReviewModal(
) {
return;
}
if (!result.ok && result.stale) {
closeResolvedReview();
return;
}
const path = result.ok ? buildMediaTimingWaveformPath(result.peaks ?? []) : '';
if (!path) {
setWaveformState('unavailable');
@@ -711,13 +707,11 @@ export function createMediaTimingReviewModal(
reviewId: payload.reviewId,
decision,
});
if (!result.ok && !result.stale) {
if (!result.ok) {
setStatus(result.message ?? 'The timing review could not be resolved.', true);
showEditor();
return;
}
// A stale review was already settled by main; keeping the modal up would leave
// controls that can never succeed over a live mpv window.
closeResolvedReview();
} catch (error) {
setStatus(error instanceof Error ? error.message : String(error), true);
@@ -765,10 +759,6 @@ export function createMediaTimingReviewModal(
}
return;
}
if (!result.ok && result.stale) {
closeResolvedReview();
return;
}
if (!result.ok) {
setStatus(result.message ?? 'Audio preview is unavailable.', true);
setPreviewPlaying(false);
-2
View File
@@ -79,8 +79,6 @@ export interface MediaTimingReviewResolveRequest {
export interface MediaTimingReviewActionResult {
ok: boolean;
message?: string;
/** The review this request targeted has already ended; the renderer should close. */
stale?: boolean;
}
export interface NotificationOptions {