Greasy Fork is available in English.

ChatGPT الاستمرار التلقائي ⏩

⚡ استمر في توليد استجابات متعددة لـ ChatGPT تلقائيًا

// ==UserScript==
// @name                ChatGPT Auto-Continue ⏩
// @name:af             ChatGPT Auto-Aangaan ⏩
// @name:am             ChatGPT Auto-ተጨባጭ ማሳያ ⏩
// @name:ar             ChatGPT الاستمرار التلقائي ⏩
// @name:az             ChatGPT Avtomatik Davam et ⏩
// @name:be             ChatGPT Аўтаматычнае Працягванне ⏩
// @name:bg             ChatGPT Автоматично Продължаване ⏩
// @name:bn             ChatGPT স্বয়ংক্রিয় চালিয়ে যাওয়া ⏩
// @name:bo             ChatGPT རེད་འཐུམ་བཅོས་པ། ⏩
// @name:bs             ChatGPT Automatski Nastavi ⏩
// @name:ca             ChatGPT Auto-Continua ⏩
// @name:ceb            ChatGPT Auto-Padayon ⏩
// @name:ckb            ChatGPT دهستكاری خۆکار ⏩
// @name:cs             ChatGPT Automatické Pokračování ⏩
// @name:cy             ChatGPT Auto-Parhau ⏩
// @name:da             ChatGPT Auto-Fortsæt ⏩
// @name:de             ChatGPT Automatisches Fortfahren ⏩
// @name:dv             ChatGPT އައިނާދު ހިސާބަތް ⏩
// @name:dz             ChatGPT རེད་འཐུམ་གཅིག་ཁྱེར། ⏩
// @name:el             ChatGPT Αυτόματη Συνέχιση ⏩
// @name:eo             ChatGPT Aŭtomata Daŭrigado ⏩
// @name:es             ChatGPT Auto-Continuar ⏩
// @name:et             ChatGPT Automaatne Jätkamine ⏩
// @name:eu             ChatGPT Auto-Jarraitu ⏩
// @name:fa             ChatGPT ادامه خودکار ⏩
// @name:fi             ChatGPT Automaattinen Jatkaminen ⏩
// @name:fo             ChatGPT Auto-Verða ⏩
// @name:fr             ChatGPT Auto-Continuer ⏩
// @name:fr-CA          ChatGPT Auto-Continuer ⏩
// @name:gd             ChatGPT Auto-Leantainn ⏩
// @name:gl             ChatGPT Auto-Continuar ⏩
// @name:gu             ChatGPT સ્વચાલિત-ચાલુ રાખો ⏩
// @name:haw            ChatGPT Auto-Kōkua ⏩
// @name:he             ChatGPT המשך אוטומטי ⏩
// @name:hi             ChatGPT स्वचालित-प्रचालित रखें ⏩
// @name:hr             ChatGPT Auto-Nastavi ⏩
// @name:ht             ChatGPT Otomatik Kontinye ⏩
// @name:hu             ChatGPT Automatikus Folytatás ⏩
// @name:hy             ChatGPT Ինքնաշխատում Շարունակումը ⏩
// @name:id             ChatGPT Lanjut Otomatis ⏩
// @name:is             ChatGPT Sjálfvirk Framhald ⏩
// @name:it             ChatGPT Auto-Continua ⏩
// @name:ja             ChatGPT 自動継続 ⏩
// @name:jv             ChatGPT Lanjut Otomatis ⏩
// @name:ka             ChatGPT ავტომატური გაგრძელება ⏩
// @name:kab            ChatGPT Yemmeslayen Avrid n Tizwaru ⏩
// @name:kk             ChatGPT Автоматты Жалғастыру ⏩
// @name:km             ChatGPT បន្តទៅមកដល់ដោយស្វ័យប្រវត្តិ ⏩
// @name:kn             ChatGPT ಸ್ವಯಂಚಾಲಿತ ಮುಂದುವರಿಕೆ ⏩
// @name:ko             ChatGPT 자동 계속 ⏩
// @name:ku             ChatGPT Berdewamkirina Auto ⏩
// @name:ky             ChatGPT Автоматтык Жалгастыруу ⏩
// @name:la             ChatGPT Auto-Continuare ⏩
// @name:lb             ChatGPT Auto-Weiderginn ⏩
// @name:lo             ChatGPT ດຽວນີ້ບໍ່ຮອດຄວາມເລີຍ ⏩
// @name:lt             ChatGPT Automatinis Tęsti ⏩
// @name:lv             ChatGPT Automātiska Turpināšana ⏩
// @name:mg             ChatGPT Miverina Automatically ⏩
// @name:mi             ChatGPT Whakareri Tūmau ⏩
// @name:mk             ChatGPT Автоматско Продолжување ⏩
// @name:ml             ChatGPT ഓട്ടോ-തുടരുക ⏩
// @name:mn             ChatGPT Автомат Үргэлжлүүлэх ⏩
// @name:ms             ChatGPT Auto-Sambung ⏩
// @name:mt             ChatGPT Awto-Kontinwa ⏩
// @name:my             ChatGPT အလိုအလျောက်-ဆက်လက်လုပ်ကိုင်တယ် ⏩
// @name:ne             ChatGPT स्वचालित-तत्परता ⏩
// @name:nl             ChatGPT Auto-Doorgaan ⏩
// @name:no             ChatGPT Auto-Fortsette ⏩
// @name:ny             ChatGPT Auto-Endeleza ⏩
// @name:pa             ChatGPT ਸਵੈ-ਚਲੋ ⏩
// @name:pap            ChatGPT Sigui Automátikamente ⏩
// @name:pl             ChatGPT Automatyczne Kontynuowanie ⏩
// @name:ps             ChatGPT خپلکار تسلیم ⏩
// @name:pt             ChatGPT Auto-Continuar ⏩
// @name:ro             ChatGPT Auto-Continuare ⏩
// @name:ru             ChatGPT Авто-Продолжение ⏩
// @name:rw             ChatGPT Kugerageza Auto ⏩
// @name:si             ChatGPT ස්වයංක්‍රීය-දියවැඩියාව ⏩
// @name:sk             ChatGPT Auto-Pokračovať ⏩
// @name:sl             ChatGPT Samodejno Nadaljuj ⏩
// @name:sm             ChatGPT Aunoa'i-Taulaga ⏩
// @name:so             ChatGPT Isdhaaf Caruureed ⏩
// @name:sr             ChatGPT Аутоматски Настави ⏩
// @name:sv             ChatGPT Auto-Fortsätt ⏩
// @name:sw             ChatGPT Kusonga Kiotomatiki ⏩
// @name:ta             ChatGPT தானியங்கி தொடர்ந்து செல்லுங்கள் ⏩
// @name:te             ChatGPT ఆటో-కంటిన్యూ ⏩
// @name:tg             ChatGPT Давомоти автоматӣ ⏩
// @name:th             ChatGPT ดำเนินการต่ออย่างอัตโนมัติ ⏩
// @name:ti             ChatGPT ኣበይቲ ድሕሪ ተረኺቡ ⏩
// @name:tk             ChatGPT Avtomatik Dowam etmek ⏩
// @name:to             ChatGPT Tonu-'Aofa ⏩
// @name:tpi            ChatGPT Otomatik Kontinyu ⏩
// @name:tr             ChatGPT Otomatik Devam ⏩
// @name:uk             ChatGPT Автоматичне Продовження ⏩
// @name:ur             ChatGPT خودکار جاری رکھیں ⏩
// @name:uz             ChatGPT Avtomatik Davom ⏩
// @name:vi             ChatGPT Tự Động Tiếp Tục ⏩
// @name:xh             ChatGPT Ukuphela Okuqukethweyo ⏩
// @name:yi             ChatGPT אַווטאָ-קאַנטיניוירן ⏩
// @name:zh             ChatGPT 自动继续 ⏩
// @name:zh-CN          ChatGPT 自动继续 ⏩
// @name:zh-HK          ChatGPT 自動繼續 ⏩
// @name:zh-SG          ChatGPT 自动继续 ⏩
// @name:zh-TW          ChatGPT 自動繼續 ⏩
// @name:zu             ChatGPT Ngokugcwele Ukuphela ⏩
// @description         ⚡ Automatically continue generating multiple ChatGPT responses
// @description:af      ⚡ Outomaties voortgaan met die opwekking van meerdere ChatGPT-antwoorde
// @description:am      ⚡ እንዴትስ እንዲደርስ ያለብሳል የተወሰነ ምርጫዎች ለChatGPT
// @description:ar      ⚡ استمر في توليد استجابات متعددة لـ ChatGPT تلقائيًا
// @description:az      ⚡ ChatGPT cavablarını avtomatik olaraq çoxaldmağa davam edin
// @description:be      ⚡ Аўтаматычна працягвайце генерацыю некалькіх адказаў ChatGPT
// @description:bem     ⚡ Tontonkanyani kupitika kuwambo wanthu wokha-wokha wa ChatGPT
// @description:bg      ⚡ Продължете автоматично да генерирате множество отговори от ChatGPT
// @description:bn      ⚡ ChatGPT প্রতিক্রিয়া উত্পাদন অটোমেটিকভাবে চালিয়ে যান
// @description:bo      ⚡ ཡིག་ཆ་འཚོལ་ལག་སྤྱོད་རོགས་བྱུང་གནང་ནུས་པའི་ChatGPTལྕེབ་གསོར་བརྡ་འཕྲོ་ཤོག་ནང་བསྐྱོད་པ།
// @description:bs      ⚡ Nastavite automatski generirati više odgovora ChatGPT-a
// @description:ca      ⚡ Continua generant automàticament múltiples respostes de ChatGPT
// @description:ceb     ⚡ Magpadayon sa pag-generate og daghang mga Tugbang sa ChatGPT nga Otomatik
// @description:ckb     ⚡ بەردەوامبوون بە سەرجەم وەڵامەکانی ChatGPT
// @description:cs      ⚡ Automaticky pokračujte v generování více odpovědí ChatGPT
// @description:cy      ⚡ Parhewch i gynhyrchu nifer o ymatebion ChatGPT yn awtomatig
// @description:da      ⚡ Forsæt automatisk med at generere flere ChatGPT-responser
// @description:de      ⚡ Generieren Sie automatisch mehrere ChatGPT-Antworten weiterhin
// @description:dv      ⚡ އައުތީ ހުންނަވާ މެއިންމު ChatGPT އަޕް ކޮންޓެއް ބަދަލުކުރުމުގެ ރަނގަޅަ
// @description:dz      ⚡ འཕྲོས་མེད་པར་དུག་ཞིབ་པ་བསྐུགས་པར་ཡོད་མི་ChatGPTལྕེབ་གསོར་བརྡ་འཕྲོ་ཤོག་ནང་བསྐྱོད་པ།
// @description:el      ⚡ Συνεχίστε αυτόματα να δημιουργείτε πολλαπλές απαντήσεις ChatGPT
// @description:eo      ⚡ Daŭrigu aŭtomate generi plurajn respondojn ChatGPT
// @description:es      ⚡ Continúa generando automáticamente múltiples respuestas de ChatGPT
// @description:et      ⚡ Jätkake automaatselt mitme ChatGPT-vastuse genereerimist
// @description:eu      ⚡ Jarraitu automatikoki ChatGPT erantzun anitzak sortzen
// @description:fa      ⚡ ادامه تولید خودکار چندین پاسخ ChatGPT
// @description:fi      ⚡ Jatka automaattisesti useiden ChatGPT-vastausten generointia
// @description:fo      ⚡ Halda áfram við at framleiða fleiri ChatGPT svar
// @description:fr      ⚡ Continuez automatiquement à générer plusieurs réponses ChatGPT
// @description:fr-CA   ⚡ Continuez automatiquement à générer plusieurs réponses ChatGPT
// @description:gd      ⚡ Lean air adhart a' gabhail air adhart na freagairtean ChatGPT le bhith a' riochdachadh nas mòr
// @description:gl      ⚡ Continúa xerando automaticamente múltiples respostas de ChatGPT
// @description:gu      ⚡ આપોઆપ વધતા ચાર્જો આપતી કરો ChatGPT પ્રતિભાઓ
// @description:haw     ⚡ E mālama i ka hōʻoluʻolu ʻana i nā pane ʻelua a i ʻole iā ChatGPT
// @description:he      ⚡ המשך ליצור באופן אוטומטי מספר תגובות ChatGPT
// @description:hi      ⚡ स्वचालित रूप से बहुत सारे ChatGPT प्रतिक्रियाएँ उत्पन्न करना जारी रखें
// @description:hr      ⚡ Automatski nastavite generirati više ChatGPT odgovora
// @description:ht      ⚡ Kontinye otomatikman kontinye jenerasyon plizyè repons ChatGPT
// @description:hu      ⚡ Folytassa automatikusan több ChatGPT-válasz generálását
// @description:hy      ⚡ Շարունակեք ավտոմատ ստեղծել մեկից ավելի ChatGPT պատասխաններ
// @description:id      ⚡ Lanjutkan secara otomatis menghasilkan beberapa respons ChatGPT
// @description:is      ⚡ Halda áfram að framleiða fjölda ChatGPT-svara sjálfkrafa
// @description:it      ⚡ Continua automaticamente a generare più risposte di ChatGPT
// @description:ja      ⚡ ChatGPTの複数の応答を自動的に継続的に生成し続ける
// @description:jv      ⚡ Terus ngasilake balasan multipel ChatGPT kasebut otomatis
// @description:ka      ⚡ გაგრძელეთ ავტომატურად გენერირებას რამდენიმე ChatGPT პასუხის
// @description:kab     ⚡ Sekcem seg yilmeẓyen deg usefru n tufat ChatGPT
// @description:kk      ⚡ ChatGPT-ның бірнеше жауаптарын автоматты түрде жалғастыруға жалғастырыңыз
// @description:km      ⚡ បន្តទៀតហើយបន្តការបង្កើតចម្លើយជាច្រើននៃ ChatGPT ដោយស្វ័យប្រវត្តិ
// @description:kn      ⚡ ಸ್ವಯಂಚಾಲಿತವಾಗಿ ChatGPT ಪ್ರತಿಕ್ರಿಯೆಗಳನ್ನು ಮುಂದುವರಿಸಿ
// @description:ko      ⚡ ChatGPT 응답을 자동으로 계속 생성하세요
// @description:ku      ⚡ Parvekirina otomatîk a berdevkêya çêkirina gelek bersivên ChatGPT
// @description:ky      ⚡ Тууралуу даярдалган көптөгөн ChatGPT каражаттарын жалгастыр
// @description:la      ⚡ Automatica continua generatio plurium responsionum ChatGPT
// @description:lb      ⚡ Fuert mat der Automatiséierung vum generéieren vun méi ChatGPT Äntwerten
// @description:lo      ⚡ ຕະຫຼາດໃນການຜະລິດທັງເຫລົ່າຂອງການສ້າງຄໍາອະທິບາຍຂອງ ChatGPT
// @description:lt      ⚡ Tęskite automatiškai generuoti daugelį ChatGPT atsakymų
// @description:lv      ⚡ Turpiniet automātiski ģenerēt vairākas ChatGPT atbildes
// @description:mg      ⚡ Mihatra ny famokarana an-taonana momba ny fijery maromaro amin'ny ChatGPT
// @description:mi      ⚡ Whakapau tonu i te whakaputa i ngā whakahoki ā-ipurangi maha mō te ChatGPT
// @description:mk      ⚡ Настани се автоматски да генерираш повеќе одговори на ChatGPT
// @description:ml      ⚡ ChatGPT പ്രതികരണങ്ങൾക്ക് സ്വയംഭാവതന്നെ തുടങ്ങുക
// @description:mn      ⚡ ChatGPT хариултуудыг автоматаар үүсгэнэ үү
// @description:ms      ⚡ Terus menghasilkan beberapa respons ChatGPT secara automatik
// @description:mt      ⚡ Kompluta b'mod awtomatiku jipproduċi iktar risposti tal-ChatGPT
// @description:my      ⚡ ချောတောင်းကိုလည်း ChatGPT အတွက် အလိုအလျောက် ထပ်တိုးထားသည်ကိုနှိပ်ပါ
// @description:ne      ⚡ क्याटजीपीटी प्रतिक्रियाहरूलाई स्वतः सार्नुहोस्
// @description:nl      ⚡ Ga automatisch door met het genereren van meerdere ChatGPT-reacties
// @description:no      ⚡ Fortsett automatisk med å generere flere ChatGPT-responser
// @description:ny      ⚡ Kwezalitsa mabuku achinsinsi amakono apamwamba a ChatGPT
// @description:pa      ⚡ ਆਪਣੇ ਆਪ ਕਈ ChatGPT ਜਵਾਬਾਂ ਨੂੰ ਜਾਰੀ ਰੱਖਣ ਦੇ ਨਾਲ ਜਾਰੀ ਰੱਖੋ
// @description:pap     ⚡ Kontinua generando automaticamente varios respondenan di ChatGPT
// @description:pl      ⚡ Kontynuuj automatyczne generowanie wielu odpowiedzi ChatGPT
// @description:ps      ⚡ په خپله خوښه خپور شه کړه چې د ChatGPT پاسخونه وویشتل
// @description:pt      ⚡ Continue gerando automaticamente várias respostas do ChatGPT
// @description:pt-BR   ⚡ Continue gerando automaticamente várias respostas do ChatGPT
// @description:rn      ⚡ Komeza automatik kugenera ibyanditswe byinshi bya ChatGPT
// @description:ro      ⚡ Continuați să generați automat mai multe răspunsuri ChatGPT
// @description:ru      ⚡ Продолжайте автоматически генерировать несколько ответов ChatGPT
// @description:rw      ⚡ Angana gusuzumira kongera amakuru adahindurwa ya ChatGPT
// @description:sg      ⚡ Kwâandâ mbele mbanzi mêlêba mêvâmba ya tâ ChatGPT
// @description:si      ⚡ ChatGPT හි බහුතරක් ස්වයංක්රීයව පවතී
// @description:sk      ⚡ Automaticky pokračujte v generovaní viacerých odpovedí ChatGPT
// @description:sl      ⚡ Samodejno nadaljujte z generiranjem več odgovorov ChatGPT
// @description:sm      ⚡ Alofa faauaogaina ona faaaogāina ni tali i le mafaufau ChatGPT
// @description:sn      ⚡ Enda kusvika pachigadzirwa chekugadzirisa vashandisi vairambidzwi vechi ChatGPT
// @description:so      ⚡ Sii wadnaansho badan oo ChatGPT ka heli
// @description:sr      ⚡ Настави аутоматски да генеришеш више ChatGPT одговора
// @description:sv      ⚡ Fortsätt att automatiskt generera flera ChatGPT-svar
// @description:sw      ⚡ Endelea kuzalisha majibu mengi ya ChatGPT kiotomatiki
// @description:ta      ⚡ தானியங்கி மீண்டும் பல விளக்கங்களை உருவாக்கத் தொடர்ந்துவிடுங்கள் ChatGPT
// @description:te      ⚡ ఆటోమేటిక్గా మరియు మరిన్ని ChatGPT సమాధానాలను రచించండి
// @description:tg      ⚡ Идомаи автоматӣ барои иҷод кардани чанд ҷавоби ChatGPT
// @description:th      ⚡ ดำเนินการสร้างคำตอบหลาย ๆ ของ ChatGPT อัตโนมัติ
// @description:ti      ⚡ ደቂቃዎት የሚጠፋ ኮድ ብቻ በኮስታኒክስ በሚገባ ጥሩ ጥያቄዎች ይሰጣል
// @description:tk      ⚡ Tölegiňizde ChatGPT-e hasapla otomatik toplum
// @description:tn      ⚡ Koisa ha maele a ChatGPT ho ngola ho tlaleletsa
// @description:to      ⚡ Tonu ki hono fakahoko ki he fakafofonga ha nonga ai he ChatGPT
// @description:tpi     ⚡ Kontinyu genaratim planti respons bilong ChatGPT bi autometik
// @description:tr      ⚡ Otomatik olarak çoklu ChatGPT yanıtları üretmeye devam edin
// @description:uk      ⚡ Продовжуйте автоматично генерувати багато відповідей ChatGPT
// @description:ur      ⚡ ChatGPT جو جوابات خودکار طور پر تیار کرنا جاری رکھیں
// @description:uz      ⚡ Ko'plab ChatGPT javoblarni avtomatik ravishda yaratishni davom ettirish
// @description:vi      ⚡ Tiếp tục tạo ra nhiều câu trả lời ChatGPT một cách tự động
// @description:xh      ⚡ Qhubeka ukuqhuba okuqukethweyo lwezibalo eziningi zikaChatGPT
// @description:yi      ⚡ פֿאָרטזעצן ווײַטער גענערירן מיינערע אַנטוואָרטן פֿון ChatGPT אַװטאָמאַטיש
// @description:zh      ⚡ 自动继续生成多个 ChatGPT 响应
// @description:zh-CN   ⚡ 自动继续生成多个 ChatGPT 响应
// @description:zh-HK   ⚡ 自動繼續生成多個 ChatGPT 響應
// @description:zh-SG   ⚡ 自动继续生成多个 ChatGPT 响应
// @description:zh-TW   ⚡ 自動繼續生成多個 ChatGPT 響應
// @description:zu      ⚡ Terus menghasilkan imibuzo eminingi ye-ChatGPT ngokwesizulu
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.12.23.4
// @license             MIT
// @icon                https://media.chatgptautocontinue.com/images/icons/continue-symbol/circled/with-robot/icon48.png?de3b6bd
// @icon64              https://media.chatgptautocontinue.com/images/icons/continue-symbol/circled/with-robot/icon64.png?de3b6bd
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @connect             cdn.jsdelivr.net
// @connect             update.greasyfork.org
// @require             https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.4.0/dist/chatgpt.min.js#sha256-LfB3mqeB6Xiq2BDub1tn3BtvEiMcaWEp+I094MFpA+Q=
// @require             https://cdn.jsdelivr.net/gh/adamlui/chatgpt-auto-continue@2b7bdb2a99cf71021dba0b014830e7240c78bc76/chromium/extension/components/modals.js#sha256-Bk/p3LsLW/UOxxMWLDRCzpyP9Kjos5NGLKcXLlViJtk=
// @require             https://cdn.jsdelivr.net/gh/adamlui/chatgpt-auto-continue@2b7bdb2a99cf71021dba0b014830e7240c78bc76/chromium/extension/lib/dom.js#sha256-mdgglx6OZmPxvzAuCMoZa+Msw5GN7F50IBepwudDW00=
// @require             https://cdn.jsdelivr.net/gh/adamlui/chatgpt-auto-continue@3f496d6c137665fa12051e44205d34d3cd898040/chromium/extension/lib/settings.js#sha256-wCviFMPMib+hKjnsr0ACIPJlKYhn6H1fdpm4woGCPMM=
// @resource brsCSS     https://assets.aiwebextensions.com/styles/rising-stars/dist/black.min.css?v=0cde30f9ae3ce99ae998141f6e7a36de9b0cc2e7#sha256-4nbm81/JSas4wmxFIdliBBzoEEHRZ057TpzNX1PoQIs=
// @resource wrsCSS     https://assets.aiwebextensions.com/styles/rising-stars/dist/white.min.css?v=0cde30f9ae3ce99ae998141f6e7a36de9b0cc2e7#sha256-pW8xWWV6tm8Q6Ms+HWZv6+QzzTLJPyL1DyE18ywpVaE=
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @grant               GM_getResourceText
// @grant               GM_xmlhttpRequest
// @grant               GM.xmlHttpRequest
// @noframes
// @homepageURL         https://www.chatgptautocontinue.com
// @supportURL          https://support.chatgptautocontinue.com
// @contributionURL     https://github.com/sponsors/adamlui
// ==/UserScript==

