1- import { afterEach , beforeEach , describe , expect , it , vi } from "vitest" ;
1+ import { afterEach , beforeEach , describe , expect , it , vi , type MockInstance } from "vitest" ;
22import {
33 chmodSync ,
44 existsSync ,
5+ mkdirSync ,
56 mkdtempSync ,
67 readFileSync ,
78 readdirSync ,
@@ -11,27 +12,17 @@ import {
1112import { tmpdir } from "node:os" ;
1213import { dirname , join , resolve } from "node:path" ;
1314import { fileURLToPath } from "node:url" ;
14- import { WhisperUnavailableError } from "./whisper/manager.js" ;
15-
16- const { transcribeMock, renderMock } = vi . hoisted ( ( ) => ( {
17- transcribeMock : vi . fn ( ) ,
18- renderMock : vi . fn ( ) ,
19- } ) ) ;
20- vi . mock ( "./whisper/transcribe.js" , async ( importOriginal ) => ( {
21- ...( await importOriginal < typeof import ( "./whisper/transcribe.js" ) > ( ) ) ,
22- transcribe : transcribeMock ,
23- } ) ) ;
24- // Parakeet runs on parakeet-mlx in these tests, whatever this machine has installed.
25- vi . mock ( "./whisper/sherpa.js" , async ( importOriginal ) => ( {
26- ...( await importOriginal < typeof import ( "./whisper/sherpa.js" ) > ( ) ) ,
27- sherpaParakeetInstalled : ( ) => false ,
28- } ) ) ;
29- vi . mock ( "./background-removal/pipeline.js" , async ( importOriginal ) => ( {
30- ...( await importOriginal < typeof import ( "./background-removal/pipeline.js" ) > ( ) ) ,
31- render : renderMock ,
32- } ) ) ;
33-
34- import { RemoveBackgroundError , TranscribeError , removeBackground , transcribe } from "./api.js" ;
15+ import * as pipeline from "./background-removal/pipeline.js" ;
16+ import * as manager from "./whisper/manager.js" ;
17+ import * as sherpa from "./whisper/sherpa.js" ;
18+ import * as whisper from "./whisper/transcribe.js" ;
19+ import {
20+ RemoveBackgroundError ,
21+ TranscribeError ,
22+ removeBackground ,
23+ transcribe ,
24+ type TranscribeOptions ,
25+ } from "./api.js" ;
3526
3627const SRT = `1
372800:00:01,000 --> 00:00:03,500
@@ -43,10 +34,14 @@ Render video. Built for agents.
4334` ;
4435
4536let dir : string ;
37+ let transcribeMock : MockInstance < typeof whisper . transcribe > ;
38+ let renderMock : MockInstance < typeof pipeline . render > ;
4639beforeEach ( ( ) => {
4740 dir = mkdtempSync ( join ( tmpdir ( ) , "hf-api-test-" ) ) ;
48- transcribeMock . mockReset ( ) ;
49- renderMock . mockReset ( ) ;
41+ transcribeMock = vi . spyOn ( whisper , "transcribe" ) ;
42+ renderMock = vi . spyOn ( pipeline , "render" ) ;
43+ // Parakeet runs on parakeet-mlx in these tests, whatever this machine has installed.
44+ vi . spyOn ( sherpa , "sherpaParakeetInstalled" ) . mockReturnValue ( false ) ;
5045 vi . spyOn ( console , "log" ) ;
5146 vi . spyOn ( console , "error" ) ;
5247} ) ;
@@ -120,8 +115,8 @@ describe("transcribe", () => {
120115 it ( "transcribes with whisper and hands back the runner, status and progress" , async ( ) => {
121116 const input = dummyAudio ( ) ;
122117 transcribeMock . mockImplementation ( async ( _input , outputDir , options ) => {
123- options . onProgress ?.( "Checking model..." ) ;
124- options . onEvent ?.( {
118+ options ? .onProgress ?.( "Checking model..." ) ;
119+ options ? .onEvent ?.( {
125120 type : "progress" ,
126121 phase : "transcription" ,
127122 model : "small.en" ,
@@ -186,7 +181,7 @@ describe("transcribe", () => {
186181 let signal : unknown ;
187182 transcribeMock . mockImplementation ( async ( _input , _outputDir , options ) => {
188183 const before = process . listenerCount ( "SIGINT" ) ;
189- signal = options . startCancellation ( ) ;
184+ signal = options ? .startCancellation ?. ( ) ;
190185 handlersAdded = process . listenerCount ( "SIGINT" ) - before ;
191186 controller . abort ( ) ;
192187 throw new Error ( "Command failed: whisper-cli" ) ;
@@ -201,7 +196,7 @@ describe("transcribe", () => {
201196
202197 it ( "names a missing whisper as whisper_unavailable, with the original error as cause" , async ( ) => {
203198 const input = dummyAudio ( ) ;
204- const missing = new WhisperUnavailableError ( "whisper-cpp not found" ) ;
199+ const missing = new manager . WhisperUnavailableError ( "whisper-cpp not found" ) ;
205200 transcribeMock . mockRejectedValue ( missing ) ;
206201
207202 const err = await transcribeError ( { input, engine : "whisper" } ) ;
@@ -277,12 +272,113 @@ describe("transcribe", () => {
277272 } ,
278273 ) ;
279274
280- it ( "keeps every import of the API modules at module scope" , ( ) => {
275+ /** A stand-in tool that starts a process of its own, writes both pids, then waits for it. */
276+ function hangingTool ( path : string , pidFile : string , before = "" ) : void {
277+ writeFileSync ( path , `#!/bin/sh\n${ before } sleep 15 &\necho "$$ $!" > "${ pidFile } "\nwait\n` ) ;
278+ chmodSync ( path , 0o755 ) ;
279+ }
280+
281+ /** Aborts once the stand-in is running; a blocked event loop never gets to. */
282+ async function abortWhileRunning ( pidFile : string , options : Omit < TranscribeOptions , "signal" > ) {
283+ const controller = new AbortController ( ) ;
284+ const poll = setInterval ( ( ) => {
285+ if ( existsSync ( pidFile ) && readFileSync ( pidFile , "utf8" ) . includes ( " " ) ) controller . abort ( ) ;
286+ } , 20 ) ;
287+ const started = Date . now ( ) ;
288+ const err = await transcribeError ( { ...options , signal : controller . signal } ) . finally ( ( ) =>
289+ clearInterval ( poll ) ,
290+ ) ;
291+ const pids = readFileSync ( pidFile , "utf8" ) . trim ( ) . split ( " " ) . map ( Number ) ;
292+ return { err, elapsed : Date . now ( ) - started , pids } ;
293+ }
294+
295+ it . skipIf ( process . platform === "win32" ) (
296+ "stops a whisper runtime install in progress when the signal aborts" ,
297+ async ( ctx ) => {
298+ const bin = join ( dir , "bin" ) ;
299+ mkdirSync ( bin ) ;
300+ const pidFile = join ( dir , "install.pid" ) ;
301+ // Homebrew on macOS, git clone elsewhere: whichever install step runs first never ends.
302+ hangingTool ( join ( bin , "brew" ) , pidFile ) ;
303+ hangingTool ( join ( bin , "git" ) , pidFile ) ;
304+ writeFileSync ( join ( bin , "cmake" ) , "#!/bin/sh\nexit 1\n" ) ;
305+ chmodSync ( join ( bin , "cmake" ) , 0o755 ) ;
306+ vi . stubEnv ( "PATH" , `${ bin } :/usr/bin:/bin` ) ;
307+ vi . stubEnv ( "HYPERFRAMES_WHISPER_PATH" , "" ) ;
308+ if ( manager . findWhisper ( ) ) ctx . skip ( ) ;
309+
310+ const { err, elapsed, pids } = await abortWhileRunning ( pidFile , {
311+ input : dummyAudio ( ) ,
312+ engine : "whisper" ,
313+ } ) ;
314+
315+ expect ( err . code ) . toBe ( "cancelled" ) ;
316+ expect ( elapsed ) . toBeLessThan ( 10_000 ) ;
317+ for ( const pid of pids ) expect ( ( ) => process . kill ( pid , 0 ) , `pid ${ pid } ` ) . toThrow ( ) ;
318+ } ,
319+ ) ;
320+
321+ it . skipIf ( process . platform === "win32" ) (
322+ "stops ffmpeg preparing the audio when the signal aborts, and removes its partial WAV" ,
323+ async ( ) => {
324+ vi . spyOn ( manager , "ensureWhisper" ) . mockResolvedValue ( {
325+ executablePath : "/no/whisper-cli" ,
326+ source : "system" ,
327+ } ) ;
328+ vi . spyOn ( manager , "ensureModel" ) . mockResolvedValue ( join ( dir , "ggml-small.en.bin" ) ) ;
329+ const ffmpeg = join ( dir , "ffmpeg" ) ;
330+ const pidFile = join ( dir , "ffmpeg.pid" ) ;
331+ hangingTool ( ffmpeg , pidFile , 'for out; do :; done\nprintf partial > "$out"\n' ) ;
332+ vi . stubEnv ( "HYPERFRAMES_FFMPEG_PATH" , ffmpeg ) ;
333+ vi . stubEnv ( "HYPERFRAMES_FFPROBE_PATH" , join ( dir , "no-ffprobe" ) ) ;
334+ const input = join ( dir , "narration.mp3" ) ;
335+ writeFileSync ( input , "not-real-audio" ) ;
336+ const wavs = ( ) =>
337+ readdirSync ( tmpdir ( ) ) . filter ( ( f ) => f . startsWith ( `hyperframes-audio-${ process . pid } -` ) ) ;
338+
339+ const { err, elapsed, pids } = await abortWhileRunning ( pidFile , { input, engine : "whisper" } ) ;
340+
341+ expect ( err . code ) . toBe ( "cancelled" ) ;
342+ expect ( elapsed ) . toBeLessThan ( 10_000 ) ;
343+ for ( const pid of pids ) expect ( ( ) => process . kill ( pid , 0 ) , `pid ${ pid } ` ) . toThrow ( ) ;
344+ expect ( wavs ( ) ) . toEqual ( [ ] ) ;
345+ } ,
346+ ) ;
347+
348+ // Spelled so that this file's own source, which it also reads, does not match.
349+ const localLoad = / \b i m p o r t \( | \b i m p o r t [ O A M ] (?: r i g i n a l | c t u a l | o c k ) \b / ;
350+
351+ it ( "keeps every module load at module scope, in the API, the code it runs and their tests" , ( ) => {
352+ for ( const sample of [
353+ "await import" + "('x')" ,
354+ "vi.import" + "Actual('x')" ,
355+ "import" + "Original()" ,
356+ ] ) {
357+ expect ( sample ) . toMatch ( localLoad ) ;
358+ }
281359 const here = dirname ( fileURLToPath ( import . meta. url ) ) ;
282- const files = [ "api.ts" , ...readdirSync ( join ( here , "api" ) ) . map ( ( f ) => join ( "api" , f ) ) ] ;
283- const sources = files . filter ( ( f ) => ! f . endsWith ( ".test.ts" ) ) ;
284- for ( const file of sources ) {
285- expect ( readFileSync ( join ( here , file ) , "utf8" ) , file ) . not . toMatch ( / \b i m p o r t \( / ) ;
360+ const api = readdirSync ( join ( here , "api" ) ) . map ( ( f ) => join ( "api" , f ) ) ;
361+ const files = [
362+ "api.ts" ,
363+ ...api ,
364+ "api.test.ts" ,
365+ "commands/remove-background.ts" ,
366+ "commands/transcribe.ts" ,
367+ "commands/transcribe.test.ts" ,
368+ "utils/download.ts" ,
369+ "utils/download.test.ts" ,
370+ "utils/stoppableExecFile.ts" ,
371+ "utils/stoppableExecFile.test.ts" ,
372+ "whisper/manager.ts" ,
373+ "whisper/modelForLanguage.ts" ,
374+ "whisper/parakeet.ts" ,
375+ "whisper/sherpa.ts" ,
376+ "whisper/transcribe.ts" ,
377+ "whisper/transcribe.test.ts" ,
378+ "whisper/transcribe.signal.test.ts" ,
379+ ] ;
380+ for ( const file of files ) {
381+ expect ( readFileSync ( join ( here , file ) , "utf8" ) , file ) . not . toMatch ( localLoad ) ;
286382 }
287383 } ) ;
288384
@@ -326,7 +422,7 @@ describe("removeBackground", () => {
326422 durationSeconds : 1 ,
327423 avgMsPerFrame : 10 ,
328424 provider : "cpu" ,
329- format : "webm" ,
425+ format : "webm" as const ,
330426 } ;
331427 renderMock . mockResolvedValue ( rendered ) ;
332428 const onProgress = vi . fn ( ) ;
0 commit comments