@@ -6,7 +6,7 @@ import styles from "./home.module.scss";
66
77import log from "loglevel" ;
88import dynamic from "next/dynamic" ;
9- import { useState , useEffect } from "react" ;
9+ import { useState , useEffect , useRef } from "react" ;
1010import {
1111 HashRouter as Router ,
1212 Routes ,
@@ -164,6 +164,19 @@ const useWebLLM = () => {
164164 const [ webllm , setWebLLM ] = useState < WebLLMApi | undefined > ( undefined ) ;
165165 const [ isWebllmActive , setWebllmAlive ] = useState ( false ) ;
166166
167+ const isWebllmInitialized = useRef ( false ) ;
168+
169+ // If service worker registration timeout, fall back to web worker
170+ const timeout = setTimeout ( ( ) => {
171+ if ( ! isWebllmInitialized . current && ! isWebllmActive && ! webllm ) {
172+ log . info (
173+ "Service Worker activation is timed out. Falling back to use web worker." ,
174+ ) ;
175+ setWebLLM ( new WebLLMApi ( "webWorker" , config . logLevel ) ) ;
176+ setWebllmAlive ( true ) ;
177+ }
178+ } , 2_000 ) ;
179+
167180 // Initialize WebLLM engine
168181 useEffect ( ( ) => {
169182 if ( "serviceWorker" in navigator ) {
@@ -198,6 +211,8 @@ const useWebLLM = () => {
198211 ) ,
199212 ) ;
200213 setWebllmAlive ( true ) ;
214+ isWebllmInitialized . current = true ;
215+ clearTimeout ( timeout ) ;
201216 }
202217 navigator . serviceWorker . removeEventListener (
203218 "message" ,
@@ -217,18 +232,9 @@ const useWebLLM = () => {
217232 ) ;
218233 setWebLLM ( new WebLLMApi ( "webWorker" , config . logLevel ) ) ;
219234 setWebllmAlive ( true ) ;
235+ isWebllmInitialized . current = true ;
236+ clearTimeout ( timeout ) ;
220237 }
221-
222- // If service worker registration timeout
223- setTimeout ( ( ) => {
224- if ( ! isWebllmActive && ! webllm ) {
225- log . info (
226- "Service Worker activation is timed out. Falling back to use web worker." ,
227- ) ;
228- setWebLLM ( new WebLLMApi ( "webWorker" , config . logLevel ) ) ;
229- setWebllmAlive ( true ) ;
230- }
231- } , 3_000 ) ;
232238 } , [ ] ) ;
233239
234240 if ( webllm ?. webllm . type === "serviceWorker" ) {
0 commit comments