@@ -20,10 +20,29 @@ window.aiInstructions = "";
2020window . aiInstructionPromise = fetch ( "prompts/ai-instruct.md" )
2121 . then ( res => res . text ( ) )
2222 . then ( text => { window . aiInstructions = text ; } )
23- . catch ( err => {
24- console . error ( "Failed to load AI instructions" , err ) ;
25- window . aiInstructions = "" ;
26- } ) ;
23+ . catch ( err => {
24+ console . error ( "Failed to load AI instructions" , err ) ;
25+ window . aiInstructions = "" ;
26+ } ) ;
27+
28+ // Ensure AI instructions are loaded before any polliLib calls
29+ window . ensureAIInstructions = async function ensureAIInstructions ( ) {
30+ if ( window . aiInstructions ) return window . aiInstructions ;
31+ try {
32+ if ( window . aiInstructionPromise ) await window . aiInstructionPromise ;
33+ } catch ( e ) {
34+ // fall through to re-fetch
35+ }
36+ if ( window . aiInstructions ) return window . aiInstructions ;
37+ try {
38+ const res = await fetch ( "prompts/ai-instruct.md" , { cache : "no-store" } ) ;
39+ window . aiInstructions = await res . text ( ) ;
40+ } catch ( e ) {
41+ console . error ( "Failed to fetch AI instructions" , e ) ;
42+ window . aiInstructions = "" ;
43+ }
44+ return window . aiInstructions ;
45+ } ;
2746
2847document . addEventListener ( "DOMContentLoaded" , ( ) => {
2948
@@ -463,19 +482,12 @@ document.addEventListener("DOMContentLoaded", () => {
463482 chatBox . appendChild ( loadingDiv ) ;
464483 chatBox . scrollTop = chatBox . scrollHeight ;
465484
466- if ( ! window . aiInstructions ) {
467- try {
468- const res = await fetch ( "prompts/ai-instruct.md" , { cache : "no-store" } ) ;
469- window . aiInstructions = await res . text ( ) ;
470- } catch ( e ) {
471- window . aiInstructions = "" ;
472- }
485+ await window . ensureAIInstructions ( ) ;
486+
487+ const messages = [ ] ;
488+ if ( window . aiInstructions ) {
489+ messages . push ( { role : "system" , content : window . aiInstructions } ) ;
473490 }
474-
475- const messages = [ ] ;
476- if ( window . aiInstructions ) {
477- messages . push ( { role : "system" , content : window . aiInstructions } ) ;
478- }
479491 const memories = Memory . getMemories ( ) ;
480492 if ( memories ?. length ) {
481493 messages . push ( { role : "system" , content : `Relevant memory:\n${ memories . join ( "\n" ) } \nUse it in your response.` } ) ;
0 commit comments