@@ -16,11 +16,12 @@ try {
1616
1717export const BACKGROUND_TASK_IDENTIFIER = 'background-fetch-task' ; // legacy id retained
1818
19- let taskDefined = false ;
19+ // Track definition across Fast Refresh cycles
20+ let taskDefined = ( globalThis as any ) . __CODEBUILDER_BACKGROUND_TASK_DEFINED__ === true ;
2021function defineBackgroundTask ( ) {
2122 if ( taskDefined ) return ;
2223 try {
23- TaskManager . defineTask ( BACKGROUND_TASK_IDENTIFIER , async ( ) => {
24+ const handler = async ( ) => {
2425 try {
2526 const startedAt = new Date ( ) . toISOString ( ) ;
2627 console . log ( '[BackgroundTask] Started' , startedAt ) ;
@@ -48,8 +49,21 @@ function defineBackgroundTask() {
4849 console . error ( '[BackgroundTask] Failed' , error ) ;
4950 return BackgroundTask . BackgroundTaskResult . Failed ;
5051 }
51- } ) ;
52+ } ;
53+ // Prefer TaskManager; some libs might also expose a define API
54+ if ( typeof ( BackgroundTask as any ) . defineTask === 'function' ) {
55+ try {
56+ ( BackgroundTask as any ) . defineTask ( BACKGROUND_TASK_IDENTIFIER , handler ) ;
57+ } catch ( btErr : any ) {
58+ const m = btErr ?. message || '' ;
59+ if ( ! / a l r e a d y d e f i n e d / i. test ( m ) ) {
60+ console . warn ( '[BackgroundTask] BackgroundTask.defineTask failed, falling back to TaskManager.defineTask' , m ) ;
61+ }
62+ }
63+ }
64+ TaskManager . defineTask ( BACKGROUND_TASK_IDENTIFIER , handler ) ;
5265 taskDefined = true ;
66+ ( globalThis as any ) . __CODEBUILDER_BACKGROUND_TASK_DEFINED__ = true ;
5367 console . log ( '[BackgroundTask] Task definition ensured' ) ;
5468 } catch ( e ) {
5569 // If already defined, ignore; otherwise log
@@ -58,6 +72,7 @@ function defineBackgroundTask() {
5872 console . warn ( '[BackgroundTask] defineTask error' , msg ) ;
5973 } else {
6074 taskDefined = true ; // treat as defined
75+ ( globalThis as any ) . __CODEBUILDER_BACKGROUND_TASK_DEFINED__ = true ;
6176 }
6277 }
6378}
@@ -73,6 +88,8 @@ export async function registerBackgroundFetch(minimumIntervalMinutes: number = 1
7388 try {
7489 // Double-ensure task is defined before registering
7590 defineBackgroundTask ( ) ;
91+ // Small delay to let task registry settle (helps with Fast Refresh race conditions)
92+ await new Promise ( res => setTimeout ( res , 25 ) ) ;
7693 const status = await BackgroundTask . getStatusAsync ( ) ;
7794 if ( status !== BackgroundTask . BackgroundTaskStatus . Available ) {
7895 console . warn ( '[BackgroundTask] Not available, status=' , status ) ;
@@ -90,6 +107,7 @@ export async function registerBackgroundFetch(minimumIntervalMinutes: number = 1
90107 console . log ( '[BackgroundTask] Retrying after ensure definition...' ) ;
91108 try {
92109 defineBackgroundTask ( ) ;
110+ await new Promise ( res => setTimeout ( res , 100 ) ) ;
93111 await BackgroundTask . registerTaskAsync ( BACKGROUND_TASK_IDENTIFIER , {
94112 minimumInterval : Math . max ( 15 , minimumIntervalMinutes ) ,
95113 } ) ;
0 commit comments