-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTM-commandbar.auto.min.js
1 lines (1 loc) · 27.2 KB
/
TM-commandbar.auto.min.js
1
const main=async()=>{const e=MineTm.Mine,t={lastDeletedChatTitleKey:"mine-last-deleted-chat-title",lastDeletedChatEntryKey:"mine-last-deleted-chat-entry",updateChatData:async(e,n)=>await t._withIndexeddbStore("readwrite",(t=>t.put(n,`CHAT_${e}`))),getChatData:async e=>(await t._withIndexeddbStore("readonly",(t=>t.get(`CHAT_${e}`)))).target.result,deleteCurrentChat:async()=>{const n=MineTm.getCurrentChatId(),a=await MineTm.getChatIndexedDbValueAsync(n);if(!a)throw"cant get cur chat data";const s=JSON.stringify(a);sessionStorage.setItem(t.lastDeletedChatEntryKey,s),sessionStorage.setItem(t.lastDeletedChatTitleKey,a.chatTitle),await MineTm.deleteChatIndexedDbValueAsync(n),e.Extension.closeTab()},getLastDeletedChatTitle:()=>sessionStorage.getItem(t.lastDeletedChatTitleKey),isThereARecoverableChat:()=>!!t.getLastDeletedChatTitle(),recoverDeletedChat:async()=>{const n=sessionStorage.getItem(t.lastDeletedChatEntryKey);if(!n)throw"no recoverable chat";const a=JSON.parse(n),s=a.chatID;if(await MineTm.getChatIndexedDbValueAsync(s))throw"recoverable chat already exists";let i=!1;await MineTm.setChatIndexedDbValueAsync(s,a).catch((()=>i=!0)),i?e.toastError("error saving recovered data"):MineTm.goToChatIdWithHardReload(s,!0)},getResponseBlocksWithSelection:()=>{const e=window.getSelection();if(!e?.rangeCount)return[];const t=e.getRangeAt(0),n=1===t.startContainer?.nodeType?t.startContainer:t.startContainer?.parentElement,a=1===t.endContainer?.nodeType?t.endContainer:t.endContainer?.parentElement;if(!n||!a)return[];const s=n.closest('[data-element-id="response-block"]'),i=a.closest('[data-element-id="response-block"]');if(!s||!i)return[];if(s===i)return[s];const o=[];let r=s,l=0;for(;r&&l<1e3&&(o.push(r),r!==i);){let e=r;do{e=e.nextElementSibling}while(e&&!e.matches('[data-element-id="response-block"]'));if(!e){let t=r.parentElement;for(;t&&!t.nextElementSibling;)t=t.parentElement;e=t?.nextElementSibling?.querySelector('[data-element-id="response-block"]')}if(!e)break;r=e,l++}return o},getResponseBlockWithSelection:()=>{const e=window.getSelection();if(e.rangeCount>0){let t=e.getRangeAt(0).commonAncestorContainer;for(;t&&1!==t.nodeType;)t=t.parentNode;return t.closest('[data-element-id="response-block"]')}return null},getAllIndexedDbItems:(e,t)=>new Promise(((n,a)=>{const s=indexedDB.open(e);s.onupgradeneeded=()=>{s.result.createObjectStore(t)},s.onsuccess=()=>{const e=s.result.transaction(t,"readonly").objectStore(t).getAll();e.onsuccess=()=>n(e.result),e.onerror=()=>a(e.error)},s.onerror=e=>a(e.target.error)})),_withIndexeddbStore:async(e,t)=>new Promise(((n,a)=>{const s=indexedDB.open("keyval-store");s.onerror=e=>a(e),s.onsuccess=s=>{const i=s.target.result,o=i.transaction("keyval",e),r=o.objectStore("keyval"),l=t(r);l.onerror=e=>a(e),l.onsuccess=e=>n(e),o.oncomplete=()=>i.close()}})),openModelMenuItemAsync:async t=>{(await e.waitForQs('[data-element-id="current-chat-title"] button[aria-haspopup="menu"]')).click(),(await e.waitFor((()=>e.qsaa('[id^="headlessui-menu-item"][role="menuitem"]').find((e=>e.innerText.toLowerCase()===t.toLowerCase()))))).click()}};MineTm.TmCbHelper=t;const n="\n⚙️ Fix/polish the code:\n* no unnecessary try catch\n* no unnecessary parenthesis/brackets\n* no auto-generated/obvious comments (but preserve mine)\n* prefer fat arrow notation\n* use semicolons and such\n* 2-space indents\n* favor early returns\n* favor trailing commas\n* readable variable names, favoring const (for JS)\n* inline simple returns (for JS)\n* DRY, modular code\n* simplified\n* keep all contextual instructions/comments about integrating the code OUTSIDE of the code block\n".trim();let a,s="https://www.typingmind.com/",i="https://www.typingmind.com/.*chat";const o=()=>{const t=e.qs(".mine_notes"),n=t.value.split(/\n\s*\n+/).filter((e=>e.trim()));return n.length?(e.updateReactTypableFormValue(t,n.slice(1).join("\n\n")),n[0].trim()):""},r=async t=>{if(!t)return!1;const n=await MineTm.getTaAsync();return e.updateReactTypableFormValue(n,t),(await MineTm.getSendButtonAsync()).click(),!0};MineTm.Mine.CommandBar.serveGetCommandsFnAsync((async()=>{const l=MineTm.getCurrentChatId();let c,m,u,d,h=[];if(l&&(d=await MineTm.getChatIndexedDbValueAsync(l),d)){h=d.messages||[],c=d.modelInfo.id.replace("claude-","c.").replace("3-5-","3.5.").replace("sonnet-","s.").replace("gemini-exp-","g.e.").replace(/"/g,"");const t=h.slice(-1)[0]?.createdAt;if(t){const e=Date.now()-new Date(t).getTime();u=MineTm.formatDurationLabel(e)+" ago"}const n=e.qs('[data-tooltip-content="Chat Info"]')?.innerText;n&&(m="$"+Number(n.replace("$","")).toFixed(2))}c||(c=e.qs('[data-element-id="current-chat-title"] button[aria-haspopup="menu"] .truncate')?.innerText||"");const g=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth","twentieth"];cosnt=getNumberAsWord=e=>g[e-1];let y=0;const p=h.map(((t,n)=>{if(!t.isPinned)return;const a={site:i,title:`📌 [Go to pinned] ${y<g.length?getNumberAsWord(y+1):n}`,analytics:{manualTimeSavedMs:7e3},run:async()=>e.qs(`.message-index-${n}`).scrollIntoView({behavior:"smooth"})};return y++,a})).filter(Boolean);p.length&&(p[p.length-1].hotkeySequence="p+l"),p.length>1&&(p[0].hotkeySequence="p+f");const w=(d?MineTm.getChatEngagedDurationLabel(d):"")+(u?`, ${u}`:""),T=t.isThereARecoverableChat(),f=[{site:s,title:[(new Date).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),e.qs("#__mine_info_div")?.innerText,p.length?`${p.length} 📌`:null,w,m,T?"↩️ recoverable chat":"",c].filter(Boolean).join(" • "),isStatusBar:!0},{site:s,title:"New chat",analytics:{manualTimeSavedMs:1e3},run:async()=>{window.location.href=s}},{site:i,title:"🗜️ Condense/compress chat (with fork)",showHintNotToInteract:!0,analytics:{manualTimeSavedMs:6e4},run:async(t={})=>{let n=!0;if(!0===t.triggerEvent?.shiftKey&&(n=!1),n&&!confirm("Ensure you backed it up and want to proceed?"))return;const a=await MineTm.getTaAsync();if(a.value.trim().length)return e.toastWarning("Text input must be clear");const s=(await MineTm.getCurChatIdbMetaAsync()).idbe,i=s.messages.length,o=`\nOkay, we discussed a lot. I need to start a new fresh chat bc this is slowing down my computer. BUT I don't want to lose richness of the context. I want to preserve maximum context fidelity so you remember full context when starting a new chat.\n\nThis is kind of meta, but here's the generic prompt I was going to send you. Please update this high level prompt with the purpose of compelling you to produce a good report and return it in one code block. You must produce something and do so in entirety. Do NOT generate the actual report, just update the prompt to be more effective.\n\n"""\n[System note — ${(new Date).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"numeric",minute:"2-digit",hour12:!0})}]\nLet's condense this chat. Generate a comprehensive, high-information-density report of all critical discussions, strategic frameworks, and tactical developments covered so far. Include rich details for anything explicitly called out as important, or from original summarized report. Consider the ENTIRE chat, not just recent stuff.\n\nThis report will become your only memory of our previous conversation, as everything before this message will be deleted. The system prompt will carry over automatically.\n\nGuidelines for the report:\n* Maintain mission goal/objectives\n* Maintain rich narrative detail\n* Preserve specific numbers, quotes, and key insights\n* Include all mission-critical information\n* Avoid shallow bullet-points in lists\n* Capture psychological frameworks and strategic evolution\n* Document territory developments and asset analyses\n* Include all relevant operational protocols\n\nLength should match information density needs - be as detailed as necessary to preserve all valuable intelligence.\n\nNote: do not call any plugins.\n\nGenerate the comprehensive report now.\n"""`.trim();e.updateReactTypableFormValue(a,o+"\n\nNote: this is an automated request, so do NOT ask any questions. You MUST generate the most detailed, information rich report possible without concern for length."),(await MineTm.getSendButtonAsync()).click(),await MineTm.waitForCompletedMsgCountAsync(i+2,6e4),await e.waitFor((()=>!MineTm.getIsAiResponding())),await MineTm.scrollToLastMsgAsync();const r=(await MineTm.getCurChatIdbMetaAsync()).idbe,l=(e=>{const t=e.match(/^```[\w]*\n([\s\S]*?)\n```/m);return t?t[1]:""})(r.messages.slice(-1)[0].content[0].text);if(!l.trim())return e.toastError("Unexpected AI response for phase 1");e.updateReactTypableFormValue(a,l+"\n\n---\nIMPORTANT: This is not a prompt refinement request anymore. Generate the report now!"),(await MineTm.getSendButtonAsync()).click(),await MineTm.waitForCompletedMsgCountAsync(r.messages.length+2,6e4);const c=MineTm.getCurrentChatId();await MineTm.scrollToLastMsgAsync();const m=MineTm.getAllResponseBlocks().pop();if(!await MineTm.forkResponseBlockAsync(m))return e.toastError("Error forking it");const u=MineTm.getCurrentChatId(),d=`${s.chatTitle} @done(${Date.now()})`;await MineTm.renameChatAsync(u,d);const h=await MineTm.getChatIndexedDbValueAsync(c);h.messages.splice(0,h.messages.length-2);const g=h.messages[0];if("user"!==g.role)return e.toastError("Something was wrong during validation");g.content="[Redacted — prompt requesting summarization of previous chat for continuation]",await MineTm.setChatIndexedDbValueAsync(c,h),MineTm.goToChatIdWithHardReload(c)}},{site:i,title:"Diff last code",hotkeySequence:"d+c",analytics:{manualTimeSavedMs:2e4},run:async()=>{const e=["```",'"""'],t=(t,n=e)=>{const a=t.split("\n");let s=!1,i=[],o="";for(const e of a)if(s){if(e===o)return i.join("\n").trim();i.push(e)}else for(const t of n)if(e.startsWith(t)){s=!0,o=t;break}return null},{aiText:n,useTextWithCode:a}=await(async()=>{const{idbe:t}=await MineTm.getCurChatIdbMetaAsync();return{aiText:t.messages[t.messages.length-1].content[0].text,useTextWithCode:t.messages.reverse().filter((e=>"user"===e.role)).find((t=>t.content.split("\n").filter((t=>t.startsWith(e[0])||t.startsWith(e[1]))).length>=2)).content}})(),s=t(n),i=t(a),o=encodeURIComponent(JSON.stringify({a:i,b:s}));window.open(`https://www.textcompare.org/javascript/?mine_config=${o}`)}},{site:i,title:"Go to message by timestamp",analytics:{manualTimeSavedMs:1e4},run:async()=>{const t=prompt('Enter timestamp (like "07:35")');if(!t?.trim())return;const n=t.trim().padStart(5,"0");e.qsaa('[id^="message-timestamp"]').find((e=>e.innerText===n))?.closest('[data-element-id="response-block"]').scrollIntoView({behavior:"smooth"})}},{site:i,title:"Enable javascript plugin",analytics:{manualTimeSavedMs:1e4},run:async()=>{await MineTm.setPluginsStateAsync(!0,e,{desiredMaybePluginNames:["Javascript Runner"]})}},{site:i,title:"Wipe plugin contexts",analytics:{manualTimeSavedMs:3e4},run:async()=>{const t=e.qsaa('[data-element-id="response-block"]').filter((e=>e.querySelector("details")||e.querySelector('[data-element-id="additional-actions-of-response-container"]')?.innerText.length)).reverse();for(let e=0;e<t.length;e++){const n=t[e];await MineTm.deleteRespBlockAsync(n)}}},{site:i,title:"➖ Delete last exchange",hotkeySequence:"d+l",analytics:{manualTimeSavedMs:1e4},run:async()=>await MineTm.deleteLastExchangeAsync()},{site:i,title:"➖ Delete selected messages",hotkeySequence:"d+m",showHintNotToInteract:!0,analytics:{manualTimeSavedMs:1e4},run:async(n={})=>{let a=!0;!0===n.triggerEvent?.shiftKey&&(a=!1);const s=(t.getResponseBlocksWithSelection()||[]).reverse();if(!s.length)return e.toastWarning("[noop] no selected messages found");window.getSelection().removeAllRanges();const i=s.map((e=>"* "+((e=>e.querySelector('[data-element-id="user-message"]'))(e)?"🧑🏻":"🤖")+": "+e.innerText.split("\n")[0].slice(0,50)+"...")).join("\n");if(!(a&&s.length>10)||confirm(`Proceed with deletion of ${s.length} message${1===s.length?"":"s"}?\n${i}`))for(let e=0;e<s.length;e++){const t=s[e];t.scrollIntoView(),await MineTm.deleteRespBlockAsync(t)}}},{site:i,title:"📌 Pin/Unpin this message",hotkeySequence:"p",analytics:{manualTimeSavedMs:7e3},run:async()=>{const n=t.getResponseBlockWithSelection();if(!n)return e.toast("[noop] Select some text in a msg first");await MineTm.togglePinResponseBlockAsync(n)&&await MineTm.favoriteCurrentChatAsync()}},{site:i,title:"📌 Fix/polish code",hotkeySequence:"f+c",analytics:{manualTimeSavedMs:7e3},run:async()=>{MineTm.sendMessageAsync(n,{append:!0})}},{title:"🏁 Productionize code",hotkeySequence:"p+c",analytics:{manualTimeSavedMs:48e4},run:async()=>{const t=async e=>{const t=(await MineTm.getCurChatIdbMetaAsync()).idbe.messages.length;await e(),await MineTm.waitForCompletedMsgCountAsync(t+2,3e5)};let a=0;const s=async()=>{const n='\n⚙️ Let\'s test this.\n\nWe can do some forths, whereby every time I will run your code in the browser and give you its resulting console.logs.\n\nNow, show one code block containing the code, with clear readable tests.\n\nNote: Once the execution results I give you prove your code is correct, provide just the final code (without tests), and end your response with "#LGTM" on a new line to indicate that we are done.\n'.trim();await t((async()=>MineTm.sendMessageAsync(n)));let s=0;for(;;){if(30===s)throw"taking too many iterations";const n=MineTm.getAllResponseBlocks().pop();if(s>0&&n.innerText.trim().endsWith("#LGTM"))break;await t((async()=>{(await e.waitFor((()=>n.querySelector(".exec-and-reply-btn")))).click()})),s++}a+=s};await s(),await t((async()=>MineTm.sendMessageAsync(n))),a++,await s(),a++;const i=MineTm.getAllResponseBlocks(),o=i[i.length-3].querySelector("code").innerText,r=i[i.length-1].querySelector("code").innerText;o.includes(r)?e.toastSuccess(`🏁 Productionized with ${a} iteration${1===a?"":"s"}`):e.toastWarning("🏁 Productionized. Ensure final code is same that was tested.")}},{site:i,title:"Clear context before this message",analytics:{manualTimeSavedMs:1e4},run:async()=>{const n=t.getResponseBlockWithSelection();if(!n)return e.toast("[noop] Select some text in a msg first");const a=n.closest('[class*="message-index-"]'),s=Number([...a.classList].find((e=>e.startsWith("message-index-"))).split("-")[2]),i=await MineTm.getChatIndexedDbValueAsync(l);i.messages.splice(s,0,{type:"clear-context"}),await MineTm.setChatIndexedDbValueAsync(l,i),window.location.reload()}},{site:i,title:"☁️ Copy/upload current chat to server",hotkeySequence:"u",analytics:{manualTimeSavedMs:6e4},run:async()=>await MineTm.copyCurrentChatToServerAsync()},{site:i,title:"📝 Rename current chat (reloads)",hotkeySequence:"r",analytics:{manualTimeSavedMs:1e4},run:async()=>{const e=MineTm.getCurrentChatId();if(!e)return;const t=await MineTm.getChatIndexedDbValueAsync(e),n=prompt("Rename chat to:",t.chatTitle);n?.trim()&&(await MineTm.renameChatAsync(e,n),window.location.reload())}},...[{levelEnum:"title",levelLabel:"titles"},{levelEnum:"message",levelLabel:"individual chat messages"},{levelEnum:"chat",levelLabel:"chats"}].map((({levelEnum:t,levelLabel:n})=>({site:s,title:`🔍 Search ${n}`,hotkeySequence:"title"===t?"s":"message"===t?"s+m":"",analytics:{manualTimeSavedMs:6e4},run:async(s={})=>{const i=!0===s.triggerEvent?.shiftKey;let o=prompt(`Search ${t}\n* space separated terms\n* must match all terms`,a);o?.trim()&&(a=o,await(async(e,t)=>{const n=await(async()=>{const e="keyval";return new Promise(((t,n)=>{const a=indexedDB.open("keyval-store");a.onerror=e=>n(`Database error: ${e.target.error}`),a.onsuccess=n=>{const a=n.target.result.transaction([e],"readonly").objectStore(e),s=[];a.openCursor().onsuccess=e=>{const n=e.target.result;n?(n.key.startsWith("CHAT_")&&s.push({key:n.key,value:n.value}),n.continue()):t(s)}}}))})(),a=e.toLowerCase().split(" ").filter((e=>e.length>0));return n.filter((e=>{const n=e.value;if(!n||"object"!=typeof n)return!1;if("title"===t){const e=n.chatTitle;if(!e)return!1;const t=e.toLowerCase();return a.every((e=>t.includes(e)))}const s=n.messages;if(!Array.isArray(s))return!1;if("message"===t)return s.some((e=>{if(Array.isArray(e?.content))return!1;if("user"!==e.role||"string"!=typeof e?.content)return!1;const t=e.content.toLowerCase();return a.every((e=>t.includes(e)))}));{const e=s.filter((e=>"user"===e.role&&"string"==typeof e?.content)).map((e=>e.content.toLowerCase())).join(" ");return a.every((t=>e.includes(t)))}}))})(o,t).then((t=>{if(!t.length)return e.toast("No results.");if(1===(t=t.sort(((e,t)=>t.value?.updatedAt-e.value?.updatedAt))).length||i)return void window.open(`https://typingmind.com/#chat=${t[0].value.chatID}`);const a=t.map((e=>e.value)).map((e=>`<tr><td>${e.messages.length}</td><td style="padding-left:5px;"><a href="https://typingmind.com/#chat=${e.chatID}" target="_blank">${e.chatTitle}</a></td></tr>`)),s=`<table style="margin-top:5px;width:100%;"><caption style="color:gray;margin-bottom:10px;">${a.length} result${1===a.length?"":"s"} for "${o}" in ${n}</caption><tr><th style='text-align:left;'># msgs</th><th style='text-align:left;padding-left:5px;'>Title</th></tr>`+a.join("")+"</table>";e.showFloatingMiniWindow(s,`Search ${n}`)})))}}))),...[{name:"Gemini Experimental 1206",hotkeySequence:"m+g"},{name:"Claude 3.5 Sonnet",hotkeySequence:"m+s"},{name:"DeepSeek Reasoner",hotkeySequence:"m+d"},{name:"GPT-4o Mini",hotkeySequence:"m+m"},{name:"Ollama: phi4:latest",hotkeySequence:"m+p"},{name:"O1",hotkeySequence:"m+o"}].map((({name:t,hotkeySequence:n})=>({site:s,title:`🧠 Switch to model: ${t}`,analytics:{manualTimeSavedMs:1e4},hotkeySequence:n,run:async()=>{const n=()=>e.qs('[data-element-id="current-chat-title"] button[aria-haspopup="menu"]');n().click(),(await e.waitFor((()=>e.qsaa('[data-element-id="current-chat-title"] [role="menuitem"]').find((e=>e.innerText.split("\n")[0].toLowerCase()===t.toLowerCase()))))).click(),await e.waitFor((()=>n()?.querySelector(".truncate")?.innerText===t))}}))),{site:i,title:"Retry last message",analytics:{manualTimeSavedMs:3e3},run:async()=>{const t=e.qsaa('[data-element-id="user-message"]').pop();t.scrollIntoView({behavior:"smooth"}),t.closest('[data-element-id="response-block"]').querySelector('button[data-element-id="edit-message-button"]').click()}},{site:s,title:"Toggle fullscreen",hotkeySequence:"f",analytics:{manualTimeSavedMs:3e3},run:async()=>{document.dispatchEvent(new Event("mineToggleFullscreen"))}},{site:i,title:"Scroll to last/bottom message",hotkeySequence:"l",analytics:{manualTimeSavedMs:5e3},run:async()=>await MineTm.scrollToLastMsgAsync()},{site:i,title:"Scroll to last/bottom context limit message",hotkeySequence:"l+c",analytics:{manualTimeSavedMs:5e3},run:async()=>{const t=e.qs(".firstLookbackMessage");if(!t)return e.toast("No context limited message");t?.scrollIntoView({behavior:"smooth"})}},{site:i,title:"Copy hyperlink to selected message",hotkeySequence:"h+l",analytics:{manualTimeSavedMs:5e3},run:async()=>{const n=t.getResponseBlockWithSelection();if(!n)return e.toast("[noop] Select some text in a msg first");const a="message-timestamp-",s=e.qs(`[id^="${a}"]`,n).id?.replace(a,"");if(!s)return e.toastWarning("Coudnt get message id");const i=`https://www.typingmind.com/#chat=${MineTm.getCurrentChatId()}&messageId=${s}`;e.Extension.copyText(i)}},{site:s,title:"Replace lines",hotkeySequence:"r+l",analytics:{manualTimeSavedMs:15e3},run:async()=>{const t=await MineTm.getTaAsync(),n=(t.value.substring(t.selectionStart,t.selectionEnd)||"").split("\n")[0]||prompt("Enter the exact line contents you'd like to replace","Me");if(!n?.trim())return;const a=prompt(`What would you like to replace instances of that line ("${n}") with?`,"Myself");if(!a?.trim())return;const s=t.value.split("\n").map((e=>e===n?a:e)).join("\n");e.updateReactTypableFormValue(t,s),t.focus()}},{site:i,title:"Prune everything before latest context clear",analytics:{manualTimeSavedMs:3e4},run:async()=>{const e=MineTm.getCurrentChatId(),n=await t.getChatData(e),a=(e=>{for(let t=e.length-1;t>=0;t--)if("clear-context"===e[t].type)return t;return-1})(n.messages);a<0||(n.messages.splice(0,a+1),await t.updateChatData(e,n),window.location.reload())}},...[0,3,5,10,20,25,50,75,100].map((n=>({site:i,title:`👀 Set lookback history to: ${n||"All"} msg${1===n?"":"s"}`,analytics:{manualTimeSavedMs:17e3},run:async()=>{await t.openModelMenuItemAsync("Change Chat Parameters");const a=await e.waitForQs('[data-element-id="pop-up-modal"] select');e.updateReactTypableFormValue(a,n),e.qs('[data-element-id="save-model-settings-button"]').click(),await e.waitFor((async()=>(await MineTm.getCurChatIdbMetaAsync()).contextSize===n),{recheckIntervalMs:100}),document.dispatchEvent(new CustomEvent("numMsgsInChatChanged"))}}))),{title:"Edit system prompt",hotkeySequence:"s+p",analytics:{manualTimeSavedMs:1e4},run:async()=>{const n=e.CommandBar.isCurrentUrlMatchedByPattern(i);await t.openModelMenuItemAsync(n?"Change Chat Parameters":"Manage Models");const a=await e.waitForQs('[data-element-id="new-system-instruction"]');n&&await e.sleep(100),a.scrollIntoView({behavior:"smooth"}),n&&await e.sleep(500),a.focus()}},{site:i,title:"🟢 Run continuous cache keep-alive",hotkeySequence:"k+a",analytics:{manualTimeSavedMs:3e4},run:async()=>{const t=MineTm.getCurrentChatId();if(!t)return e.toastWarning("Must be in a chat");let n=0;const a=async()=>{e.toast("Sending cache keep-alive msg..."),await e.sleep(5e3),await(async()=>{MineTm.turnOffJsScrollingInstantly();const t=e.qsaa('[data-element-id="response-block"]').length;await MineTm.sendMessageAsync("[System] Cache keepalive ping. Send a paragraph long acknowledgement statement."),await e.waitFor((()=>e.qsaa('[data-element-id="response-block"]').length>t+1)),(await e.waitFor(MineTm.getStopButton)).click(),await e.waitFor((()=>!e.qs('[data-element-id="streaming-block"]'))),await e.sleep(100),await MineTm.deleteLastExchangeAsync({enableScrolling:!1}),MineTm.turnOnJsScrollingInstantly()})(),n++};await a();let s=Date.now();for(;;){const i=MineTm.getCurrentChatId();if(i!==t)break;const o=await MineTm.getChatIndexedDbValueAsync(i);if(!o)throw"Couldn't find chat in db";const r=o.messages.reverse().find((e=>"user"===e.role)),l=r?new Date(r.createdAt).getTime():0,c=Math.max(l,s);c!==s&&(n=0);const m=Date.now()-c;if(m>=3e5)throw"[Polling] Unexpected timing";if(20===n)throw"[Polling] assuming user abandoned";m>=27e4&&(await a(),s=Date.now()),await e.sleep(3e4)}}},{site:i,title:"Prune since last call",analytics:{manualTimeSavedMs:3e4},run:async()=>{const e=MineTm.getCurrentChatId(),n=await t.getChatData(e),a=(e=>{for(let n=e.length-1;n>=0;n--)if("user"===(t=e[n]).role&&t.content.toLowerCase().startsWith("[operational message]")&&t.content.toLowerCase().includes("ready"))return n;var t;return-1})(n.messages);a<0||(n.messages.splice(a),await t.updateChatData(e,n),window.location.reload())}},{site:i,title:"➖ Wipe chat clean",analytics:{manualTimeSavedMs:2e4},run:async()=>{await(async()=>{const t=e.qs("#chat-input-textbox"),n=t.value;e.updateReactTypableFormValue(t,""),e.qsaa('[data-element-id="user-message"]')[0].closest('[data-element-id="response-block"]').querySelector('[data-element-id="edit-message-button"]').click(),await e.waitFor((()=>!!t.value)),e.updateReactTypableFormValue(t,"."),e.qsaa('[data-element-id="message-input"] [d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"]').forEach((t=>e.simulateClick(t.closest("svg")))),(await e.waitForQs('[data-element-id="send-button"]')).click(),e.updateReactTypableFormValue(t,n)})()}},{site:s,title:"🤙🏻 Go Live",hotkeySequence:"g+l",analytics:{manualTimeSavedMs:5e3},run:async(t={})=>{await e.waitFor((()=>!!MineTm.goLiveAsync)),MineTm.goLiveAsync()}},{site:s,title:"🤙🏻 Go Live (minimized)",hotkeySequence:"g+l+m",analytics:{manualTimeSavedMs:1e4},run:async(t={})=>{await e.waitFor((()=>!!MineTm.goLiveAsync)),MineTm.goLiveAsync(),await e.waitForQs("#mineToggleWidgetMinimization").then((e=>e.click()))}},{site:s,title:"📝 Notes",hotkeySequence:"n",analytics:{manualTimeSavedMs:3e3},run:async(t={})=>{(()=>{const t=e.qs(".mine_notes");t.focus(),t.value.trim()||(e.updateReactTypableFormValue(t," "),t.select())})()}},{site:s,title:"📝 Notes | next",hotkeySequence:"n+n",analytics:{manualTimeSavedMs:3e3},run:async(t={})=>{const n=o();if(!n)return e.toastWarning("Notes is empty");await r(n)}},{site:s,title:"📝 Notes | all",hotkeySequence:"n+a",analytics:{manualTimeSavedMs:3e3},run:async(t={})=>{const n=[];let a;for(;a=o();)n.push(a);if(!n.length)return e.toastWarning("Notes is empty");await r(n.join("\n\n"))}},{site:s,title:"📝 Notes | next | delete",hotkeySequence:"n+n+x",analytics:{manualTimeSavedMs:5e3},run:async(t={})=>{if(!o())return e.toastWarning("Notes are empty")}},{site:i,title:"▶️ Execute and reply last",hotkeySequence:"e",analytics:{manualTimeSavedMs:7e3},run:async(t={})=>e.qsaa(".exec-and-reply-btn").pop().click()},{site:i,title:"🗑️ Destructive exit (dexit)",hotkeySequence:"x",showHintNotToInteract:!0,analytics:{manualTimeSavedMs:8e3},run:async(n={})=>{let a=!0;const s=e.qsaa('[data-element-id="user-message"]'),i=s.map((e=>e.innerText)).join("\n").split("\n").length,o=s.length;(i<50||o<15||!0===n.triggerEvent?.shiftKey)&&(a=!1);const r=await MineTm.getChatIndexedDbValueAsync(MineTm.getCurrentChatId());if(!r)return e.toastWarning("Current chat not found in DB");const l=Date.now()-new Date(r.createdAt).getTime(),c=Math.floor(l/6e4),m=Math.floor(l%6e4/1e3);let u;u=c>0?`~${c.toLocaleString()}m ago`:`${m}s ago`;const d=r.messages.filter((e=>e.isPinned)).length;d&&(a=!0);const h=[`"${document.title}"`,`you sent ${i} lines (over ${o} msgs)`,`chat made ${u}`,d?`${d} pinned`:""].filter(Boolean).map((e=>`* ${e}`)).join("\n");a&&!confirm(`Are you sure you want to delete this chat and exit?\n\n${h}`)||await t.deleteCurrentChat()}},{site:i,title:"Export conversation transcript",analytics:{manualTimeSavedMs:1e4},run:async(t={})=>{const n=await MineTm.getChatIndexedDbValueAsync(MineTm.getCurrentChatId());let a=!1;const s=`[Title] ${n.chatTitle} (with ${n.model})\n\n`+n.messages.map((({role:e,content:t,createdAt:n})=>{let s;return Array.isArray(t)&&1===t.length&&"text"===t[0].type?s=t[0].text:(a=!0,s=JSON.stringify(t)),`[${n}] ${e}: ${s}`})).join("\n\n");a&&e.toastWarning("Transcript likely lossy, as chat data isn't simple (had attachments)."),((e,t)=>{const n=new Blob([e],{type:"text/plain"}),a=URL.createObjectURL(n),s=document.createElement("a");s.href=a,s.download=t,s.click(),URL.revokeObjectURL(a)})(s,`mine-chat-transcript-${n.id}.txt`)}},{title:"🧬 Engage CTC strategy",analytics:{manualTimeSavedMs:3e4},hotkeySequence:"t",run:async()=>{const e="[System message] Let's iteratively refine our strategy. Show our current strategy concisely in a text block (```). If drafting a message, omit wrapping quotes. Only include actionables in the block, and keep rest outside it. If there's not enough context, write 'do nothing' in it.";let t=!1;d&&(t=d.messages.slice(-1*((d.chatParams.contextLimit||1e15)-2)).find((t=>"user"===t.role&&t.content?.includes(e))));const n=t?"[System message] Show the latest strategy":e;await MineTm.sendMessageAsync(n,{append:!0})}},...p];return T&&f.push({site:s,hotkeySequence:"z",title:`↩️ Recover deleted chat: "${t.getLastDeletedChatTitle()}"`,analytics:{manualTimeSavedMs:12e4},run:async()=>await t.recoverDeletedChat()}),f}))};main().then();