Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(editor): hold the "one busy phase" promise through the first-run download

Etienne Lescotee4b5bc0c00e
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.ts
index 351b756d0..df94fc102 100644
--- a/electron/stt/index.test.ts
+++ b/electron/stt/index.test.ts
@@ -94,6 +94,26 @@ describe("SttManager", () => {
expect(fakeWhisperServer.stop).toHaveBeenCalledOnce();
});
+ it("retries setup after a failed one instead of caching the rejection", async () => {
+ // First run downloads a 253 MB model. Caching a rejected `prepare()` meant
+ // one dropped connection failed every later transcription in the session —
+ // including the retry the editor offers — until the app was restarted.
+ const { ensureModels } = await import("./modelManager");
+ const mocked = vi.mocked(ensureModels);
+ mocked.mockClear();
+ mocked.mockRejectedValueOnce(new Error("Failed to download: network unreachable"));
+ const mgr = new SttManager();
+
+ await expect(mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" })).rejects.toThrow(
+ "network unreachable",
+ );
+ // The network came back: the next attempt must actually attempt.
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+
+ expect(mocked).toHaveBeenCalledTimes(2);
+ expect(fakeWhisperServer.start).toHaveBeenCalledOnce();
+ });
+
it("setStatusSink replaces the previous sink (last call wins)", () => {
const mgr = new SttManager();
const a = vi.fn();
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index 4f3e992aa..641a3abe6 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -59,7 +59,18 @@ export class SttManager {
if (options.statusSink) this.statusSink = options.statusSink;
if (options.modelsBaseDir) this.modelsBaseDir = options.modelsBaseDir;
if (!this.initPromise) {
- this.initPromise = this.prepare();
+ // A REJECTED init must not be cached. `prepare()` downloads a 253 MB
+ // model on first run, and caching its rejection meant one dropped
+ // connection poisoned the whole app session: every later transcription
+ // — including the retry the UI offers, and every remaining asset in the
+ // auto-transcription queue — awaited the same stale rejection and failed
+ // in milliseconds, with no way back short of quitting the app.
+ // Reconnecting the network changed nothing. Clearing the slot on failure
+ // makes the next attempt a real attempt.
+ this.initPromise = this.prepare().catch((error) => {
+ this.initPromise = null;
+ throw error;
+ });
}
return this.initPromise;
}
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index acbcf0285..356e250d7 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -15,6 +15,7 @@ import {
import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
+ useAssetTranscriptions,
useAutoTranscription,
useTimelineTranscriptGate,
useTranscriptionStore,
@@ -139,6 +140,17 @@ export function NewEditorShell() {
// routinely silent, and keying the transcript pane off it made the pane claim
// "no audio track" for a project whose actual footage was mid-transcription.
const transcriptGate = useTimelineTranscriptGate();
+ // Per asset, for the transcript pane: only the block whose transcript is
+ // actually being rewritten goes read-only. The gate answers "may a
+ // transcript-dependent ACTION run?", which is a different question.
+ const transcriptions = useAssetTranscriptions();
+ const busyAssetIds = useMemo(
+ () =>
+ Object.values(transcriptions)
+ .filter((v) => v.status === "running" || v.status === "queued")
+ .map((v) => v.assetId),
+ [transcriptions],
+ );
const tl = useTimeline();
useUndoRedoShortcuts(() => {
// ponytail: placeholder, wire when undo stack merges with history
@@ -1002,7 +1014,7 @@ export function NewEditorShell() {
transcripts: document?.transcripts ?? [],
assets: document?.assets ?? [],
trimRanges: document?.timeline?.trimRanges ?? [],
- busy: transcriptGate.state === "pending",
+ busyAssetIds,
onSeek: handleSeek,
onAddTrimRange: handleAddTrimRange,
onRemoveTrimRange: handleRemoveTrimRange,
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 3de8beea4..0490f3105 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -9,6 +9,7 @@ import {
FileText,
HelpCircle,
Layout as LayoutIcon,
+ Loader2,
MousePointerClick,
Palette,
Sliders,
@@ -524,7 +525,7 @@ export function TranscriptPane({
transcripts,
assets,
trimRanges,
- busy,
+ busyAssetIds,
onSeek,
onAddTrimRange,
onRemoveTrimRange,
@@ -537,7 +538,12 @@ export function TranscriptPane({
transcripts: AxcutTranscript[];
assets: AxcutAsset[];
trimRanges: AxcutTrimRange[];
- busy: boolean;
+ /** Assets whose transcript is being (re)generated right now — their block is
+ * read-only while the run is in flight, since it is about to be replaced.
+ * PER ASSET on purpose: a timeline-wide flag made every other clip's word
+ * stream silently swallow Backspace and hover-bin clicks for the whole
+ * background pass, with nothing on screen to say why. */
+ busyAssetIds: readonly string[];
onSeek: (sec: number) => void;
onAddTrimRange: (target: TrimTarget, startSec: number, endSec: number, reason: string) => void;
onRemoveTrimRange: (trimId: string) => void;
@@ -646,7 +652,7 @@ export function TranscriptPane({
key={section.clip.id}
index={idx}
section={section}
- busy={busy}
+ busy={busyAssetIds.includes(section.clip.assetId)}
cueWordId={cueWordId}
onSeek={onSeek}
onAddTrimRange={onAddTrimRange}
@@ -952,6 +958,23 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
{ts("transcript.clipLabel", { index: index + 1 })} · {sourceRangeLabel}
</span>
</span>
+ {/* A block whose transcript is being regenerated is read-only — say it,
+ rather than letting the word stream look live and drop the edits. */}
+ {busy ? (
+ <span
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 5,
+ flexShrink: 0,
+ font: "500 11px/1 var(--font-body)",
+ color: "var(--accent)",
+ }}
+ >
+ <Loader2 size={12} className="animate-spin" />
+ {ts("transcript.transcribing")}
+ </span>
+ ) : null}
</span>
{words.length === 0 ? (
<p
@@ -963,7 +986,7 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
fontStyle: "italic",
}}
>
- {ts("transcript.noClipTranscript")}
+ {busy ? ts("transcript.transcribing") : ts("transcript.noClipTranscript")}
</p>
) : (
<div
@@ -971,6 +994,8 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
role="textbox"
tabIndex={0}
contentEditable={!busy}
+ aria-busy={busy}
+ aria-readonly={busy}
suppressContentEditableWarning
spellCheck={false}
aria-label={ts("transcript.editorAria", { filename })}
@@ -984,7 +1009,11 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
font: "400 13px/1.65 var(--font-body)",
color: "var(--fg)",
textWrap: "pretty",
- cursor: "text",
+ // Read-only while its transcript is being regenerated: the cursor
+ // and the wash are what stop it from reading as an editor that
+ // ignores you (see the `busy` note on TranscriptPane).
+ cursor: busy ? "progress" : "text",
+ opacity: busy ? 0.6 : 1,
outline: "none",
// no overflow on the per-clip editor — the
// parent paneBody (already overflow-y: auto) is the
diff --git a/src/components/ai-edition/TranscriptPane.gating.test.tsx b/src/components/ai-edition/TranscriptPane.gating.test.tsx
index ba319a1f5..354bbbb3c 100644
--- a/src/components/ai-edition/TranscriptPane.gating.test.tsx
+++ b/src/components/ai-edition/TranscriptPane.gating.test.tsx
@@ -51,7 +51,7 @@ function renderPane(
transcripts={[]}
assets={[ASSET]}
trimRanges={[]}
- busy={false}
+ busyAssetIds={[]}
onSeek={vi.fn()}
onAddTrimRange={vi.fn()}
onRemoveTrimRange={vi.fn()}
diff --git a/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx b/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx
index af75267ad..c55ae8233 100644
--- a/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx
+++ b/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx
@@ -67,7 +67,11 @@ const W2_TRIMMED: AxcutTrimRange = {
reason: "",
};
-function renderPane(trimRanges: AxcutTrimRange[], onAddTrimRange = vi.fn()) {
+function renderPane(
+ trimRanges: AxcutTrimRange[],
+ onAddTrimRange = vi.fn(),
+ busyAssetIds: string[] = [],
+) {
const view = render(
<I18nProvider>
<TranscriptPane
@@ -75,7 +79,7 @@ function renderPane(trimRanges: AxcutTrimRange[], onAddTrimRange = vi.fn()) {
transcripts={[TRANSCRIPT]}
assets={[ASSET]}
trimRanges={trimRanges}
- busy={false}
+ busyAssetIds={busyAssetIds}
onSeek={vi.fn()}
onAddTrimRange={onAddTrimRange}
onRemoveTrimRange={vi.fn()}
@@ -128,6 +132,27 @@ describe("keyboard cut with the caret between words", () => {
expect(cutRange(onAddTrimRange)).toEqual([2, 3]); // "trois"
});
+ it("keeps cutting while ANOTHER asset is being transcribed", () => {
+ // The background pass runs on its own now, so a run on some other media must
+ // not quietly turn this block into an editor that ignores Backspace — the
+ // read-only state is scoped to the asset whose transcript is being rewritten.
+ const { editor, onAddTrimRange } = renderPane([], vi.fn(), ["asset_other"]);
+ caretBeforeWordAt(editor, 3);
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(cutRange(onAddTrimRange)).toEqual([2, 3]);
+ });
+
+ it("stops cutting, visibly, while THIS asset is being transcribed", () => {
+ // Its transcript is about to be replaced, so the block is read-only — and it
+ // says so, instead of swallowing the keystroke in silence.
+ const { editor, onAddTrimRange, getByText } = renderPane([], vi.fn(), ["asset_1"]);
+ caretBeforeWordAt(editor, 3);
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(cutRange(onAddTrimRange)).toBeNull();
+ expect(editor).toHaveAttribute("aria-busy", "true");
+ expect(getByText("Transcribing…")).toBeInTheDocument();
+ });
+
it("Backspace skips over an already-trimmed word instead of doing nothing", () => {
// Hold Backspace and you land here: "deux" is already struck through, so the word
// immediately before the caret has nothing left to cut. The keystroke used to
@@ -184,7 +209,7 @@ describe("keyboard cut with the caret between words", () => {
transcripts={[TRANSCRIPT]}
assets={[ASSET]}
trimRanges={trims}
- busy={false}
+ busyAssetIds={[]}
onSeek={vi.fn()}
onAddTrimRange={(_target, startSec, endSec) =>
setTrims((prev) => [
diff --git a/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx b/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx
index 36004c5c3..9ce354646 100644
--- a/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx
+++ b/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx
@@ -73,7 +73,7 @@ function renderPane(onSeek: (sec: number) => void = vi.fn()) {
transcripts={[TRANSCRIPT]}
assets={[ASSET]}
trimRanges={[]}
- busy={false}
+ busyAssetIds={[]}
onSeek={onSeek}
onAddTrimRange={vi.fn()}
onRemoveTrimRange={vi.fn()}
diff --git a/src/lib/ai-edition/store/transcriptionStore.test.ts b/src/lib/ai-edition/store/transcriptionStore.test.ts
index 61bd4b6bd..25e2b2548 100644
--- a/src/lib/ai-edition/store/transcriptionStore.test.ts
+++ b/src/lib/ai-edition/store/transcriptionStore.test.ts
@@ -211,6 +211,23 @@ describe("useTranscriptionStore", () => {
expect(toastMocks.error).toHaveBeenCalledTimes(1);
});
+ it("stops the queue on an engine failure instead of failing each asset in turn", async () => {
+ // The model download died / whisper-server didn't come up: that verdict is
+ // about the engine, so the remaining assets inherit it rather than each
+ // spending a full retry budget and stacking an identical toast.
+ transcribeMocks.transcribeAsset.mockRejectedValue(new Error("whisper-server exited"));
+ loadDocument(makeDoc(["asset_1", "asset_2", "asset_3"]));
+
+ useTranscriptionStore.getState().sync(useProjectStore.getState().document);
+ await whenTranscriptionIdle();
+
+ expect(transcribeMocks.transcribeAsset).toHaveBeenCalledTimes(1);
+ const jobs = useTranscriptionStore.getState().jobs;
+ expect(Object.values(jobs).map((j) => j.status)).toEqual(["failed", "failed", "failed"]);
+ expect(jobs.asset_3?.failure?.message).toBe("whisper-server exited");
+ expect(toastMocks.error).toHaveBeenCalledTimes(1);
+ });
+
it("request() re-runs a failed asset and clears the remembered verdict", async () => {
transcribeMocks.transcribeAsset.mockRejectedValueOnce(
new Error("No audio track found in this video."),
diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts
index c09dba4b8..9d765afc3 100644
--- a/src/lib/ai-edition/store/transcriptionStore.ts
+++ b/src/lib/ai-edition/store/transcriptionStore.ts
@@ -257,6 +257,29 @@ function patchJob(assetId: string, runId: number, patch: Partial<TranscriptionJo
});
}
+/**
+ * Give every still-queued job the verdict that just came back from the engine.
+ * Waiters are flushed so a `requestTimelineTranscripts()` awaiting the batch
+ * settles instead of hanging on runs that will never happen.
+ */
+function failRemainingQueue(projectId: string, failure: TranscriptionFailure): void {
+ const queued = Object.entries(useTranscriptionStore.getState().jobs)
+ .filter(([, job]) => job.status === "queued")
+ .map(([assetId]) => assetId);
+ if (queued.length === 0) return;
+ useTranscriptionStore.setState((state) => {
+ if (state.projectId !== projectId) return state;
+ const jobs = { ...state.jobs };
+ for (const assetId of queued) {
+ const job = jobs[assetId];
+ if (job?.status !== "queued") continue;
+ jobs[assetId] = { ...job, status: "failed", phase: undefined, failure };
+ }
+ return { jobs };
+ });
+ for (const assetId of queued) flushSettleWaiters(assetId);
+}
+
/** True while `runId` is still the attempt the store is tracking for this asset. */
function isCurrentRun(assetId: string, runId: number): boolean {
return useTranscriptionStore.getState().jobs[assetId]?.runId === runId;
@@ -380,6 +403,13 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {
patchJob(assetId, runId, { status: "failed", phase: undefined, failure });
flushSettleWaiters(assetId);
await persistPermanentFailure(projectId, assetId, failure);
+ // A transient failure is about the ENGINE, not about this media: the model
+ // download died, whisper-server didn't come up. Marching the rest of the
+ // queue into the same wall would spend a full retry budget per asset and
+ // stack one identical toast per asset. Fail them with the same verdict
+ // instead — the gate then reads "failed" (not "queued forever"), and one
+ // manual retry re-runs them all once the engine is back.
+ if (failure.kind === "error") failRemainingQueue(projectId, failure);
// A silent recording is an expected outcome, not an incident: the media
// card and every gated button already say so. Only surface the noisy
// (retryable) failures, plus anything the user asked for by hand.
diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.ts
index bf2c7320f..1116bb9a2 100644
--- a/src/lib/captioning/extractMono16k.ts
+++ b/src/lib/captioning/extractMono16k.ts
@@ -57,13 +57,23 @@ async function loadSourceVideoFile(videoUrl: string, signal?: AbortSignal): Prom
function mixToMono(audioBuffer: AudioBuffer): Float32Array {
const { length, numberOfChannels } = audioBuffer;
+ if (numberOfChannels === 0) return new Float32Array(length);
+ // `getChannelData` is a WebIDL call, so calling it INSIDE the sample loop cost
+ // one call per sample per channel — ~57 M of them for a ten-minute stereo
+ // recording, seconds of blocked main thread. That was survivable while
+ // transcription only ran when the user asked for it; it now runs by itself when
+ // a project opens, and a frozen window (spinners included) is exactly what the
+ // automatic pass must not look like. Hoisting the channel arrays out of the loop
+ // leaves plain typed-array indexing.
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < numberOfChannels; c++) channels.push(audioBuffer.getChannelData(c));
+ // Mono source: the mixdown is a copy. `slice` keeps the caller's contract of
+ // owning its buffer (the AudioBuffer's own array is reused by the context).
+ if (numberOfChannels === 1) return channels[0].slice();
const out = new Float32Array(length);
- if (numberOfChannels === 0) return out;
for (let i = 0; i < length; i++) {
let sum = 0;
- for (let c = 0; c < numberOfChannels; c++) {
- sum += audioBuffer.getChannelData(c)[i];
- }
+ for (let c = 0; c < numberOfChannels; c++) sum += channels[c][i];
out[i] = sum / numberOfChannels;
}
return out;
diff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.md
index a2f1e385d..cf60e7c6b 100644
--- a/technical-documentation/architecture/transcription-and-captions.md
+++ b/technical-documentation/architecture/transcription-and-captions.md
@@ -96,6 +96,42 @@ running, the media-card dot green (ready) / amber (silent or no speech) / red
and — the point of the whole thing — a disabled "Smart cuts" entry whose
subtitle is the reason rather than "With AI".
+### One phase, including the first-run model download
+
+On a fresh install the GGML model (~253 MB) is not on disk. It is fetched by
+`SttManager.prepare()` **inside** the `stt:transcribe` IPC call — i.e. inside a
+run this store has already marked `running` — so the user sees one single busy
+phase that simply takes longer the first time. That is deliberate: no separate
+"downloading" step, no progress bar to stare at, and nothing that looks
+clickable in the meantime (`phase: "model"` is emitted by the main process but
+deliberately not forwarded to the renderer by `transcribeAsset`). Nothing in the
+renderer imposes a timeout that a slow download could trip: the preload does a
+bare `ipcRenderer.invoke`, `fetchWithRetry` has no per-request deadline, and
+whisper-server's 30 s readiness budget only starts once the download resolved.
+
+Three edges make that promise hold, and each is load-bearing:
+
+- **A failed setup is not cached.** `SttManager.init` used to memoise the
+ rejected `prepare()` promise, so one dropped connection during the first
+ download failed every later transcription in the session — including the retry
+ the editor offers — until the app was restarted. It now clears the slot on
+ failure ([`electron/stt/index.ts`](../../electron/stt/index.ts)).
+- **A transient failure stops the queue** instead of walking the remaining
+ assets into the same wall: they inherit the verdict (one toast, one retry
+ affordance) rather than each spending a full retry budget.
+- **Read-only is scoped per asset.** The transcript pane's blocks go read-only
+ only for the asset whose transcript is being rewritten, and say so (spinner +
+ "Transcribing…" + dimmed stream). A timeline-wide flag made every other
+ clip's word stream swallow Backspace and hover-bin clicks in silence for the
+ whole background pass.
+
+Still synchronous, and still on the main thread: `mixToMono`
+([`src/lib/captioning/extractMono16k.ts`](../../src/lib/captioning/extractMono16k.ts))
+now hoists its channel arrays out of the sample loop (it was making one WebIDL
+call per sample per channel), but a long recording will still block the renderer
+for a moment during "extracting-audio". Moving the mixdown to a worker is the
+next step if it shows up in practice.
+
## The STT engine
The recogniser is **whisper.cpp**, embedded as a static library inside one