ChatGPT Auto-Continue ⏩

⚡ Automatically continue generating multiple ChatGPT responses

Install this script?
Author's suggested script

You may also like ChatGPT Infinity ∞.

Install this script
// ==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.10.3.1
// @license             MIT
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @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
// @require             https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.3.4/dist/chatgpt.min.js#sha256-oUcV59cGJ+lLsvG8yERiH+q2uYnmXkQwqM6zlNcl204=
// @connect             cdn.jsdelivr.net
// @connect             greasyfork.org
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @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 APP info
    const app = {
        name: 'ChatGPT Auto-Continue', symbol: '≫', configKeyPrefix: 'chatGPTautoContinue',
        author: { name: 'Adam Lui', url: 'https://github.com/adamlui' },
        urls: {
            chatgptJS: 'https://chatgpt.js.org',
            donate: {
                cashApp: 'https://cash.app/$adamlui',
                gitHub: 'https://github.com/sponsors/adamlui',
                payPal: 'https://paypal.me/adamlui'
            },
            gitHub: 'https://github.com/adamlui/chatgpt-auto-continue',
            greasyFork: 'https://greasyfork.org/scripts/466789-chatgpt-auto-continue',
            relatedApps: 'https://github.com/adamlui/chatgpt-apps',
            review: { greasyFork: 'https://greasyfork.org/scripts/466789-chatgpt-auto-continue/feedback#post-discussion' },
            support: 'https://support.chatgptautocontinue.com'
        },
        latestAssetCommitHash: 'e125f8f' // for cached messages.json
    }
    app.urls.assetHost = app.urls.gitHub.replace('github.com', 'cdn.jsdelivr.net/gh') + `@${app.latestAssetCommitHash}`
    app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-zA-Z-]*)$/, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)

    // Init ENV info
    const env = { scriptManager: (() => { try { return GM_info.scriptHandler } catch (err) { return 'other' }})() }

    // Init CONFIG
    const config = { userLanguage: chatgpt.getUserLanguage() }
    const settings = {
        load(...keys) {
            if (Array.isArray(keys[0])) keys = keys[0] // use 1st array arg, else all comma-separated ones
            keys.forEach(key => config[key] = GM_getValue(app.configKeyPrefix + '_' + key, false))
        },
        save(key, value) { GM_setValue(app.configKeyPrefix + '_' + key, value) ; config[key] = value }
    } ; settings.load('notifDisabled')

    // Init app MESSAGES
    const xhr = env.scriptManager == 'OrangeMonkey' ? GM_xmlhttpRequest : GM.xmlHttpRequest
    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_sourceCode: 'Source code',
        mode_autoContinue: 'Auto-Continue',
        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_moreApps: 'More ChatGPT Apps',
        btnLabel_rateUs: 'Rate Us',
        btnLabel_getSupport: 'Get Support',
        btnLabel_updateCheck: 'Check for Updates',
        btnLabel_update: 'Update',
        btnLabel_dismiss: 'Dismiss',
        link_viewChanges: 'View changes',
        state_on: 'on',
        state_off: 'off'
    }
    if (!config.userLanguage.startsWith('en')) { // localize msgs for non-English users
        const localizedMsgs = await new Promise(resolve => {
            const msgHostDir = app.urls.assetHost + '/chromium/extension/_locales/',
                  msgLocaleDir = ( config.userLanguage ? config.userLanguage.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 up to 3X (original/region-stripped/EN) only
                    msgHref = config.userLanguage.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)
    }

    // Init SETTINGS props
    Object.assign(app, { settings: { notifDisabled: { type: 'toggle', label: app.msgs.menuLabel_modeNotifs }}})

    // Define MENU functions

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

        register() {

            // Add toggles
            Object.keys(app.settings).forEach(key => {
                const settingIsEnabled = config[key] ^ /disabled|hidden/i.test(key),
                      menuLabel = `${ app.settings[key].symbol || menu.state.symbols[+settingIsEnabled] } `
                                + app.settings[key].label + menu.state.separator + menu.state.words[+settingIsEnabled]
                menu.ids.push(GM_registerMenuCommand(menuLabel, () => {
                    settings.save(key, !config[key]) ; syncConfigToUI()
                    notify(`${app.settings[key].label}: ${menu.state.words[+(/disabled|hidden/i.test(key) ^ config[key])]}`)
                }))
            })
    
            // Add About entry
            const aboutLabel = `💡 ${app.msgs.menuLabel_about} ${app.msgs.appName}`
            menu.ids.push(GM_registerMenuCommand(aboutLabel, modals.about.show))

            // Add Donate entry
            const donateLabel = `💖 ${app.msgs.menuLabel_donate}`
            menu.ids.push(GM_registerMenuCommand(donateLabel, modals.donate.show))
        },

        refresh() {
            if (env.scriptManager == 'OrangeMonkey') return
            for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
        }
    }

    function updateCheck() {

        // Fetch latest meta
        const currentVer = GM_info.script.version
        xhr({
            method: 'GET', url: app.urls.update + '?t=' + Date.now(),
            headers: { 'Cache-Control': 'no-cache' },
            onload: response => { const updateAlertWidth = 377

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

                        // Alert to update
                        const updateModalID = siteAlert(`🚀 ${app.msgs.alert_updateAvail}!`, // title
                            `${app.msgs.alert_newerVer} ${app.msgs.appName} `
                                + `(v${latestVer}) ${app.msgs.alert_isAvail}!  `
                                + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
                                    + 'href="' + app.urls.gitHub + '/commits/main/greasemonkey/'
                                    + app.urls.update.replace(/.*\/(.*)meta\.js/, '$1user.js') + '"'
                                    + `> ${app.msgs.link_viewChanges}</a>`,
                            function update() { // button
                                modals.safeWinOpen(app.urls.update.replace('meta.js', 'user.js') + '?t=' + Date.now())
                            }, '', updateAlertWidth
                        )

                        // Localize button labels if needed
                        if (!config.userLanguage.startsWith('en')) {
                            const updateAlert = document.querySelector(`[id="${updateModalID}"]`),
                                  updateBtns = updateAlert.querySelectorAll('button')
                            updateBtns[1].textContent = app.msgs.btnLabel_update
                            updateBtns[0].textContent = app.msgs.btnLabel_dismiss
                        }

                        return
                }}

                // Alert to no update, return to About modal
                siteAlert(`${app.msgs.alert_upToDate}!`, // title
                    `${app.msgs.appName} (v${currentVer}) ${app.msgs.alert_isUpToDate}!`, // msg
                    '', '', updateAlertWidth
                )
                modals.about.show()
    }})}

    // Define FEEDBACK functions

    function notify(msg, pos = '', notifDuration = '', shadow = '') {

        // 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 || chatgpt.isDarkMode() ? '' : 'shadow')
        const notif = document.querySelector('.chatgpt-notif:last-child')

        // Append styled state word
        if (foundState) {
            const styledState = document.createElement('span')
            styledState.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' }`
            styledState.append(foundState) ; notif.append(styledState)
        }
    }

    function siteAlert(title = '', msg = '', btns = '', checkbox = '', width = '') {
        return chatgpt.alert(title, msg, btns, checkbox, width )}

    // Define MODAL functions

    const modals = {

        about: {
            show() {

                // Show alert
                const chatgptJSver = (/chatgpt-([\d.]+)\.min/.exec(GM_info.script.header) || [null, ''])[1],
                      headingStyle = 'font-size: 1.15rem',
                      pStyle = 'position: relative ; left: 3px',
                      pBrStyle = 'position: relative ; left: 4px ',
                      aStyle = 'color: ' + ( chatgpt.isDarkMode() ? '#c67afb' : '#8325c4' ) // purple
                const aboutModalID = siteAlert(
                    app.msgs.appName, // title
                    `<span style="${headingStyle}"><b>🏷️ <i>${app.msgs.about_version}</i></b>: </span>`
                        + `<span style="${pStyle}">${GM_info.script.version}</span>\n`
                    + `<span style="${headingStyle}"><b>⚡ <i>${app.msgs.about_poweredBy}</i></b>: </span>`
                        + `<span style="${pStyle}"><a style="${aStyle}" href="${app.urls.chatgptJS}" target="_blank" rel="noopener">`
                        + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
                    + `<span style="${headingStyle}"><b>📜 <i>${app.msgs.about_sourceCode}</i></b>:</span>\n`
                        + `<span style="${pBrStyle}"><a href="${app.urls.gitHub}" target="_blank" rel="nopener">`
                        + app.urls.gitHub + '</a></span>',
                    [ // buttons
                        function checkForUpdates() { updateCheck() },
                        function getSupport() { modals.safeWinOpen(app.urls.support) },
                        function rateUs() { modals.safeWinOpen(app.urls.review.greasyFork) },
                        function moreChatGPTapps() { modals.safeWinOpen(app.urls.relatedApps) }
                    ], '', 478 // set width
                )
        
                // Re-format buttons to include emoji + localized label + hide Dismiss button
                for (const button of document.getElementById(aboutModalID).querySelectorAll('button')) {
                    button.style.cssText = 'cursor: pointer !important' // since tweaks won't load on auto-disable
                    if (/updates/i.test(button.textContent)) button.textContent = (
                        '🚀 ' + ( app.msgs.btnLabel_updateCheck ))
                    else if (/support/i.test(button.textContent)) button.textContent = (
                        '🧠 ' + ( app.msgs.btnLabel_getSupport ))
                    else if (/rate/i.test(button.textContent)) button.textContent = (
                        '⭐ ' + ( app.msgs.btnLabel_rateUs ))
                    else if (/apps/i.test(button.textContent)) button.textContent = (
                        '🤖 ' + ( app.msgs.btnLabel_moreApps ))
                    else button.style.display = 'none' // hide Dismiss button
                }
            }
        },

        donate: {
            longCOVIDwikiLink: 'https://en.wikipedia.org/wiki/Long_COVID',

            show() {

                // Show alert
                const donateModalID = siteAlert(
                    `💖 ${app.msgs.alert_showYourSupport}`, // title
                        `<p>${app.msgs.appName} ${app.msgs.alert_isOSS}.</p>`
                      + `<p>${app.msgs.alert_despiteAffliction} `
                          + `<a target="_blank" rel="noopener" href="${modals.donate.longCOVIDwikiLink}">${app.msgs.alert_longCOVID}</a> `
                          + `${app.msgs.alert_since2020}, ${app.msgs.alert_byDonatingResults}.</p>`
                      + `<p>${app.msgs.alert_yourContrib}, <b>${app.msgs.alert_noMatterSize}</b>, ${app.msgs.alert_directlySupports}.</p>`
                      + `<p>${app.msgs.alert_tyForSupport}!</p>`
                      + `<img src="https://cdn.jsdelivr.net/gh/adamlui/adamlui/images/siggie/${ chatgpt.isDarkMode() ? 'white' : 'black' }.png"`
                          + ' style="height: 54px ; margin: 5px 0 -2px 5px"></img>'
                      + `<p>—<b><a target="_blank" rel="noopener" href="${app.author.url}">${app.msgs.appAuthor}</a></b>, ${app.msgs.alert_author}</p>`,
                    [ // buttons
                        function paypal() { modals.safeWinOpen(app.urls.donate.payPal) },
                        function githubSponsors() { modals.safeWinOpen(app.urls.donate.gitHub) },
                        function cashApp() { modals.safeWinOpen(app.urls.donate.cashApp) },
                        function rateUs() { modals.safeWinOpen(app.urls.review.greasyFork) }
                    ], '', 478 // set width
                )

                // Format text
                const donateModal = document.getElementById(donateModalID)
                donateModal.querySelectorAll('p').forEach(p => // v-pad text, shrink line height
                    p.style.cssText = 'padding: 8px 0 ; line-height: 20px')

                // Format buttons
                const btns = donateModal.querySelectorAll('button')
                btns.forEach((btn, idx) => {
                    if (idx == 0) btn.style.display = 'none' // hide Dismiss button
                    else {
                        btn.style.cssText = 'padding: 8px 6px !important ; margin-top: -14px ; width: 107px ; line-height: 14px'
                        if (idx == btns.length -1) // de-emphasize right-most button
                            btn.classList.remove('primary-modal-btn')
                        else if (/rate/i.test(btn.textContent)) // localize 'Rate Us' label
                            btn.textContent = app.msgs.btnLabel_rateUs
                    }
                })
            }
        },

        safeWinOpen(url) { window.open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    }

    // Define SYNC functions

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

    // Run MAIN routine

    // Create browser TOOLBAR MENU or DISABLE SCRIPT if extension installed
    const extensionInstalled = await Promise.race([
        new Promise(resolve => {
            (function checkExtensionInstalled() {
                if (document.querySelector('[chatgpt-auto-continue-extension-installed]')) resolve(true)
                else setTimeout(checkExtensionInstalled, 200)
            })()
        }), new Promise(resolve => setTimeout(() => resolve(false), 1500))])
    if (extensionInstalled) { // disable script/menu
        GM_registerMenuCommand(`${menu.state.symbols[0]} ${app.msgs.menuLabel_disabled}`, modals.about.show)
        return // exit script
    } else menu.register() // create functional menu

    // Add/update TWEAKS style
    const tweaksStyleUpdated = 20241002 // datestamp of last edit for this file's `tweaksStyle`
    let tweaksStyle = document.getElementById('tweaks-style') // try to select existing style
    if (!tweaksStyle || parseInt(tweaksStyle.getAttribute('last-updated'), 10) < tweaksStyleUpdated) { // if missing or outdated
        if (!tweaksStyle) { // outright missing, create/id/attr/append it first
            tweaksStyle = document.createElement('style') ; tweaksStyle.id = 'tweaks-style'
            tweaksStyle.setAttribute('last-updated', tweaksStyleUpdated.toString())
            document.head.append(tweaksStyle)
        }
        tweaksStyle.innerText = (
            ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
          + '.chatgpt-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;' // shrink/uppercase labels
              + `border: 2px dashed ${ chatgpt.isDarkMode() ? 'white' : 'black' } !important ; border-radius: 0 !important ;` // thiccen/square/dash borders
              + 'transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out ;' // smoothen hover fx
              + 'cursor: pointer !important ;' // add finger cursor
              + 'padding: 5px !important ; min-width: 102px }' // resize
          + '.chatgpt-modal button:hover {' // add zoom, re-scheme
              + 'transform: scale(1.055) ;'
              + ( chatgpt.isDarkMode() ? 'background-color: #2cff00 !important ; box-shadow: 2px 1px 54px #38ff00 !important ; color: black !important'
                                       : 'background-color: #c7ff006b !important ; box-shadow: 2px 1px 30px #97ff006b !important' ) + '}'
          + '.modal-buttons { margin-left: -13px !important }'
          + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
          + '.sticky div:active, .sticky div:focus {' // post-GPT-4o UI sidebar button container
              + 'transform: none !important }' // disable distracting click zoom effect
        )
    }

    // Observe DOM for need to continue generating response
    (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)
    })()

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

})()