// Documentation: https://docs.chatgptautocontinue.com
// NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org
//  © 2023–2024 KudoAI & contributors under the MIT license.

(async () => {

    // Init ENV context
    const env = {
        browser: {
            language: chatgpt.getUserLanguage(), isFF: chatgpt.browser.isFirefox(), isMobile: chatgpt.browser.isMobile()
        },
        scriptManager: {
            name: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})(),
            version: (() => { try { return GM_info.version } catch (err) { return 'unknown' }})()
        },
        ui: { scheme: getScheme() }
    }
    env.browser.isPortrait = env.browser.isMobile && (window.innerWidth < window.innerHeight)
    const xhr = typeof GM != 'undefined' && GM.xmlHttpRequest || GM_xmlhttpRequest

    // Init APP data
    const app = {
        version: GM_info.script.version, configKeyPrefix: 'chatGPTautoContinue',
        chatgptJSver: /chatgpt\.js@([\d.]+)/.exec(GM_info.scriptMetaStr)[1], urls: {},
        latestAssetCommitHash: '0204c94' // for cached app.json + messages.json
    }
    app.urls.assetHost = `https://cdn.jsdelivr.net/gh/adamlui/chatgpt-auto-continue@${app.latestAssetCommitHash}`
    const remoteAppData = await new Promise(resolve => xhr({
        method: 'GET', url: `${app.urls.assetHost}/app.json`, onload: resp => resolve(JSON.parse(resp.responseText)) }))
    Object.assign(app, { ...remoteAppData, urls: { ...app.urls, ...remoteAppData.urls }})
    app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-z-]*)$/i, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)
    app.msgs = {
        appName: app.name,
        appAuthor: app.author.name,
        appDesc: 'Automatically continue generating multiple ChatGPT responses',
        menuLabel_modeNotifs: 'Mode Notifications',
        menuLabel_about: 'About',
        menuLabel_donate: 'Please send a donation',
        menuLabel_disabled: 'Disabled (extension installed)',
        about_version: 'Version',
        about_poweredBy: 'Powered by',
        about_openSourceCode: 'Open source code',
        mode_autoContinue: 'Auto-Continue',
        helptip_modeNotifs: 'Show notifications when toggling modes/settings',
        alert_updateAvail: 'Update available',
        alert_newerVer: 'An update to',
        alert_isAvail: 'is available',
        alert_upToDate: 'Up-to-date',
        alert_isUpToDate: 'is up-to-date',
        alert_showYourSupport: 'Show your support',
        alert_isOSS: 'is open-source software built & maintained for free through 100% volunteer efforts',
        alert_despiteAffliction: 'Despite being severely afflicted by',
        alert_longCOVID: 'long COVID',
        alert_since2020: 'since 2020',
        alert_byDonatingResults: 'by donating, you help me to continue improving, fixing bugs, adding new features, and making the software even better',
        alert_yourContrib: 'Your contribution',
        alert_noMatterSize: 'no matter the size',
        alert_directlySupports: 'directly supports my unpaid efforts to ensure this project remains free and open for all to use',
        alert_tyForSupport: 'Thank you for your support',
        alert_author: 'author',
        notif_chatAutoContinued: 'Chat Auto-Continued',
        btnLabel_moreAIextensions: 'More AI Extensions',
        btnLabel_rateUs: 'Rate Us',
        btnLabel_getSupport: 'Get Support',
        btnLabel_checkForUpdates: 'Check for Updates',
        btnLabel_update: 'Update',
        btnLabel_dismiss: 'Dismiss',
        link_viewChanges: 'View changes',
        state_on: 'on',
        state_off: 'off'
    }

    // LOCALIZE app.msgs for non-English users
    if (!env.browser.language.startsWith('en')) {
        const localizedMsgs = await new Promise(resolve => {
            const msgHostDir = app.urls.assetHost + '/chromium/extension/_locales/',
                  msgLocaleDir = ( env.browser.language ? env.browser.language.replace('-', '_') : 'en' ) + '/'
            let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
            function fetchMsgs() { xhr({ method: 'GET', url: msgHref, onload: handleMsgs })}
            function handleMsgs(resp) {
                try { // to return localized messages.json
                    const msgs = JSON.parse(resp.responseText), flatMsgs = {}
                    for (const key in msgs)  // remove need to ref nested keys
                        if (typeof msgs[key] == 'object' && 'message' in msgs[key])
                            flatMsgs[key] = msgs[key].message
                    resolve(flatMsgs)
                } catch (err) { // if bad response
                    msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try original/region-stripped/EN only
                    msgHref = env.browser.language.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
                        msgHref.replace(/([^_]+_[^_]+)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
                            : ( msgHostDir + 'en/messages.json' ) // else use default English messages
                    fetchMsgs()
                }
            }
            fetchMsgs()
        })
        Object.assign(app.msgs, localizedMsgs)
    }

    // Export DEPENDENCIES to imported resources
    dom.dependencies.import({ env }) // for env.ui.scheme
    modals.dependencies.import({ app, env, updateCheck }) // for app data + env.ui.scheme + modals.about
    settings.dependencies.import({ app }) // for app.msgs + app.configKeyPrefix refs

    // Init SETTINGS
    settings.load(Object.keys(settings.controls))

    // Define MENU functions

    const menu = {
        ids: [], state: {
            symbols: ['❌', '✔️'], separator: env.scriptManager.name == 'Tampermonkey' ? ' — ' : ': ',
            words: [app.msgs.state_off.toUpperCase(), app.msgs.state_on.toUpperCase()]
        },

        register() {
            const tooltipsSupported = env.scriptManager.name == 'Tampermonkey'
                                   && parseInt(env.scriptManager.version.split('.')[0]) >= 5

            // Show "Disabled (extension installed)"
            if (env.extensionInstalled)
                GM_registerMenuCommand(`${menu.state.symbols[0]} ${app.msgs.menuLabel_disabled}`,
                    () => modals.open('about'), tooltipsSupported ? { title: ' ' } : undefined )

            // ...or add settings toggles
            else Object.keys(settings.controls).forEach(key => {
                const settingIsEnabled = config[key] ^ /disabled|hidden/i.test(key)
                const menuLabel = `${ settings.controls[key].symbol || menu.state.symbols[+settingIsEnabled] } `
                                + settings.controls[key].label
                                + menu.state.separator + menu.state.words[+settingIsEnabled]
                menu.ids.push(GM_registerMenuCommand(menuLabel, () => {
                    settings.save(key, !config[key]) ; syncConfigToUI({ updatedKey: key })
                    notify(`${settings.controls[key].label}: ${
                        menu.state.words[+(/disabled|hidden/i.test(key) ^ config[key])]}`)
                }, tooltipsSupported ? { title: settings.controls[key].helptip || ' ' } : undefined))
            });

            // Add About/Donate entries
            ['about', 'donate'].forEach(entryType => {
                if (entryType === 'donate' && env.extensionInstalled) return
                menu.ids.push(GM_registerMenuCommand(
                    `${ entryType == 'about' ? '💡' : '💖' }`
                        + ` ${app.msgs[`menuLabel_${entryType}`]} ${ entryType == 'about' ? app.msgs.appName : '' }`,
                    () => modals.open(entryType), tooltipsSupported ? { title: ' ' } : undefined
                ))
            })
        },

        refresh() {
            if (typeof GM_unregisterMenuCommand == 'undefined') return
            for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
        }
    }

    function updateCheck() {
        xhr({
            method: 'GET', url: app.urls.update + '?t=' + Date.now(),
            headers: { 'Cache-Control': 'no-cache' },
            onload: resp => {

                // Compare versions, alert if update found
                app.latestVer = /@version +(.*)/.exec(resp.responseText)[1]
                for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
                    const currentSubVer = parseInt(app.version.split('.')[i], 10) || 0,
                          latestSubVer = parseInt(app.latestVer.split('.')[i], 10) || 0
                    if (currentSubVer > latestSubVer) break // out of comparison since not outdated
                    else if (latestSubVer > currentSubVer) // if outdated
                        return modals.open('update', 'available')
                }

                // Alert to no update found, nav back to About
                modals.open('update', 'unavailable')
        }})
    }

    // Define FEEDBACK functions

    function notify(msg, pos = '', notifDuration = '', shadow = '') {
        if (config.notifDisabled && !msg.includes(app.msgs.menuLabel_modeNotifs)) return

        // Strip state word to append colored one later
        const foundState = menu.state.words.find(word => msg.includes(word))
        if (foundState) msg = msg.replace(foundState, '')

        // Show notification
        chatgpt.notify(`${app.symbol} ${msg}`, pos, notifDuration, shadow || env.ui.scheme == 'dark' ? '' : 'shadow')
        const notif = document.querySelector('.chatgpt-notif:last-child')

        // Append styled state word
        if (foundState) {
            const styledStateSpan = dom.create.elem('span')
            styledStateSpan.style.cssText = `color: ${
                foundState == menu.state.words[0] ? '#ef4848 ; text-shadow: rgba(255, 169, 225, 0.44) 2px 1px 5px'
                                                  : '#5cef48 ; text-shadow: rgba(255, 250, 169, 0.38) 2px 1px 5px' }`
            styledStateSpan.append(foundState) ; notif.append(styledStateSpan)
        }
    }

    // Define UI functions

    function syncConfigToUI() { menu.refresh() /* prefixes/suffixes */ }

    function getScheme() {
        return document.documentElement.className
            || (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
    }

    function checkContinueBtn() {
        const continueBtn = chatgpt.getContinueBtn()
        if (continueBtn) {
            continueBtn.click()
            notify(app.msgs.notif_chatAutoContinued, 'bottom-right')
            try { chatgpt.scrollToBottom() } catch(err) {}
            setTimeout(checkContinueBtn, 5000)
        } else setTimeout(checkContinueBtn, 500)
    }

    // Run MAIN routine

    env.extensionInstalled = await Promise.race([
        new Promise(resolve => {
            (function checkExtensionInstalled() {
                if (document.documentElement.hasAttribute('chatgpt-auto-continue-extension-installed')) resolve(true)
                else setTimeout(checkExtensionInstalled, 200)
            })()
        }), new Promise(resolve => setTimeout(() => resolve(false), 1500))])

    menu.register() ; if (env.extensionInstalled) return

    // Add STARS styles
    ['brs', 'wrs'].forEach(cssType => document.head.append(dom.create.style(GM_getResourceText(`${cssType}CSS`))))

    // Observe DOM for need to continue generating response
    checkContinueBtn()

    // NOTIFY of status on load
    notify(`${app.msgs.mode_autoContinue}: ${app.msgs.state_on.toUpperCase()}`)

    // Monitor SCHEME PREF changes to update sidebar toggle + modal colors
    new MutationObserver(handleSchemePrefChange).observe( // for site scheme pref changes
        document.documentElement, { attributes: true, attributeFilter: ['class'] })
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener( // for browser/system scheme pref changes
        'change', () => requestAnimationFrame(handleSchemePrefChange))
    function handleSchemePrefChange() {
        const displayedScheme = getScheme()
        if (env.ui.scheme != displayedScheme) { env.ui.scheme = displayedScheme ;  modals.stylize() }
    }

})()