Greasy Fork is available in English.

Wyczyść Historię ChatGPT 🕶️

Automatycznie czyści historię czatu podczas odwiedzania chat.openai.com

Stan na 23-02-2024. Zobacz najnowsza wersja.

// ==UserScript==
// @name                Autoclear ChatGPT History
// @name:af             Verwyder ChatGPT Geskiedenis 🕶️
// @name:am             በተሻለ ChatGPT ጉዳዮ ማግኘት 🕶️
// @name:ar             مسح تاريخ ChatGPT 🕶️
// @name:az             ChatGPT Tarixini Təmizləyin 🕶️
// @name:be             Ачысціць гісторыю ChatGPT 🕶️
// @name:bem            Lekeni ChatGPT History 🕶️
// @name:bg             Изчистете ChatGPT История 🕶️
// @name:bn             চ্যাটজিপিটি ইতিহাস মুছে ফেলুন 🕶️
// @name:bo             ChatGPT སྐད་དོན་ཚར་བཟོ། 🕶️
// @name:bs             Obriši ChatGPT historiju 🕶️
// @name:ca             Esborra l'historial de ChatGPT 🕶️
// @name:ceb            Autoclear ChatGPT Kasaysayan 🕶️
// @name:ckb            بسڕەوەی مێژووی ChatGPT 🕶️
// @name:cs             Vymazat ChatGPT Historii 🕶️
// @name:cy             Clirio Hanes ChatGPT 🕶️
// @name:da             Ryd ChatGPT Historik 🕶️
// @name:de             ChatGPT-Verlauf löschen 🕶️
// @name:dv             ChatGPT ހިސްތުކުރުން ފުހެވޭނީ 🕶️
// @name:dz             ChatGPT སྐད་ཆ་འབད་བཅུ་ 🕶️
// @name:el             Διαγραφή Ιστορικού ChatGPT 🕶️
// @name:eo             Forviŝi ChatGPT Historion 🕶️
// @name:es             Borrar Historial de ChatGPT 🕶️
// @name:et             Kustuta ChatGPT Ajalugu 🕶️
// @name:eu             Ezabatu ChatGPT Historia 🕶️
// @name:fa             پاک کردن تاریخچه ChatGPT 🕶️
// @name:fi             Poista ChatGPT:n historia 🕶️
// @name:fo             Strika ChatGPT Søgu 🕶️
// @name:fr             Effacer l'historique de ChatGPT 🕶️
// @name:fr-CA          Effacer l'historique de ChatGPT 🕶️
// @name:gd             Lùghdaich Eachdraidh ChatGPT 🕶️
// @name:gl             Limpar Historial de ChatGPT 🕶️
// @name:gu             આપો ChatGPT ઇતિહાસ 🕶️
// @name:haw            Kāpaki Kākoʻo i ka Moʻolelo o ChatGPT 🕶️
// @name:he             מחק את היסטוריית ChatGPT 🕶️
// @name:hi             ChatGPT इतिहास को हटाएं 🕶️
// @name:hr             Izbriši ChatGPT Povijest 🕶️
// @name:ht             Efase ChatGPT Istwa 🕶️
// @name:hu             ChatGPT Előzmények Törlése 🕶️
// @name:hy             Ջնջել ChatGPT-ի Պատմությունը 🕶️
// @name:id             Hapus Riwayat ChatGPT 🕶️
// @name:is             Eyða ChatGPT Saga 🕶️
// @name:it             Cancella Cronologia ChatGPT 🕶️
// @name:ja             ChatGPT の履歴を削除する 🕶️
// @name:jv             Hapus Riwayat ChatGPT 🕶️
// @name:ka             ChatGPT-ის ისტორიის გასუფთავება 🕶️
// @name:kab            Sken ChatGPT Tamɣarit 🕶️
// @name:kk             ChatGPT Тарихын Жою 🕶️
// @name:km             លុបប្រវត្តិសាស្រ្ត ChatGPT 🕶️
// @name:kn             ChatGPT ಇತಿಹಾಸವನ್ನು ಅಳಿಸಿ 🕶️
// @name:ko             ChatGPT 기록 지우기 🕶️
// @name:ku             Çavkaniya ChatGPTê Paqij bike 🕶️
// @name:ky             ChatGPT Тарыхын Жок Кыл 🕶️
// @name:la             Eximitte Historiam ChatGPT 🕶️
// @name:lb             Läschen ChatGPT Geschicht 🕶️
// @name:lo             ລຶບບັນດາຕິນມັກສະບັບ ChatGPT 🕶️
// @name:lt             Išvalyti ChatGPT Istoriją 🕶️
// @name:lv             Notīrīt ChatGPT Vēsturi 🕶️
// @name:mg             Mamafa ny ChatGPT Historique 🕶️
// @name:mi             Muku ChatGPT Hītori 🕶️
// @name:mk             Избриши го Историјата на ChatGPT 🕶️
// @name:ml             ചാറ്റ്‌ജിപിടി ചരിത്രം മായ്ക്കുക 🕶️
// @name:mn             ChatGPT Түүхийг устгах 🕶️
// @name:ms             Padam Sejarah ChatGPT 🕶️
// @name:mt             Ħassar It-Twaħħil ChatGPT 🕶️
// @name:my             ဆက်လက် ChatGPT သမိုင်းကို ဖျက်ပစ်နေပါသည် 🕶️
// @name:ne             Autoclear ChatGPT इतिहास 🕶️
// @name:nl             Wis ChatGPT Geschiedenis 🕶️
// @name:no             Autoclear ChatGPT Historie 🕶️
// @name:ny             Tikalonso ChatGPT Chisulo 🕶️
// @name:pa             ਚੈਟਜੀਪੀਟੀ ਇਤਿਹਾਸ ਮਿਟਾਓ 🕶️
// @name:pap            Bula Historia di ChatGPT 🕶️
// @name:pl             Wyczyść Historię ChatGPT 🕶️
// @name:ps             د ChatGPT د تاریخ پاکول 🕶️
// @name:pt             Limpar Histórico do ChatGPT 🕶️
// @name:pt-BR          Limpar Histórico do ChatGPT 🕶️
// @name:rn             Kwihesha ChatGPT Byinshi 🕶️
// @name:ro             Ștergeți Istoricul ChatGPT 🕶️
// @name:ru             Очистить Историю ChatGPT 🕶️
// @name:rw             Fata ChatGPT Itangazo 🕶️
// @name:sg             Mbama ChatGPT Makumbe 🕶️
// @name:si             නැවත සංවේදී ChatGPT ඉතිරිකිරීම 🕶️
// @name:sk             Vymažte ChatGPT Históriu 🕶️
// @name:sl             Počisti Zgodovino ChatGPT 🕶️
// @name:sm             Masi ChatGPT Faʻaipoipoga 🕶️
// @name:sn             Tirisa ChatGPT Chiremba 🕶️
// @name:so             Ka Saar Tareenka ChatGPT 🕶️
// @name:sr             Обриши историју ChatGPT-а 🕶️
// @name:sv             Rensa ChatGPT Historik 🕶️
// @name:sw             Futa Historia ya ChatGPT 🕶️
// @name:ta             தானாகவே அழிக்க சேட்ஜிபிடி வரலாற்றை 🕶️
// @name:te             ChatGPT చరిత్రను తొలగించు 🕶️
// @name:tg             Тозаиши корҳои ChatGPT 🕶️
// @name:th             ล้างประวัติศาสตร์ ChatGPT 🕶️
// @name:ti             ምርግጋጽ ChatGPT ኣጸዓይ ፈጥር 🕶️
// @name:tk             ChatGPT Tarixini Aýyr 🕶️
// @name:tn             Futa ChatGPT Tlhahlobo 🕶️
// @name:to             Fakatonu ChatGPT History 🕶️
// @name:tpi            Kolim ChatGPT Stori 🕶️
// @name:tr             ChatGPT Geçmişi Temizle 🕶️
// @name:uk             Очистити Історію ChatGPT 🕶️
// @name:ur             ChatGPT کی تاریخ صاف کریں 🕶️
// @name:uz             ChatGPT Tarixini Tozalash 🕶️
// @name:vi             Xóa Lịch Sử ChatGPT 🕶️
// @name:xh             Qhipha ChatGPT Isaziso 🕶️
// @name:yi             ויסמעקן טשאַטגפּט געשיכטע 🕶️
// @name:zh             自动清除 ChatGPT 历史记录 🕶️
// @name:zh-CN          自动清除 ChatGPT 历史记录 🕶️
// @name:zh-HK          自動清除 ChatGPT 歷史記錄 🕶️
// @name:zh-SG          自动清除 ChatGPT 历史记录 🕶️
// @name:zh-TW          自動清除 ChatGPT 歷史記錄 🕶️
// @name:zu             Sula ChatGPT Isifundo 🕶️
// @description         Auto-clears chat history when visiting chat.openai.com
// @description:af      Skoonmaak Chat Geskiedenis wanneer jy chat.openai.com besoek
// @description:am      የ chat.openai.com ጸሃይ ታክሲን በማግኘት ታከለው
// @description:ar      يقوم تلقائيًا بمسح سجل المحادثات عند زيارة chat.openai.com
// @description:az      chat.openai.com-a gedəndə avtomatik olaraq söhbət tarixini təmizləyir
// @description:be      Аўтаматычна ачышчае гісторыю чата пры наведванні chat.openai.com
// @description:bem     Chibwezache Mphindi Zochitika Pamene Kumatemba chat.openai.com
// @description:bg      Автоматично изчиства чат историята при посещение на chat.openai.com
// @description:bn      যখন chat.openai.com পরিদর্শন করা হলে অটোমেটিকভাবে চ্যাট ইতিহাস মুছে ফেলে
// @description:bo      དཔེར་ན་ chat.openai.com འགྲེལ་བཤད་འདི་ལུ་ སྤྱོད་ཡོད་མི་འདི་བལྟ་མི་བཟོ།
// @description:bs      Automatski briše istoriju chata prilikom posjete chat.openai.com
// @description:ca      S'elimina automàticament l'historial de xats en visitar chat.openai.com
// @description:ceb     Automatic gidut-ana sa kasaysayan sa chat sa pagbisita sa chat.openai.com
// @description:ckb     ده‌ستکاریکردنی مێژووی گفتوگۆکان خۆکارانه بۆ سەردانی chat.openai.com
// @description:cs      Automaticky vymaže historii chatu při návštěvě chat.openai.com
// @description:cy      Mae'n glirio hanes sgwrs yn awtomatig wrth ymweld â chat.openai.com
// @description:da      Renser automatisk chatloggen ved besøg på chat.openai.com
// @description:de      Löscht den Chatverlauf automatisch beim Besuch von chat.openai.com
// @description:dv      chat.openai.com އެކައުންމަދުގެ ޗެކުމު ހުރިހައްދަވާނެ ޗައިންކުރޭ
// @description:dz      འཛུགས་མིག་འདི་ལུ་ chat.openai.com འགྲེལ་བཤད་རོགས་བསྐྱེད་ཡོད།
// @description:el      Αυτόματη διαγραφή ιστορικού συνομιλίας κατά την επίσκεψη στο chat.openai.com
// @description:eo      Memorigo de la babilado aŭtomate malaperas dum vizito ĉe chat.openai.com
// @description:es      Borra automáticamente el historial de chat al visitar chat.openai.com
// @description:et      Kustutab automaatselt vestluse ajaloo, kui külastate saiti chat.openai.com
// @description:eu      Berezgaitasunez ezabatzen du txataren historia chat.openai.com bisitatzen denean
// @description:fa      پاک کردن خودکار تاریخچه چت در هنگام بازدید از chat.openai.com
// @description:fi      Poistaa keskusteluhistorian automaattisesti käydessä chat.openai.comissa
// @description:fo      Auto-rensar spjall søguna tá tú vitjar chat.openai.com
// @description:fr      Efface automatiquement l'historique des discussions lors de la visite de chat.openai.com
// @description:fr-CA   Efface automatiquement l'historique des discussions lors de la visite de chat.openai.com
// @description:gd      Thoir aire bheagachaidh air eachdraidh na còmhraidh nuair a tha thu a' tadhal air chat.openai.com
// @description:gl      Limpa automáticamente o historial do chat ao visitar chat.openai.com
// @description:gu      chat.openai.com મુકે છે નાતીજે જ્ઞાનવર્ધક ચેટ નો ઇતિહાસ
// @description:haw     Mālama haku ʻinoʻino pāhana hoʻohānau mai ana i chat.openai.com
// @description:he      מנקה באופן אוטומטי את היסטוריית הצ'אט בעת ביקור ב-chat.openai.com
// @description:hi      chat.openai.com पर आवर्तित होने पर चैट इतिहास को स्वचालित रूप से साफ करता है
// @description:hr      Automatski briše povijest razgovora prilikom posjeta chat.openai.com
// @description:ht      Auto-efase istwa chat la lè vizite chat.openai.com
// @description:hu      Automatikusan törli a csevegés előzményeit a chat.openai.com látogatásakor
// @description:hy      Պատմությունը ինքնաշխատանքային մաքրում է chat.openai.com այցելելուն դեպի
// @description:id      Menghapus otomatis riwayat obrolan saat mengunjungi chat.openai.com
// @description:is      Hreinsar sjálfvirkt spjallshönnun þegar heimsókn er gerð á chat.openai.com
// @description:it      Cancella automaticamente la cronologia della chat durante la visita a chat.openai.com
// @description:ja      chat.openai.com を訪れる際に自動的にチャット履歴を消去します
// @description:jv      Otomatis ngapus riwayat obrolan nalika ngunjungi chat.openai.com
// @description:ka      თავისითად წაშლის ჩათის ისტორიას chat.openai.com-ზე მომსახურების დროს
// @description:kab     Ireɣsan Ayren Tisstrir ChatGPT I yur-s achat.openai.com
// @description:kk      chat.openai.com-ды көруге бастап автоматты түрде чат тарихын жою
// @description:km      លុបសេវាកម្មប្រវត្តិការណ៍ជជែកពីព័ត៌មានមនុស្សកន្លងទៅកាន់ chat.openai.com
// @description:kn      chat.openai.com ಸಂದರ್ಶಿಸಿದಾಗ ಸ್ವಯಂಚಾಲಿತವಾಗಿ ಚಾಟ್ ಇತಿಹಾಸವನ್ನು ಅಳಿಸುತ್ತದೆ
// @description:ko      chat.openai.com 방문 시 채팅 기록을 자동으로 지웁니다
// @description:ku      Çêkirina historyaya chatê di hembêzkirina chat.openai.com de
// @description:ky      chat.openai.com барысында түр кат жазмаларын автоматтык түрде жок этиш
// @description:la      Automate chat historia clearum cum chat.openai.com adibvisam
// @description:lb      Läscht automatesch d'Chat-Geschicht wéini een chat.openai.com besicht
// @description:lo      ລຶບປະວັດການສົນທະນາໃນຖ້າເຂົ້າຊົມ chat.openai.com
// @description:lt      Automatiškai išvalo pokalbių istoriją apsilankius chat.openai.com
// @description:lv      Automātiski notīra čata vēsturi, apmeklējot chat.openai.com
// @description:mg      Mamafa tsy ampy lalao ny tetikasa vaovao rehefa mitovy amin'ny chat.openai.com
// @description:mi      Auto-kōmata e whakakore i te hītori whakawhiti kōrero i te toro ki te chat.openai.com
// @description:mk      Автоматски брише историја на разговорот при посета на chat.openai.com
// @description:ml      chat.openai.com സന്ദർശിക്കുമ്പോൾ ചാറ്റ് ചരിത്രം ഓട്ടോ-പിന്തുണച്ച് അഴിച്ചുവയ്ക്കുന്നു
// @description:mn      chat.openai.com-оос орж ирэх үед чатын түүхийг автоматаар цэвэрлэнэ
// @description:ms      Membersihkan sejarah perbualan secara automatik apabila melawat chat.openai.com
// @description:mt      Jħassar awtomatikament il-kronoloġija tal-chat meta żżur chat.openai.com
// @description:my      chat.openai.com ကိုသွားဖို့အတွက် စကားဝှက်မှတ်တမ်းကို အလိုလိုရွေးချယ်ရန် အလွယ်တကူပြန်ဖွင့်ထားသည်
// @description:ne      chat.openai.com मा आएकोमा च्याट इतिहास स्वचालित रूपमा हटाउँछ
// @description:nl      Wis automatisch de chatgeschiedenis bij een bezoek aan chat.openai.com
// @description:no      Sletter automatisk samtalehistorikk ved besøk på chat.openai.com
// @description:ny      Kwatsa makina m'chipatala cha chat pamene kuwona chat.openai.com
// @description:pa      chat.openai.com ਦੇ ਦੌਰਾਨ ਚੈਟ ਇਤਿਹਾਸ ਆਟੋਮੈਟਿਕ ਕਲੀਅਰ ਹੋ ਜਾਂਦਾ ਹੈ
// @description:pap     Limpieza automático di historial di chat na bishita chat.openai.com
// @description:pl      Automatycznie czyści historię czatu podczas odwiedzania chat.openai.com
// @description:ps      خودکار تاریخچه چت پاک کول په chat.openai.com کښې
// @description:pt      Limpa automaticamente o histórico de bate-papo ao visitar chat.openai.com
// @description:pt-BR   Limpa automaticamente o histórico de bate-papo ao visitar chat.openai.com
// @description:rn      Guteza inkuru y'ikarita y'imibare igihe utanga chat.openai.com
// @description:ro      Șterge automat istoricul chat-ului la vizitarea chat.openai.com
// @description:ru      Автоматически очищает историю чата при посещении chat.openai.com
// @description:rw      Inyunganira amakuru ya chat inyuma yuko umaze guhamagara chat.openai.com
// @description:sg      Auto-kura kolibatalu ya misamba wakari karika kutɔbɔ chat.openai.com
// @description:si      chat.openai.com වෙත පැය සඳහා ස්වයංක්‍රීයතාවයින් චැට් ඉතිරිකිරීම මකා දැමුම
// @description:sk      Automaticky vymazáva históriu chatu pri návšteve chat.openai.com
// @description:sl      Samodejno izbriše zgodovino klepeta ob obisku spletnega mesta chat.openai.com
// @description:sm      Automa i le malologa o le sootaga i luma i le chat.openai.com
// @description:sn      Inongorora chat history chinayo ipapo uchi chiri kunochinja chat.openai.com
// @description:so      Wax ka qaad chatka markii la booqdo chat.openai.com
// @description:sr      Аутоматски брише историју чата при посети chat.openai.com
// @description:sv      Rensar automatiskt chattens historik vid besök på chat.openai.com
// @description:sw      Inaondoa historia ya mazungumzo moja kwa moja wakati wa kutembelea chat.openai.com
// @description:ta      chat.openai.com அடுத்தடுத்தப்படும் நேரத்தில் உரையாடல் வரலாறை தானியங்கே நீக்குகிறது
// @description:te      chat.openai.com సందర్శించినప్పుడు స్వయంచాలకంగా చాట్ చరిత్రను తొలగిస్తుంది
// @description:tg      Тарихи чатро худкор ҷоба кунед, ки chat.openai.com равед
// @description:th      ล้างประวัติการสนทนาโดยอัตโนมัติเมื่อเข้าชม chat.openai.com
// @description:ti      ኮምፕዩተር እየጠበቀ ጊዜ chat.openai.com የተሰኘውን ችግርን አስፈልጋል
// @description:tk      chat.openai.com-a ugradykda çat görnüşini awtomatiki biçimde boşaltýar
// @description:tn      Emucisha chat chinyakanyaka nga uwonawo chat.openai.com
// @description:to      'Oku fa'a kovi 'e he ngaahi sipoti fakamatala 'i he falelotu ki he chat.openai.com
// @description:tpi     Autometik klia chat histeri long bisitim long chat.openai.com
// @description:tr      chat.openai.com'u ziyaret ettiğinizde sohbet geçmişini otomatik olarak temizler
// @description:uk      Автоматично очищає історію чату при відвідуванні chat.openai.com
// @description:ur      chat.openai.com کے دورے پر چیٹ تاریخ خودکار طور پر صاف کرتا ہے
// @description:uz      chat.openai.com saytini tashrif buyurganda chat tarixini avtomatik ravishda o'chiradi
// @description:vi      Xóa lịch sử trò chuyện tự động khi ghé thăm chat.openai.com
// @description:xh      Ingqalasela ihisitela le-chat uma uzithola chat.openai.com
// @description:yi      רומט די פֿונען דער שאַט היסטאָריע ביי בעזוך בקוקן chat.openai.com
// @description:zh      访问 chat.openai.com 时自动清除聊天记录
// @description:zh-CN   访问 chat.openai.com 时自动清除聊天记录
// @description:zh-HK   訪問 chat.openai.com 時自動清除聊天記錄
// @description:zh-SG   访问 chat.openai.com 时自动清除聊天记录
// @description:zh-TW   訪問 chat.openai.com 時自動清除聊天記錄
// @description:zu      Ziba itshala lokucabanga okuzoshintshwa ngokuzenzakalelayo uma ukubuka chat.openai.com
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.2.23
// @license             MIT
// @icon                https://raw.githubusercontent.com/adamlui/userscripts/master/chatgpt/media/icons/openai-favicon48.png
// @icon64              https://raw.githubusercontent.com/adamlui/userscripts/master/chatgpt/media/icons/openai-favicon64.png
// @compatible          chrome
// @compatible          edge
// @compatible          firefox
// @compatible          opera
// @compatible          brave
// @compatible          vivaldi
// @compatible          librewolf
// @compatible          ghost
// @compatible          qq
// @match               *://chat.openai.com/*
// @run-at              document-end
// @require             https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@2.6.5/dist/chatgpt.min.js#sha256-g22gyKeCX7FgEKHXxU3huz8oDksJqCURmRF2RwgSrP0=
// @connect             raw.githubusercontent.com
// @connect             greasyfork.org
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @grant               GM_openInTab
// @grant               GM.xmlHttpRequest
// @noframes
// @homepageURL         https://github.com/adamlui/autoclear-chatgpt-history
// @supportURL          https://github.com/adamlui/autoclear-chatgpt-history/issues
// ==/UserScript==

// NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org (c) 2023–2024 KudoAI & contributors under the MIT license.

(async () => {

    // Init config
    const config = {
        appName: 'Autoclear ChatGPT History', appSymbol: '🕶️', userLanguage: chatgpt.getUserLanguage(),
        gitHubURL: 'https://github.com/adamlui/autoclear-chatgpt-history',
        greasyForkURL: 'https://greasyfork.org/scripts/460805-autoclear-chatgpt-history' }
    config.keyPrefix = toCamelCase(config.appName)
    config.updateURL = config.greasyForkURL.replace('https://', 'https://update.')
        .replace(/(\d+)-?(.*)$/, (_, id, name) => `${ id }/${ !name ? 'script' : name }.meta.js`)
    config.supportURL = config.gitHubURL + '/issues/new'
    config.assetHostURL = config.gitHubURL.replace('github.com', 'raw.githubusercontent.com') + '/main/'
    loadSetting('autoclear', 'buttonHidden', 'notifDisabled', 'toggleHidden')

    // Define messages
    const msgsLoaded = new Promise(resolve => {
        const msgHostDir = config.assetHostURL + 'greasemonkey/_locales/',
              msgLocaleDir = ( config.userLanguage ? config.userLanguage.replace('-', '_') : 'en' ) + '/'
        let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
        GM.xmlHttpRequest({ method: 'GET', url: msgHref, onload: onLoad })
        function onLoad(response) {
            try { // to return localized messages.json
                const messages = new Proxy(JSON.parse(response.responseText), {
                    get(target, prop) { // remove need to ref nested keys
                        if (typeof target[prop] == 'object' && target[prop] !== null && 'message' in target[prop]) {
                            return target[prop].message
                }}}) ; resolve(messages)
            } catch (err) { // if 404
                msgXHRtries++ ; if (msgXHRtries === 3) return // 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
                GM.xmlHttpRequest({ method: 'GET', url: msgHref, onload: onLoad })
            }
        }
    }) ; const messages = await msgsLoaded

    // Init/register menu
    const state = {
        symbol: ['✔️', '❌'], word: ['ON', 'OFF'],
        separator: getUserscriptManager() == 'Tampermonkey' ? ' — ' : ': ' }
    let menuIDs = [] ; registerMenu() // create browser toolbar menu

    // Add/update tweaks style
    const tweaksStyleUpdated = 2023123 // datestamp of last edit for this file's `tweaksStyle`
    await chatgpt.isLoaded()
    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-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;'
              + 'border-radius: 0 !important ; padding: 5px !important ; min-width: 102px }'
          + '.modal-buttons { margin-left: -13px !important }'
          + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
        )
    }

    // Create nav toggle div, add styles
    const navToggleDiv = document.createElement('div')
    navToggleDiv.style.maxHeight = '44px' // prevent flex overgrowth
    navToggleDiv.style.margin = '2px 0' // add v-margins
    navToggleDiv.style.userSelect = 'none' // prevent highlighting
    navToggleDiv.style.cursor = 'pointer' // add finger cursor
    updateToggleHTML() // create children

    // Borrow classes from sidebar div
    const chatHistorySelector = 'nav[aria-label="Chat history"]',
          re_firstBtnText = chatgpt.history.isOff() ? /ChatGPTClear/ : /ChatGPT(ChatGPT|New)/
    chatgpt.history.isLoaded().then(setTimeout(() => { 
        const chatHistoryNav = document.querySelector(chatHistorySelector) || {},
              navLinks = chatHistoryNav.querySelectorAll('a'),
              firstLink = [...navLinks].find(link => re_firstBtnText.test(link.textContent)),
              firstIcon = firstLink.querySelector('div:first-child'),
              firstLabel = firstLink.querySelector('div:nth-child(2)')
        navToggleDiv.classList.add(...firstLink.classList, ...firstLabel.classList)
        navToggleDiv.querySelector('img')?.classList.add(...firstIcon.classList)
    }, 100))

    // Add listener to toggle switch/label/config/menu + auto-clear
    navToggleDiv.addEventListener('click', () => {
        const toggleInput = document.querySelector('#acToggleInput')
        toggleInput.checked = !toggleInput.checked
        config.autoclear = toggleInput.checked
        updateToggleHTML()
        for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        if (config.autoclear) {
            setTimeout(chatgpt.clearChats, 250)
            if (!config.notifDisabled) notify(( messages.mode_autoClear || 'Auto-Clear' ) + ': ON')
        } else if (!config.autoclear)
            if (!config.notifDisabled) notify(( messages.mode_autoClear || 'Auto-Clear' ) + ': OFF')
        saveSetting('autoclear', config.autoclear)
    })

    // Insert full toggle on page load + during navigation
    insertToggle()
    const nodeObserver = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type == 'childList' && mutation.addedNodes.length) {
                insertToggle()
    }})}) ; nodeObserver.observe(document.documentElement, { childList: true, subtree: true })

    // Auto-clear on first visit if enabled
    if (config.autoclear) {
        if (chatgpt.history.isOn()) setTimeout(() => { chatgpt.clearChats() }, 250)
        if (!config.notifDisabled) notify(( messages.mode_autoClear || 'Auto-Clear' ) + ': ON')
    }

    // Define SCRIPT functions

    function loadSetting(...keys) { keys.forEach(key => { config[key] = GM_getValue(config.keyPrefix + '_' + key, false) })}
    function saveSetting(key, value) { GM_setValue(config.keyPrefix + '_' + key, value) ; config[key] = value }
    function safeWindowOpen(url) { window.open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    function getUserscriptManager() { try { return GM_info.scriptHandler } catch (err) { return 'other' }}

    function toCamelCase(str) { // for `config.keyPrefix` derived from `config.appName`
        let lastLetterWasUpper = false, isFirstWord = true
        return str.replace(/-/g, ' ') // remove hyphens
            .split(' ').flatMap(word => { // split input into words/acronyms for individual processing
                if (/[A-Z]{2,}/.test(word) && word != word.toUpperCase()) { // word contains acronym
                    if (/^[A-Z][a-z]/.test(word)) // word starts w/ title-cased non-acronym
                        word = word.charAt(0).toLowerCase() + word.slice(1) // lower-case it
                    return word.replace(/([a-z]+)([A-Z]+)/g, '$1 $2') // separate words from following acronyms
                               .replace(/([A-Z]+)([a-z]+)/g, '$1 $2') // separate acronyms from following words
                               .split(' ') // split for individual processing
                } else return word // non-acronym
            }).map(word => { // convert each word/acronym's case
                const isFullAcronym = word.toUpperCase() == word
                const result = isFullAcronym
                    ? ( lastLetterWasUpper || isFirstWord ) ? word.toLowerCase() : word // alternate acronym case
                    : ( lastLetterWasUpper || isFirstWord ) // alternate non-acronym case
                        ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
                isFirstWord = false ; lastLetterWasUpper = isFullAcronym ? (result == word && !isFirstWord) : false
                return result
            }).join('') // combine to form camel case
    }

    // Define MENU functions

    function registerMenu() {
        menuIDs = [] // empty to store newly registered cmds for removal while preserving order

        // Add command to toggle auto-clear
        const acLabel = state.symbol[+!config.autoclear] + ' '
                      + ( messages.menuLabel_autoClear || 'Autoclear Chats' )
                      + state.separator + state.word[+!config.autoclear]
        menuIDs.push(GM_registerMenuCommand(acLabel, () => {
            document.querySelector('#acToggleLabel').click()
        }))

        // Add 'Toggle Visibility' command
        const tvLabel = state.symbol[+config.toggleHidden] + ' '
                      + ( messages.menuLabel_toggleVis || 'Toggle Visibility' )
                      + state.separator + state.word[+config.toggleHidden]
        menuIDs.push(GM_registerMenuCommand(tvLabel, () => {
            saveSetting('toggleHidden', !config.toggleHidden)
            navToggleDiv.style.display = config.toggleHidden ? 'none' : 'flex' // toggle visibility
            if (!config.notifDisabled) {
                notify(( messages.menuLabel_toggleVis || 'Toggle Visibility' ) + ': '+ state.word[+config.toggleHidden])
            } for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        }))

        // Add command to show notifications when changing settings/modes
        const mnLabel = state.symbol[+config.notifDisabled] + ' '
                      + ( messages.menuLabel_modeNotifs || 'Mode Notifications' )
                      + state.separator + state.word[+config.notifDisabled]
        menuIDs.push(GM_registerMenuCommand(mnLabel, () => {
            saveSetting('notifDisabled', !config.notifDisabled)
            notify(( messages.menuLabel_modeNotifs || 'Mode Notifications' ) + ': ' + state.word[+config.notifDisabled])
            for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        }))

        // Add command to launch About modal
        const amLabel = '💡 ' + ( messages.menuLabel_about || 'About' ) + ' '
                      + ( messages.appName || config.appName )
        menuIDs.push(GM_registerMenuCommand(amLabel, launchAboutModal))
    }

    function launchAboutModal() {

        // Init data/styles
        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

        // Show alert
        const aboutAlertID = alert(
            messages.appName || config.appName, // title
            `<span style="${ headingStyle }"><b>🏷️ <i>${ messages.about_version || 'Version' }</i></b>: </span>`
                + `<span style="${ pStyle }">${ GM_info.script.version }</span>\n`
            + `<span style="${ headingStyle }"><b>⚡ <i>${ messages.about_poweredBy || 'Powered by' }</i></b>: </span>`
                + `<span style="${ pStyle }"><a style="${ aStyle }" href="https://chatgpt.js.org" target="_blank" rel="noopener">`
                + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
            + `<span style="${ headingStyle }"><b>📜 <i>${ messages.about_sourceCode || 'Source code' }</i></b>:</span>\n`
                + `<span style="${ pBrStyle }"><a href="${ config.gitHubURL }" target="_blank" rel="nopener">`
                + config.gitHubURL + '</a></span>',
            [ // buttons
                function checkForUpdates() { updateCheck() },
                function getSupport() { safeWindowOpen(config.supportURL) },
                function leaveAReview() { // show review modal
                    const reviewAlertID = chatgpt.alert(( messages.alert_choosePlatform || 'Choose a platform' ) + ':', '',
                        [ function greasyFork() { safeWindowOpen(config.greasyForkURL + '/feedback#post-discussion') },
                          function futurepedia() { safeWindowOpen(
                              'https://www.futurepedia.io/tool/autoclear-chatgpt-history#autoclear-chatgpt-history-review') }])
                    document.getElementById(reviewAlertID).querySelector('button')
                        .style.display = 'none' }, // hide dismiss button
                function moreChatGPTapps() { safeWindowOpen('https://github.com/adamlui/chatgpt-apps') }
            ], '', 478 // set width
        )

        // Re-format buttons to include emoji + localized label + hide Dismiss button
        for (const button of document.getElementById(aboutAlertID).querySelectorAll('button')) {
            if (/updates/i.test(button.textContent)) button.textContent = (
                '🚀 ' + ( messages.buttonLabel_updateCheck || 'Check for Updates' ))
            else if (/support/i.test(button.textContent)) button.textContent = (
                '🧠 ' + ( messages.buttonLabel_getSupport || 'Get Support' ))
            else if (/review/i.test(button.textContent)) button.textContent = (
                '⭐ ' + ( messages.buttonLabel_leaveReview || 'Leave a Review' ))
            else if (/apps/i.test(button.textContent)) button.textContent = (
                '🤖 ' + ( messages.buttonLabel_moreApps || 'More ChatGPT Apps' ))
            else button.style.display = 'none' // hide Dismiss button
        }
    }

    function updateCheck() {

        // Fetch latest meta
        const currentVer = GM_info.script.version
        GM.xmlHttpRequest({
            method: 'GET', url: config.updateURL + '?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 updateAlertID = alert(( messages.alert_updateAvail || 'Update available' ) + '! 🚀', // title
                            ( messages.alert_newerVer || 'An update to' ) + ' ' // msg
                                + ( messages.appName || config.appName ) + ' '
                                + `(v ${ latestVer }) ${ messages.alert_isAvail || 'is available' }!   `
                                + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
                                    + 'href="' + config.gitHubURL + '/commits/main/greasemonkey/'
                                    + config.updateURL.replace(/.*\/(.*)meta\.js/, '$1user.js') + '" '
                                    + `> ${ messages.link_viewChanges || 'View changes' }</a>`,
                            function update() { // button
                                GM_openInTab(config.updateURL.replace('meta.js', 'user.js') + '?t=' + Date.now(),
                                    { active: true, insert: true } // focus, make adjacent
                                ).onclose = () => location.reload() },
                            '', updateAlertWidth
                        )

                        // Localize button labels if needed
                        if (!config.userLanguage.startsWith('en')) {
                            const updateAlert = document.querySelector(`[id="${ updateAlertID }"]`),
                                  updateBtns = updateAlert.querySelectorAll('button')
                            updateBtns[1].textContent = messages.buttonLabel_update || 'Update'
                            updateBtns[0].textContent = messages.buttonLabel_dismiss || 'Dismiss'
                        }

                        return
                }}

                // Alert to no update, return to About alert
                alert(( messages.alert_upToDate || 'Up-to-date' ) + '!', // title
                    `${ messages.appName || config.appName } (v${ currentVer }) ` // msg
                        + ( messages.alert_isUpToDate || 'is up-to-date' ) + '!',
                    '', '', updateAlertWidth
                )
                launchAboutModal()
    }})}

    // Define FEEDBACK functions

    function notify(msg, position = '', notifDuration = '', shadow = '') {
        chatgpt.notify(`${ config.appSymbol } ${ msg }`, position, notifDuration, shadow || chatgpt.isDarkMode() ? '' : 'shadow') }

    function alert(title = '', msg = '', btns = '', checkbox = '', width = '') {
        return chatgpt.alert(`${ config.appSymbol } ${ title }`, msg, btns, checkbox, width )}

    // Define TOGGLE functions

    async function insertToggle() {
        await chatgpt.history.isLoaded()

        // Select sidebar elems
        const chatHistoryNav = document.querySelector('nav[aria-label="Chat history"]') || {},
              navButtons = chatHistoryNav.querySelectorAll('a'),
              firstButton = [...navButtons].find(button => re_firstBtnText.test(button.textContent))

        // Hide 'Enable History' div + sibling gradient div
        if (chatgpt.history.isOff())
            try {
                const enableHistoryDiv = firstButton.parentNode.parentNode.nextElementSibling,
                      gradientDiv = enableHistoryDiv.nextElementSibling
                enableHistoryDiv.parentNode.style.width = '100%'
                for (const div of [enableHistoryDiv, gradientDiv]) div.style.display = 'none'
            } catch (err) {}

        // Insert toggle
        const parentToInsertInto = firstButton.parentNode.parentNode.parentNode,
              childToInsertBefore = firstButton.parentNode.parentNode.nextElementSibling
        if (!parentToInsertInto.contains(navToggleDiv))
            try { parentToInsertInto.insertBefore(navToggleDiv, childToInsertBefore) } catch (err) {}

        // Tweak styles
        firstButton.parentNode.parentNode.style.paddingBottom = '0'
        parentToInsertInto.style.backgroundColor = ( // hide transparency revealing chat log
            chatgpt.isDarkMode() ? '#0d0d0d' : '#f9f9f9' )
        if (chatgpt.history.isOff() && !config.toggleHidden)
            navToggleDiv.style.display = 'flex' // remove forced cloaking in private mode
        navToggleDiv.style.paddingLeft = chatgpt.history.isOff() ? '20px' : '8px'
        document.querySelector('#acToggleFavicon').src = `${ // update navicon color in case scheme changed
            config.assetHostURL }media/images/icons/incognito/${
            chatgpt.isDarkMode() ? 'white' : 'black' }/icon32.png`
    }

    function updateToggleHTML() {

        // Create/size/position navicon
        const navicon = document.querySelector('#acToggleFavicon') || document.createElement('img')
        navicon.id = 'acToggleFavicon'
        navicon.style.width = navicon.style.height = '1.25rem'
        navicon.style.marginLeft = navicon.style.marginRight = '4px'

        // Create/ID/disable/hide/update checkbox
        const toggleInput = document.querySelector('#acToggleInput') || document.createElement('input')
        toggleInput.id = 'acToggleInput' ; toggleInput.type = 'checkbox' ; toggleInput.disabled = true
        toggleInput.style.display = 'none' ; toggleInput.checked = config.autoclear

        // Create/ID/stylize switch
        const switchSpan = document.querySelector('#acSwitchSpan') || document.createElement('span')
        switchSpan.id = 'acSwitchSpan'
        const switchStyles = {
            position: 'relative', left: `${ chatgpt.browser.isMobile() ? 211 : 152 }px`,
            backgroundColor: toggleInput.checked ? '#ccc' : '#AD68FF', // init opposite  final color
            width: '32px', height: '16px', '-webkit-transition': '.4s', transition: '0.4s',  borderRadius: '28px'
        }
        Object.assign(switchSpan.style, switchStyles)

        // Create/ID/stylize knob, append to switch
        const knobSpan = document.querySelector('#acToggleKnobSpan') || document.createElement('span')
        knobSpan.id = 'acToggleKnobSpan'
        const knobWidth = 13
        const knobStyles = {
            position: 'absolute', left: '3px', bottom: '0.1em',
            width: `${ knobWidth }px`, height: `${ knobWidth }px`, content: '""', borderRadius: '28px',
            transform: toggleInput.checked ? // init opposite final pos
                'translateX(0)' : `translateX(${ knobWidth }px) translateY(0)`,
            backgroundColor: 'white',  '-webkit-transition': '0.4s', transition: '0.4s'
        }
        Object.assign(knobSpan.style, knobStyles) ; switchSpan.append(knobSpan)

        // Create/ID/stylize/fill label
        const toggleLabel = document.querySelector('#acToggleLabel') || document.createElement('label')
        toggleLabel.id = 'acToggleLabel'
        toggleLabel.style.marginLeft = '-41px' // left-shift to navicon
        toggleLabel.style.cursor = 'pointer' // add finger cursor on hover
        toggleLabel.innerText = ( messages.mode_autoClear || 'Auto-clear' ) + ' '
                              + ( toggleInput.checked ? ( messages.state_enabled  || 'enabled' )
                                                      : ( messages.state_disabled || 'disabled' ))
        // Append elements
        for (const elem of [navicon, toggleInput, switchSpan, toggleLabel]) navToggleDiv.append(elem)

        // Update visual state
        navToggleDiv.style.display = config.toggleHidden ? 'none' : 'flex'
        setTimeout(() => {
            if (toggleInput.checked) {
                switchSpan.style.backgroundColor = '#AD68FF'
                switchSpan.style.boxShadow = '2px 1px 9px #D8A9FF'
                knobSpan.style.transform = `translateX(${ knobWidth }px) translateY(0)`
            } else {
                switchSpan.style.backgroundColor = '#CCC'
                switchSpan.style.boxShadow = 'none'
                knobSpan.style.transform = 'translateX(0)'
            }
        }, 1) // min delay to trigger transition fx
    }

})()