// ==UserScript== // @name Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-CN Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-TW Ophel Atlas - AI 對話結構化與導覽工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:en Ophel Atlas - AI Chat Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:de Ophel Atlas - KI-Chat-Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:es Ophel Atlas - Organizador de Chats de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:fr Ophel Atlas - Organisateur de Chat IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ja Ophel Atlas - AI対話の構造化とナビゲーションツール (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ko Ophel Atlas - AI 채팅 정리 및 탐색 도구 (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:pt-BR Ophel Atlas - Organizador de Chat de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ru Ophel Atlas - Органайзер AI-чатов (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @namespace https://github.com/urzeye/ophel // @version 1.0.60 // @author urzeye // @description 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:en AI chat navigator and organizer for Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM, and Z.ai. Adds real-time outlines, Search Everywhere, conversation folders, pinning, prompt queue, prompt library, Markdown/JSON export, WebDAV sync, Zen Mode, wide/full-screen reading, scroll lock, LaTeX/table copy, tab renaming, privacy mode, notifications, reading history restore, shortcuts, prompt variables, and theme tweaks. Sound presets. Batch import. // @description:zh-CN 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:zh-TW 適用於 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 對話導覽與整理工具,提供即時大綱、Search Everywhere 全域搜尋、對話資料夾、置頂、提示詞佇列與提示詞庫、提示詞變數、Markdown/JSON 匯出、思維鏈匯出控制、WebDAV 同步、禪模式、寬螢幕/全螢幕閱讀、捲動鎖定、主題切換、LaTeX/表格複製、分頁重新命名、隱私模式、完成通知音、閱讀歷史恢復、快捷鍵與批量匯入提示詞佇列,讓長 AI 對話更易搜尋、更易導覽、更易沉澱、更易複用。 // @description:de KI-Chat-Navigator für Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM und Z.ai. Mit Echtzeit-Gliederung, Search Everywhere, Ordnern, Pinning, Prompt-Queue, Markdown/JSON-Export, WebDAV-Sync, Zen Mode, Scroll Lock, Tab-Umbenennung, Benachrichtigungen und Verlauf für lange, durchsuchbare AI-Chats. // @description:es Navegador y organizador de chats con IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM y Z.ai. Incluye esquemas en tiempo real, Search Everywhere, carpetas, fijado, cola y biblioteca de prompts, variables, exportación Markdown/JSON, sincronización WebDAV, Zen Mode, lectura amplia, bloqueo de desplazamiento, copia de LaTeX/tablas, renombrado de pestañas, privacidad, notificaciones e historial para chats largos y reutilizables. // @description:fr Navigateur et organisateur de chats IA pour Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM et Z.ai. Ajoute un plan en temps réel, Search Everywhere, dossiers, épinglage, file et bibliothèque de prompts, variables, export Markdown/JSON, sync WebDAV, Zen Mode, lecture large, verrouillage du défilement, copie LaTeX/tableaux, renommage des onglets, confidentialité, notifications et reprise de lecture pour des chats IA longs et réutilisables. // @description:ja Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai に対応する AI対話ナビゲーション整理ツール。リアルタイム目次、Search Everywhere、会話フォルダ、ピン留め、プロンプトキューとプロンプトライブラリ、プロンプト変数、Markdown/JSON エクスポート、WebDAV 同期、禅モード、ワイド/全画面読書、スクロールロック、LaTeX/表コピー、タブ名変更、プライバシーモード、完了通知、閲覧履歴復元を提供し、長い AI 対話を検索しやすく再利用しやすくします。 // @description:ko Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, QwenAI, 豆包, Kimi, ChatGLM, Z.ai를 지원하는 AI 대화 탐색·정리 도구입니다. 실시간 개요, Search Everywhere, 대화 폴더, 고정, 프롬프트 큐와 프롬프트 라이브러리, 프롬프트 변수, Markdown/JSON 내보내기, WebDAV 동기화, Zen Mode, 와이드/전체 화면 읽기, 스크롤 잠금, LaTeX/표 복사, 탭 이름 변경, 프라이버시 모드, 완료 알림, 읽기 기록 복원을 제공해 긴 AI 대화를 더 쉽게 검색하고 재사용할 수 있게 합니다. // @description:pt-BR Navegador e organizador de chats com IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM e Z.ai. Inclui outlines em tempo real, Search Everywhere, pastas, fixação, fila e biblioteca de prompts, variáveis, exportação Markdown/JSON, sincronização WebDAV, Zen Mode, leitura ampla, scroll lock, cópia de LaTeX/tabelas, renomeação de abas, privacidade, notificações e histórico para chats longos, pesquisáveis e reutilizáveis. // @description:ru Навигатор и органайзер AI-чатов для Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM и Z.ai. Добавляет структуру в реальном времени, Search Everywhere, папки, закрепление, очередь и библиотеку промптов, переменные, экспорт Markdown/JSON, синхронизацию WebDAV, Zen Mode, широкий режим, Scroll Lock, копирование LaTeX/таблиц, переименование вкладок, приватный режим, уведомления и историю чтения для длинных и переиспользуемых AI-чатов. // @license GPL-3.0-only // @icon https://raw.githubusercontent.com/urzeye/ophel/main/assets/icon.png // @homepageURL https://github.com/urzeye/ophel // @source https://github.com/urzeye/ophel.git // @supportURL https://github.com/urzeye/ophel/issues // @match https://gemini.google.com/* // @match https://business.gemini.google/* // @match https://aistudio.google.com/* // @match https://grok.com/* // @match https://chat.openai.com/* // @match https://chatgpt.com/* // @match https://claude.ai/* // @match https://www.doubao.com/* // @match https://ima.qq.com/* // @match https://chat.deepseek.com/* // @match https://www.kimi.com/* // @match https://chatglm.cn/* // @match https://chat.qwen.ai/* // @match https://www.qianwen.com/* // @match https://yuanbao.tencent.com/* // @match https://chat.z.ai/* // @require https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js // @require https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js // @require https://cdn.jsdelivr.net/npm/fuzzysort@3.1.0/fuzzysort.min.js // @require https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.js // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-markdown-vendor-ophel-1.0.60.js // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-gemini-watermark-remover-1.0.17-ophel-1.0.60.js // @resource ophelAssistantMermaidRunner https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js // @resource ophelAssistantMermaidVendor https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js // @resource ophelIcon https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-icon.193ed41c2441.png // @resource ophelKatexCss https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css // @resource ophelLocaleDe https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.de.1bc802f22f8c.json // @resource ophelLocaleEn https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.en.d7e94f34e0e5.json // @resource ophelLocaleEs https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.es.f0a51a4c4c34.json // @resource ophelLocaleFr https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.fr.824cc4e2a7cc.json // @resource ophelLocaleJa https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.ja.a8d8bf043018.json // @resource ophelLocaleKo https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.ko.eac3f63362ff.json // @resource ophelLocalePt https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.pt.f151436cfc0e.json // @resource ophelLocaleRu https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.ru.5e61c9fc2f2d.json // @resource ophelLocaleZhCN https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.zh-CN.c544151d9cbc.json // @resource ophelLocaleZhTW https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.locale.zh-TW.2835d8a38a99.json // @resource ophelMarkdownPreviewStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.markdown-preview.a99d491d0b81.css // @resource ophelNotificationBrightAlert https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-sound-bright-alert.568967a3d9f8.ogg // @resource ophelNotificationDefault https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-sound-default.15d3cda1ee80.mp3 // @resource ophelNotificationGlassPing https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-sound-glass-ping.2379b58f953e.ogg // @resource ophelNotificationSoftChime https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-sound-soft-chime.063564703b60.ogg // @resource ophelSiteIcons https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.site-icons.2c0540f606ea.json // @resource ophelStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.user.2ef2258df2f2.css // @resource ophelUserQueryMarkdownStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel.user-query-markdown.bf5242eedc63.css // @resource ophelWatermarkBg48 https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-watermark-bg-48.4afc99afe0ef.png // @resource ophelWatermarkBg96 https://cdn.jsdelivr.net/gh/urzeye/ophel@0bf1d6670e6c411ce361becdd4bcd8169c056131/userscript-assets/ophel-watermark-bg-96.3e26f2233a12.png // @tag ai // @tag chat // @tag productivity // @tag navigation // @tag outline // @tag conversation // @tag prompt // @tag export // @tag chinese // @tag multilingual // @tag cross-platform // @tag ai-assistant // @tag all-in-one // @tag 全能AI助手 // @connect * // @grant GM_addStyle // @grant GM_addValueChangeListener // @grant GM_cookie // @grant GM_deleteValue // @grant GM_getResourceText // @grant GM_getResourceURL // @grant GM_getValue // @grant GM_info // @grant GM_notification // @grant GM_removeValueChangeListener // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @grant window.focus // @run-at document-start // @noframes // ==/UserScript== (function (geminiWatermarkRemover) { 'use strict'; const d$1=new Set;const e = async e=>{d$1.has(e)||(d$1.add(e),(t=>{typeof GM_addStyle=="function"?GM_addStyle(t):(document.head||document.documentElement).appendChild(document.createElement("style")).append(t);})(e));}; const n=function(){const e="undefined"!=typeof document&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}(),r={},o=function(e,t,o){let i=Promise.resolve();if(t&&t.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=e(t.map(e=>{if((e=function(e){return "/"+e}(e))in r)return;r[e]=true;const t=e.endsWith(".css"),o=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${o}`))return;const i=document.createElement("link");return i.rel=t?"stylesheet":n,t||(i.as="script"),i.crossOrigin="",i.href=e,a&&i.setAttribute("nonce",a),document.head.appendChild(i),t?new Promise((t,n)=>{i.addEventListener("load",t),i.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${e}`)));}):void 0}));}function a(e){const t=new Event("vite:preloadError",{cancelable:true});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return i.then(t=>{for(const e of t||[])"rejected"===e.status&&a(e.reason);return e().catch(a)})};const i=function(){const e=globalThis.React;if(!e||"function"!=typeof e.createElement)throw new Error("[Ophel] React CDN runtime is missing");return e}(),a=i.Children,s=i.Component,l=i.Fragment,c=i.Profiler,d=i.PureComponent,u=i.StrictMode,h=i.Suspense,g=i.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,p=i.act,m=i.cloneElement,f=i.createContext,b=i.createElement,y=i.createFactory,v=i.createRef,x=i.forwardRef,w=i.isValidElement,S=i.lazy,C=i.memo,k=i.startTransition,T=i.unstable_act,E=i.useCallback,A=i.useContext,M=i.useDebugValue,I=i.useDeferredValue,L=i.useEffect,N=i.useId,R=i.useImperativeHandle,D=i.useInsertionEffect,P=i.useLayoutEffect,q=i.useMemo,B=i.useReducer,$=i.useRef,_=i.useState,O=i.useSyncExternalStore,z=i.useTransition,F=i.version,U=Object.freeze(Object.defineProperty({__proto__:null,Children:a,Component:s,Fragment:l,Profiler:c,PureComponent:d,StrictMode:u,Suspense:h,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:g,act:p,cloneElement:m,createContext:f,createElement:b,createFactory:y,createRef:v,default:i,forwardRef:x,isValidElement:w,lazy:S,memo:C,startTransition:k,unstable_act:T,useCallback:E,useContext:A,useDebugValue:M,useDeferredValue:I,useEffect:L,useId:N,useImperativeHandle:R,useInsertionEffect:D,useLayoutEffect:P,useMemo:q,useReducer:B,useRef:$,useState:_,useSyncExternalStore:O,useTransition:z,version:F},Symbol.toStringTag,{value:"Module"}));const H=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createRoot)throw new Error("[Ophel] ReactDOM client CDN runtime is missing");return e}();H.createRoot,H.hydrateRoot;const W=["zh-CN","zh-TW","en","ja","ko","fr","de","ru","es","pt"],j={styles:{metaName:"ophelStyles",fileName:"ophel.user.css"},markdownPreviewStyles:{metaName:"ophelMarkdownPreviewStyles",fileName:"ophel.markdown-preview.css"},userQueryMarkdownStyles:{metaName:"ophelUserQueryMarkdownStyles",fileName:"ophel.user-query-markdown.css"},icon:{metaName:"ophelIcon",fileName:"ophel-icon.png"},siteIcons:{metaName:"ophelSiteIcons",fileName:"ophel.site-icons.json"},notificationDefault:{metaName:"ophelNotificationDefault",fileName:"ophel-sound-default.mp3"},notificationSoftChime:{metaName:"ophelNotificationSoftChime",fileName:"ophel-sound-soft-chime.ogg"},notificationGlassPing:{metaName:"ophelNotificationGlassPing",fileName:"ophel-sound-glass-ping.ogg"},notificationBrightAlert:{metaName:"ophelNotificationBrightAlert",fileName:"ophel-sound-bright-alert.ogg"},watermarkBg48:{metaName:"ophelWatermarkBg48",fileName:"ophel-watermark-bg-48.png"},watermarkBg96:{metaName:"ophelWatermarkBg96",fileName:"ophel-watermark-bg-96.png"},assistantMermaidRunner:{metaName:"ophelAssistantMermaidRunner",fileName:"ophel-assistant-mermaid-runner.js",externalUrl:"https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js"},assistantMermaidVendor:{metaName:"ophelAssistantMermaidVendor",fileName:"ophel-assistant-mermaid-vendor.js",externalUrl:"https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js"}},G={"zh-CN":{metaName:"ophelLocaleZhCN",fileName:"ophel.locale.zh-CN.json"},"zh-TW":{metaName:"ophelLocaleZhTW",fileName:"ophel.locale.zh-TW.json"},en:{metaName:"ophelLocaleEn",fileName:"ophel.locale.en.json"},ja:{metaName:"ophelLocaleJa",fileName:"ophel.locale.ja.json"},ko:{metaName:"ophelLocaleKo",fileName:"ophel.locale.ko.json"},fr:{metaName:"ophelLocaleFr",fileName:"ophel.locale.fr.json"},de:{metaName:"ophelLocaleDe",fileName:"ophel.locale.de.json"},ru:{metaName:"ophelLocaleRu",fileName:"ophel.locale.ru.json"},es:{metaName:"ophelLocaleEs",fileName:"ophel.locale.es.json"},pt:{metaName:"ophelLocalePt",fileName:"ophel.locale.pt.json"}};const V="OPHEL_GEMINI_CANVAS_CODE_REQUEST",Q="OPHEL_GEMINI_CANVAS_CODE_RESPONSE";function K(e){if(e.__ophelGeminiCanvasMainInitialized)return;e.__ophelGeminiCanvasMainInitialized=true,e.document.documentElement.setAttribute("data-ophel-gemini-canvas-main","1");e.addEventListener("message",t=>{if(t.origin&&t.origin!==e.location.origin)return;const n=t.data;if(n?.type!==V)return;const r="string"==typeof n.requestId?n.requestId:"";if(!r)return;const o=(t=>{const n=e.monaco?.editor?.getModels?.();if(!Array.isArray(n)||0===n.length)return "";const r=n.find(e=>{const n=e;return t&&n.uri?.toString?.()===t})||(1===n.length?n[0]:null);return "function"!=typeof r?.getValue?"":r.getValue()})("string"==typeof n.editorUri?n.editorUri:"");e.postMessage({type:Q,requestId:r,code:o},"*");});}const Z="en",Y={},X=new Set,J=()=>{if("undefined"==typeof navigator)return Z;const e=navigator.language;return e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":Z};let ee=J();function te(e){return e&&"auto"!==e?(t=e,Object.prototype.hasOwnProperty.call(G,t)?e:e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":Z):J();var t;}function ne(e){const t=Y[e];if(t)return t;const n=G[e].metaName;try{const t=GM_getResourceText(n);if(!t)return Y[e]={},Y[e];const r=JSON.parse(t);return Y[e]=r,r}catch(r){return console.warn(`[Ophel] Failed to load userscript locale resource: ${e}`,r),Y[e]={},Y[e]}}function re(e){const t=te(e);return ee=t,ne(Z),t!==Z&&ne(t),t}function oe(){return function(e){if(e)try{const t="string"==typeof e?JSON.parse(e):e,n="object"==typeof t&&null!==t?t.state?.settings?.language:void 0;return "string"==typeof n?n:void 0}catch(t){return void console.warn("[Ophel] Failed to parse persisted settings language:",t)}}(GM_getValue("settings"))||"auto"}function ie(e){return X.add(e),()=>{X.delete(e);}}function ae(e){const t=te(e),n=ee;ee=t,ne(Z),ne(t),n!==t&&X.forEach(e=>{try{e();}catch(t){console.warn("[Ophel] Userscript i18n listener failed:",t);}});}function se(e){return te(e)}function le(e,t){const n=ne(ee),r=ee===Z?n:ne(Z);let o=n[e]||r[e]||e;return t&&Object.keys(t).forEach(e=>{o=o.replace(new RegExp(`{${e}}`,"g"),t[e]);}),o}function ce(e){return Array.from(new Set(W.map(t=>ne(t)[e]).filter(e=>"string"==typeof e&&e.trim().length>0)))}function de(){return ee}const ue=Object.freeze(Object.defineProperty({__proto__:null,getAllLocalizedTexts:ce,getCurrentLang:de,getEffectiveLanguage:se,getInitialUserscriptLanguage:oe,primeUserscriptLocales:re,setLanguage:ae,subscribeI18nChanges:ie,t:le},Symbol.toStringTag,{value:"Module"}));const he='@font-face {\n font-family: "Inter";\n src: local("Inter"), local("InterVariable");\n font-style: normal;\n font-weight: 100 900;\n unicode-range:\n U+0000-02FF, U+0304, U+0308, U+0329, U+0370-03FF, U+1D00-1DBF, U+1E00-1EFF,\n U+1F00-1FFF, U+0400-052F, U+1C80-1C88, U+2116, U+2DE0-2DFF, U+A640-A69F,\n U+1EA0-1EF9, U+20AB, U+2000-206F, U+20A0-20C0, U+20AC, U+2113, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+2C60-2C7F, U+A720-A7FF, U+FEFF, U+FFFD;\n}',ge=["gh-platform-macos","gh-platform-windows","gh-platform-other"],pe='"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif',me=`var(--gh-font-family, ${pe})`;function fe(){if("undefined"==typeof navigator)return "other";const e=navigator.userAgentData?.platform,t=[navigator.platform,e,navigator.userAgent].filter(Boolean).join(" ").toLowerCase();return /mac|iphone|ipad|ipod/.test(t)?"macos":/win/.test(t)?"windows":"other"}function be(e=fe()){return "macos"===e?'"Inter", "Hiragino Sans SC", "PingFang SC", "Apple SD Gothic Neo", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif':pe}function ye(e){e.classList.remove(...ge),e.classList.add(function(e=fe()){return `gh-platform-${e}`}());}be();const ve=new Set,xe=new Set(Object.values(j).filter(({fileName:e})=>/\.(mp3|ogg)$/i.test(e)).map(({metaName:e})=>e)),we=Object.fromEntries(Object.values(j).map(({metaName:e,fileName:t})=>{const n=t.split(".").pop()?.toLowerCase();return [e,"css"===n?"text/css":"png"===n?"image/png":"mp3"===n?"audio/mpeg":"ogg"===n?"audio/ogg":"application/octet-stream"]}));function Se(e,t){if(!t.startsWith("data:")||!xe.has(e))return t;try{const n=t.indexOf(",");if(-1===n)return t;const r=t.slice(5,n),o=t.slice(n+1),i=r.split(";").filter(Boolean),a=i[0]||"",s=we[e]||a||"application/octet-stream",l=i.includes("base64")?function(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r"string"==typeof e&&e.length>0)),window.__OPHEL_USERSCRIPT_ASSET_URLS__={icon:Te(j.icon.metaName)||"",watermarkBg48:Te(j.watermarkBg48.metaName)||"",watermarkBg96:Te(j.watermarkBg96.metaName)||"",assistantMermaidRunner:Te(j.assistantMermaidRunner.metaName)||"",assistantMermaidVendor:Te(j.assistantMermaidVendor.metaName)||""},re(oe()),"undefined"==typeof chrome||!chrome.storage){const e=["settings","prompts","folders","tags","readingHistory","claudeSessionKeys","conversations"];window.chrome={storage:{local:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},sync:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},onChanged:{addListener:()=>{},removeListener:()=>{}}},runtime:{getManifest:()=>({version:"1.0.0"}),getURL:e=>e,sendMessage:()=>Promise.resolve({})}};}const Me=window.chrome?.storage;Me&&!Me.onChanged&&(Me.onChanged={addListener:()=>{},removeListener:()=>{}});const Ie=window.chrome?.runtime;if(Ie&&!Ie.onMessage&&(Ie.onMessage={addListener:()=>{},removeListener:()=>{}}),window.top!==window.self)throw new Error("Ophel: Running in iframe, skipping initialization");if(window.ophelUserscriptInitialized)throw new Error("Ophel: Already initialized");async function Le(){const[{getAdapter:e},{App:t},{initNetworkMonitor:n},{initGeminiTitleGuard:r}]=await Promise.all([o(()=>Promise.resolve().then(()=>sm),void 0),o(()=>Promise.resolve().then(()=>Tx),void 0),o(()=>Promise.resolve().then(()=>ew),void 0),o(()=>Promise.resolve().then(()=>lw),void 0)]);r();const a=e();if(!a)return;a.afterPropertiesSet({});let s=null,l=null;const c=()=>{s?.disconnect(),s=null,null!==l&&(window.clearInterval(l),l=null);};await(async()=>{try{const e=document.createElement("div");e.id="ophel-userscript-root",ye(e),e.style.cssText="all: initial; display: block; position: fixed; inset: 0; width: 0; height: 0; overflow: visible; pointer-events: none; z-index: 2147483647;";const n=()=>document.body||document.documentElement,r=async()=>{n()||await new Promise(e=>{const t=new MutationObserver(()=>{n()&&(t.disconnect(),e());});t.observe(document.documentElement,{childList:!0,subtree:!0});});},o=()=>{const t=n();t&&e.parentElement!==t&&t.appendChild(e);};await r(),o(),[250,600,1200,2e3,3500,5e3].forEach(e=>setTimeout(o,e)),s=new MutationObserver(()=>{e.isConnected||o();}),s.observe(document.documentElement,{childList:!0,subtree:!0}),l=window.setInterval(()=>{e.isConnected||o();},2e3),window.location.hostname.includes("chatglm.cn")&&e.classList.add("gh-site-chatglm");const a=e.attachShadow({mode:"open"}),c=document.createElement("style");let d="";try{d=localStorage.getItem("ophel_us_theme_cache")||"";}catch{}c.textContent=(Ee||"")+(d?"\n"+d:""),a.appendChild(c);const u=document.createElement("div");u.id="ophel-app-container",a.appendChild(u);const h=()=>{const[,e]=i.useState(0);return i.useEffect(()=>ie(()=>{e(e=>e+1);}),[]),i.createElement(t)};H.createRoot(u).render(i.createElement(h));}catch(RS){throw c(),RS}})();const{useSettingsStore:d,getSettingsState:u}=await o(async()=>{const{useSettingsStore:e,getSettingsState:t}=await Promise.resolve().then(()=>Ri);return {useSettingsStore:e,getSettingsState:t}},void 0),{useConversationsStore:h}=await o(async()=>{const{useConversationsStore:e}=await Promise.resolve().then(()=>um);return {useConversationsStore:e}},void 0),{useFoldersStore:g}=await o(async()=>{const{useFoldersStore:e}=await Promise.resolve().then(()=>bm);return {useFoldersStore:e}},void 0),{useTagsStore:p}=await o(async()=>{const{useTagsStore:e}=await Promise.resolve().then(()=>wm);return {useTagsStore:e}},void 0),{usePromptsStore:m}=await o(async()=>{const{usePromptsStore:e}=await Promise.resolve().then(()=>$m);return {usePromptsStore:e}},void 0),{useClaudeSessionKeysStore:f}=await o(async()=>{const{useClaudeSessionKeysStore:e}=await Promise.resolve().then(()=>Av);return {useClaudeSessionKeysStore:e}},void 0),{useReadingHistoryStore:b}=await o(async()=>{const{useReadingHistoryStore:e}=await Promise.resolve().then(()=>Wy);return {useReadingHistoryStore:e}},void 0),y=e=>{if(e.getState()._hasHydrated)return Promise.resolve(true);return new Promise(t=>{let n,r=false;const o=e=>{r||(r=true,window.clearTimeout(n),t(e));},i=e.subscribe(e=>{e._hasHydrated&&(i(),o(true));});n=window.setTimeout(()=>{i(),e.setState({_hasHydrated:true}),o(false);},5e3);})};await Promise.all([y(d),y(h),y(g),y(p),y(m),y(f),y(b)]);const v=u(),x=a.getSiteId(),{initCoreModules:w,subscribeModuleUpdates:S,initUrlChangeObserver:C}=await o(async()=>{const{initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}=await Promise.resolve().then(()=>NS);return {initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}},void 0),k={adapter:a,settings:v,siteId:x};await w(k),n(),S(k),C(k),window.addEventListener("unload",c),window.addEventListener("unload",Ce);}window.ophelUserscriptInitialized=true,function(){const e="undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window;if(e.__ophelScrollLockInitialized)return;e.__ophelScrollLockInitialized=true;const t=e.Element,n=e.HTMLElement,r={scrollIntoView:t.prototype.scrollIntoView,scrollTo:e.scrollTo.bind(e),scrollTopDescriptor:Object.getOwnPropertyDescriptor(t.prototype,"scrollTop")||Object.getOwnPropertyDescriptor(n.prototype,"scrollTop")};function o(){const e=document.documentElement.dataset.ophelPositionLock;if(void 0!==e){const t=Number(e);if(!isNaN(t))return t}return null}function i(){document.documentElement.dataset.ophelPositionLockLastBlock=String(Date.now());}if(e.__ophelOriginalApis=r,e.__ophelScrollLockEnabled=false,t.prototype.scrollIntoView=function(t){const n=t&&"object"==typeof t&&t.__bypassLock;if(null!==o()){if(n)return r.scrollIntoView.call(this,t);let e=this.parentElement;for(;e;){if(e.scrollWidth>e.clientWidth&&e.scrollHeight<=e.clientHeight+10)return r.scrollIntoView.call(this,t);e=e.parentElement;}return void i()}if(!e.__ophelScrollLockEnabled)return r.scrollIntoView.call(this,t);let a=this.parentElement;for(;a;){if(a.scrollWidth>a.clientWidth&&a.scrollHeight<=a.clientHeight+10)return r.scrollIntoView.call(this,t);a=a.parentElement;}return n?r.scrollIntoView.call(this,t):void 0},e.scrollTo=function(t,n){if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return r.scrollTo.apply(e,arguments);let a;return a="object"==typeof t&&null!==t?t.top:n,"number"==typeof a&&a>e.scrollY+50?void 0:r.scrollTo.apply(e,arguments)},r.scrollTopDescriptor){const n=r.scrollTopDescriptor;Object.defineProperty(t.prototype,"scrollTop",{get:function(){return n.get?n.get.call(this):0},set:function(t){if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return void(n.set&&n.set.call(this,t));const r=o();if(null!==r)return Math.abs(t-r)>10?(i(),void(n.set&&n.set.call(this,r))):void(n.set&&n.set.call(this,t));if(!e.__ophelScrollLockEnabled)return void(n.set&&n.set.call(this,t));t>(n.get?n.get.call(this):0)+50||n.set&&n.set.call(this,t);},configurable:true});}const a=t.prototype.scrollTo;t.prototype.scrollTo=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return a.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return a.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return a.apply(this,arguments);let r;"object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n);const s=this.scrollTop||0;return "number"==typeof r&&r>s+50?void 0:a.apply(this,arguments)};const s=t.prototype.scroll;t.prototype.scroll=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return s.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return s.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return s.apply(this,arguments);let r;"object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n);const a=this.scrollTop||0;return "number"==typeof r&&r>a+50?void 0:s.apply(this,arguments)};const l=t.prototype.scrollBy;if(t.prototype.scrollBy=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return l.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return l.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return l.apply(this,arguments);let r;return "object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n),"number"==typeof r&&r>50?void 0:l.apply(this,arguments)},e.addEventListener("message",t=>{"OPHEL_SCROLL_LOCK_TOGGLE"===t.data?.type&&(e.__ophelScrollLockEnabled=t.data.enabled);}),"function"==typeof t.prototype.scrollIntoViewIfNeeded){const e=t.prototype.scrollIntoViewIfNeeded;t.prototype.scrollIntoViewIfNeeded=function(t){if(null===o())return e.call(this,t);i();};}}(),"gemini.google.com"===location.hostname&&K("undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Le();},{once:true}):Le();const Ne=i.Fragment,Re=(e,t,n)=>i.createElement(e,function(e,t){return void 0===t?e??{}:{...e??{},key:t}}(t,n)),De=Re,Pe=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Re("circle",{cx:"12",cy:"12",r:"4"}), Re("line",{x1:"12",y1:"2",x2:"12",y2:"4"}), Re("line",{x1:"12",y1:"20",x2:"12",y2:"22"}), Re("line",{x1:"4.93",y1:"4.93",x2:"6.34",y2:"6.34"}), Re("line",{x1:"17.66",y1:"17.66",x2:"19.07",y2:"19.07"}), Re("line",{x1:"2",y1:"12",x2:"4",y2:"12"}), Re("line",{x1:"20",y1:"12",x2:"22",y2:"12"}), Re("line",{x1:"4.93",y1:"19.07",x2:"6.34",y2:"17.66"}), Re("line",{x1:"17.66",y1:"6.34",x2:"19.07",y2:"4.93"})]}),qe=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:Re("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),Be=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:Re("path",{fill:t,fillRule:"evenodd",clipRule:"evenodd",d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"})}),$e=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Re("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),_e=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("circle",{cx:"12",cy:"5",r:"2.5"}), Re("line",{x1:"12",y1:"7.5",x2:"12",y2:"22"}), Re("line",{x1:"7",y1:"10",x2:"17",y2:"10"}), Re("path",{d:"M4 14C4 19 8 22 12 22C16 22 20 19 20 14"}), Re("path",{d:"M1.5 16.5L4 14L6.5 16.5"}), Re("path",{d:"M17.5 16.5L20 14L22.5 16.5"})]}),Oe=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 1024 1024",fill:"none",className:n,children:[ Re("path",{d:"M768 208H595.349a223.478 223.478 0 0 1-147.964-56 223.473 223.473 0 0 0-147.964-56H256C149.961 96 64 181.961 64 288v448c0 106.038 85.961 192 192 192h512c106.039 0 192-85.962 192-192V400c0-106.039-85.961-192-192-192z m112 528c0 61.757-50.243 112-112 112H256c-61.757 0-112-50.243-112-112V288c0-61.758 50.243-112 112-112h43.421a143.372 143.372 0 0 1 94.995 35.953A303.263 303.263 0 0 0 595.349 288H768c61.757 0 112 50.242 112 112v336z",fill:t}), Re("path",{d:"M690.783 471.577l-82.681-91.826c-7.899-8.772-18.796-13.236-29.739-13.235a39.868 39.868 0 0 0-26.752 10.274c-16.417 14.782-17.743 40.074-2.961 56.491L576.31 464H360c-22.092 0-40 17.908-40 40 0 22.091 17.908 40 40 40h304c22.092 0 40-17.909 40-40 0-8.139-2.461-15.688-6.636-22.005-1.66-3.69-3.728-7.25-6.581-10.418zM664 606.516H360c-22.092 0-40 17.908-40 40 0 8.139 2.461 15.688 6.636 22.005 1.66 3.69 3.729 7.25 6.581 10.418l82.681 91.826c7.899 8.772 18.796 13.235 29.739 13.235a39.863 39.863 0 0 0 26.752-10.274c16.417-14.782 17.743-40.074 2.961-56.491l-27.659-30.719H664c22.092 0 40-17.908 40-40s-17.908-40-40-40z",fill:t})]}),ze=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Re("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), Re("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),Fe=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Re("circle",{cx:"12",cy:"12",r:"3"}), Re("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),Ue=({size:e=18,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:[ Re("path",{d:"M512 960c-234.394624 0-425.10336-190.708736-425.10336-425.10336S277.605376 109.79328 512 109.79328c116.878336 0 225.772544 46.432256 306.69312 130.737152 9.644032 10.027008 44.068864 47.517696 52.627456 58.438656 11.113472 14.242816 8.558592 34.807808-5.684224 45.92128-14.306304 11.113472-34.87232 8.49408-45.92128-5.684224-7.791616-10.027008-39.406592-44.196864-48.156672-53.32992C703.028224 214.472704 610.8672 175.194112 512 175.194112c-198.308864 0-359.702528 161.393664-359.702528 359.702528S313.691136 894.599168 512 894.599168 871.702528 733.205504 871.702528 534.89664c0-18.074624 14.625792-32.700416 32.700416-32.700416s32.700416 14.625792 32.700416 32.700416c0 234.394624-190.708736 425.10336-425.10336 425.10336z"}), Re("path",{d:"M838.683648 371.395584H623.194112c-18.074624 0-32.700416-14.625792-32.700416-32.700416s14.625792-32.700416 32.700416-32.700416h209.294336V96.700416c0-18.074624 14.625792-32.700416 32.700416-32.700416s32.700416 14.625792 32.700416 32.700416v215.489536c-0.001024 32.635904-26.569728 59.205632-59.205632 59.205632z"})]}),He=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:Re("line",{x1:"5",y1:"12",x2:"19",y2:"12"})}),We=({size:e=18,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:[ Re("path",{d:"M192 192m32 0l0 0q32 0 32 32l0 640q0 32-32 32l0 0q-32 0-32-32l0-640q0-32 32-32Z",fill:t}), Re("path",{d:"M192 832m32 0l256 0q32 0 32 32l0 0q0 32-32 32l-256 0q-32 0-32-32l0 0q0-32 32-32Z",fill:t}), Re("path",{d:"M192 512m32 0l256 0q32 0 32 32l0 0q0 32-32 32l-256 0q-32 0-32-32l0 0q0-32 32-32Z",fill:t}), Re("path",{d:"M448 192m64 0l320 0q64 0 64 64l0 0q0 64-64 64l-320 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Re("path",{d:"M640 480m64 0l128 0q64 0 64 64l0 0q0 64-64 64l-128 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Re("path",{d:"M640 768m64 0l128 0q64 0 64 64l0 0q0 64-64 64l-128 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Re("path",{d:"M224 224m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0Z",fill:t})]}),je=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}), Re("polyline",{points:"14 2 14 8 20 8"}), Re("line",{x1:"16",y1:"13",x2:"8",y2:"13"}), Re("line",{x1:"16",y1:"17",x2:"8",y2:"17"}), Re("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),Ge=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:Re("path",{fill:t,stroke:t,strokeWidth:"0.3",d:"M19.75 6.5a.75.75 0 0 1-.75-.75V5h-.75a.75.75 0 0 1 0-1.5H19v-.75a.75.75 0 0 1 1.5 0v.75h.75a.75.75 0 0 1 0 1.5h-.75v.75a.75.75 0 0 1-.75.75M8.799 3.728a.34.34 0 0 1 .1-.18c.046-.04.082-.048.102-.048s.056.007.102.049a.34.34 0 0 1 .1.178a6.57 6.57 0 0 0 1.767 3.304a6.55 6.55 0 0 0 3.303 1.767c.07.014.135.053.178.1c.042.046.049.082.049.102s-.007.056-.049.102a.34.34 0 0 1-.178.1a6.56 6.56 0 0 0-3.303 1.768a6.56 6.56 0 0 0-1.766 3.302a.34.34 0 0 1-.101.18c-.046.04-.082.048-.102.048s-.056-.007-.102-.049a.34.34 0 0 1-.1-.178a6.57 6.57 0 0 0-1.767-3.304a6.55 6.55 0 0 0-3.303-1.767a.34.34 0 0 1-.179-.1c-.04-.047-.048-.082-.049-.102c0-.02.008-.056.049-.101a.34.34 0 0 1 .18-.102a6.56 6.56 0 0 0 3.302-1.766a6.56 6.56 0 0 0 1.767-3.303M9 2c-.883 0-1.52.695-1.67 1.422A5.06 5.06 0 0 1 5.97 5.97a5.06 5.06 0 0 1-2.546 1.36c-.728.15-1.424.788-1.423 1.673c.002.882.697 1.517 1.423 1.668a5.05 5.05 0 0 1 2.547 1.358c.87.871 1.22 1.88 1.359 2.549C7.48 15.305 8.118 16 9 16c.885 0 1.521-.695 1.672-1.423a5.06 5.06 0 0 1 1.358-2.546a5.06 5.06 0 0 1 2.548-1.36c.727-.15 1.422-.787 1.422-1.67c0-.885-.695-1.521-1.423-1.672a5.05 5.05 0 0 1-2.546-1.359a5.06 5.06 0 0 1-1.359-2.548C10.521 2.695 9.885 2 9.002 2M9.5 16.954v1.796c0 .966.784 1.75 1.75 1.75h7.5a1.75 1.75 0 0 0 1.75-1.75v-7.5a1.75 1.75 0 0 0-1.75-1.75h-1.796a2.7 2.7 0 0 0-.15-1.5h1.946A3.25 3.25 0 0 1 22 11.25v7.5A3.25 3.25 0 0 1 18.75 22h-7.5A3.25 3.25 0 0 1 8 18.75v-1.946a2.7 2.7 0 0 0 1.5.15M12 13.75a.75.75 0 0 1 .75-.75h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1-.75-.75m.75 2.25a.75.75 0 0 0 0 1.5h3.5a.75.75 0 0 0 0-1.5zm-10 3a.75.75 0 0 0 0 1.5h.75v.75a.75.75 0 0 0 1.5 0v-.75h.75a.75.75 0 0 0 0-1.5H5v-.75a.75.75 0 0 0-1.5 0V19z"})}),Ve=({size:e=16,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ Re("path",{fill:t,d:"M128 256m42.666667 0l682.666666 0q42.666667 0 42.666667 42.666667l0 0q0 42.666667-42.666667 42.666666l-682.666666 0q-42.666667 0-42.666667-42.666666l0 0q0-42.666667 42.666667-42.666667Z"}), Re("path",{fill:t,d:"M599.168 757.248a42.666667 42.666667 0 0 1-6.656-22.869333V461.653333a42.666667 42.666667 0 0 1 64.981333-36.352l218.154667 134.058667a42.666667 42.666667 0 0 1 0.554667 72.362667l-218.154667 138.666666a42.666667 42.666667 0 0 1-58.88-13.141333z m78.677333-100.522667l95.018667-60.373333-95.018667-58.368v118.741333z"}), Re("path",{fill:t,d:"M128 469.333333m42.666667 0l256 0q42.666667 0 42.666666 42.666667l0 0q0 42.666667-42.666666 42.666667l-256 0q-42.666667 0-42.666667-42.666667l0 0q0-42.666667 42.666667-42.666667Z"}), Re("path",{fill:t,d:"M128 682.666667m42.666667 0l256 0q42.666667 0 42.666666 42.666666l0 0q0 42.666667-42.666666 42.666667l-256 0q-42.666667 0-42.666667-42.666667l0 0q0-42.666667 42.666667-42.666666Z"})]}),Qe=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0},children:[ Re("path",{d:"M6.5 17.5H6a3.5 3.5 0 0 1-3.5-3.5V7a3.5 3.5 0 0 1 3.5-3.5h12A3.5 3.5 0 0 1 21.5 7v7a3.5 3.5 0 0 1-3.5 3.5h-5.2L6.5 20.5v-3Z"}), Re("circle",{cx:"8",cy:"10.5",r:"1",fill:t,stroke:"none"}), Re("circle",{cx:"12",cy:"10.5",r:"1",fill:t,stroke:"none"}), Re("circle",{cx:"16",cy:"10.5",r:"1",fill:t,stroke:"none"})]}),Ke=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), Re("polyline",{points:"7 10 12 15 17 10"}), Re("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),Ze=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), Re("polyline",{points:"17 8 12 3 7 8"}), Re("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),Ye="M12 3v12",Xe="m7 10 5 5 5-5",Je="M5 21h14",et=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M4 6h6"}), Re("path",{d:"M4 10h9"}), Re("path",{d:"M4 14h9"}), Re("path",{d:"M4 18h6"}), Re("path",{d:"M18 5v14"}), Re("path",{d:"m15.5 7.5 2.5-2.5 2.5 2.5"}), Re("path",{d:"m15.5 16.5 2.5 2.5 2.5-2.5"})]}),tt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M4 6h9"}), Re("path",{d:"M4 12h9"}), Re("path",{d:"M4 18h9"}), Re("path",{d:"M18 3v6"}), Re("path",{d:"m15.5 6.5 2.5 2.5 2.5-2.5"}), Re("path",{d:"M18 21v-6"}), Re("path",{d:"m15.5 17.5 2.5-2.5 2.5 2.5"})]}),nt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"})}),rt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Re("polyline",{points:"5 12 12 5 19 12"})]}),ot=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), Re("polyline",{points:"19 12 12 19 5 12"})]}),it=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73v.18a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.1a2 2 0 0 1-1-1.72v-.51a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"})}),at=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M13.5 10.5L21 3 M16 3h5v5 M2 21h5 M12 21a9 9 0 0 0 9-9 9 9 0 0 0-9-9 9 9 0 0 0-9 9c0 4.97 4.03 9 9 9z"})}),st=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:Re("path",{d:"M553.79358 660.032655v-121.03257a19.643494 19.643494 0 0 1 9.872902-17.085748l370.924415-213.827617a40.054312 40.054312 0 0 0 0-69.468399L553.844735 19.521745 529.597297 5.402984a40.105467 40.105467 0 0 0-60.158201 34.734199v600.916992a19.796959 19.796959 0 0 1-18.97848 19.745804c-217.561928 8.952113-430.673377 66.501412-430.673377 180.832687 0 125.227275 254.649254 181.80463 491.752367 181.80463s491.956986-56.577355 491.956986-181.90694c0-117.656345-225.900182-175.103334-449.805322-181.446546z m30.38603-525.412312l211.014096 121.3395a19.745804 19.745804 0 0 1 0 34.22265l-211.014096 121.953359a19.745804 19.745804 0 0 1-29.669861-17.085747V151.706091a19.745804 19.745804 0 0 1 29.669861-17.085748z m232.601478 765.226636a1211.655731 1211.655731 0 0 1-610.12488 0c-83.68947-25.986706-101.95178-53.149975-101.951781-58.316623s18.313466-32.278762 101.951781-58.418933a992.405691 992.405691 0 0 1 242.320915-37.598876 19.745804 19.745804 0 0 1 20.461973 19.694649v79.187836a19.745804 19.745804 0 0 0 19.796959 19.745804h44.658256a19.796959 19.796959 0 0 0 19.796959-19.745804v-79.187836a19.745804 19.745804 0 0 1 20.461973-19.745803 992.405691 992.405691 0 0 1 242.37207 37.65003c83.638315 26.037861 101.696006 52.99651 101.696006 58.316623s-18.057691 32.381072-101.696006 58.418933z",fill:t})}),lt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96L12 12.01l8.73-5.05 M12 22.08V12"})}),ct=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:[ Re("path",{d:"M511.5 119.3l366.8 168.8c-0.4 14.7-1.6 35-4.5 60.2-5.9 52.4-20.6 137.5-56.7 245.4-23 68.8-86.3 145.9-183.1 222.9-48.8 38.9-95.1 68.8-122.2 85.3-26.6-16.9-71.8-47.1-119.7-86.2-95.6-78-159-155.6-183.5-224.5-38.5-108.6-53.1-192.1-58.5-243.1-2.6-24.8-3.4-44.5-3.5-58.7l364.9-170.1m-0.2-55.1L98 257s-16 126.8 63.6 351c67.6 190.3 349.8 352.3 349.8 352.3s289.2-159 353.2-350.6C938.3 388.8 928 256 928 256L511.3 64.2z",fill:t}), Re("path",{d:"M511.3 273.3c25.4 0 46.1 20.7 46.1 46.1s-20.7 46.1-46.1 46.1c-25.4 0-46.1-20.7-46.1-46.1s20.7-46.1 46.1-46.1m0-50c-53.1 0-96.1 43-96.1 96.1s43 96.1 96.1 96.1 96.1-43 96.1-96.1-43-96.1-96.1-96.1z",fill:t}), Re("path",{d:"M486.3 383.8h50v384h-50z",fill:t}), Re("path",{d:"M513 599h94.5v50H513zM513 717h94.5v50H513z",fill:t})]}),dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z M12 16v-4 M12 8h.01"})}),ut=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"})}),ht=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2z M2 12h20 M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})}),gt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"})}),pt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z M9 12l2 2 4-4"})}),mt=({size:e=20,color:t="currentColor",className:n="",style:r,filled:o=false})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:Re("polygon",{points:"512,64 625,357 968,364 695,571 794,901 512,704 230,901 329,571 56,364 399,357",fill:o?t:"none",stroke:t,strokeWidth:96,strokeLinejoin:"round"})}),ft=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}),bt=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},fill:t,children:[ Re("path",{d:"M518.3 459c-3.2-4.1-9.4-4.1-12.6 0l-112 141.7c-4.1 5.2-0.4 12.9 6.3 12.9h73.9V856c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V613.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 459z"}), Re("path",{d:"M811.4 366.7C765.6 245.9 648.9 160 512.2 160S258.8 245.8 213 366.6C127.3 389.1 64 467.2 64 560c0 110.5 89.5 200 199.9 200H304c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8h-40.1c-33.7 0-65.4-13.4-89-37.7-23.5-24.2-36-56.8-34.9-90.6 0.9-26.4 9.9-51.2 26.2-72.1 16.7-21.3 40.1-36.8 66.1-43.7l37.9-9.9 13.9-36.6c8.6-22.8 20.6-44.1 35.7-63.4 14.9-19.2 32.6-35.9 52.4-49.9 41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.2c19.9 14 37.5 30.8 52.4 49.9 15.1 19.3 27.1 40.7 35.7 63.4l13.8 36.5 37.8 10C846.1 454.5 884 503.8 884 560c0 33.1-12.9 64.3-36.3 87.7-23.4 23.4-54.5 36.3-87.6 36.3H720c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h40.1C870.5 760 960 670.5 960 560c0-92.7-63.1-170.7-148.6-193.3z"})]}),yt=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ Re("circle",{cx:12,cy:12,r:10}), Re("line",{x1:12,y1:16,x2:12,y2:12}), Re("line",{x1:12,y1:8,x2:12.01,y2:8})]}),vt=({size:e=16,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:[ Re("rect",{x:"100",y:"282",width:"824",height:"80",rx:"40",fill:t}), Re("rect",{x:"100",y:"472",width:"824",height:"80",rx:"40",fill:t}), Re("rect",{x:"100",y:"662",width:"824",height:"80",rx:"40",fill:t})]}),xt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"})}),wt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"})}),St=({size:e=18,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"})}),Ct=({size:e=18,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"})}),kt=({size:e=20,className:t=""})=>De("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ Re("path",{d:"M15 3h6v6"}), Re("path",{d:"M9 21H3v-6"}), Re("path",{d:"M21 3l-7 7"}), Re("path",{d:"M3 21l7-7"})]}),Tt=({size:e=20,className:t=""})=>De("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ Re("path",{d:"M4 14h6v6"}), Re("path",{d:"M20 10h-6V4"}), Re("path",{d:"M14 10l7-7"}), Re("path",{d:"M3 21l7-7"})]}),Et=({size:e=20,className:t=""})=>Re("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,children:Re("path",{d:"M606.72 304.64V235.52H346.624l51.712-16.384c-7.168-24.576-25.088-62.464-40.448-90.112l-76.288 22.016c13.824 26.624 27.136 59.904 33.792 84.48H62.976v69.12h94.208C189.44 388.608 230.4 460.8 284.16 519.68c-61.952 48.128-139.264 82.432-232.448 105.984 14.336 15.872 35.328 49.152 43.008 66.048 96.256-27.648 176.128-67.072 242.176-120.832 62.464 52.736 139.776 92.16 233.472 117.248 10.752-19.968 31.744-50.688 47.616-66.048-89.088-20.992-164.352-55.808-225.792-103.424 52.224-57.856 92.672-128 122.88-214.016h91.648z m-171.52 0a474.624 474.624 0 0 1-97.28 165.376c-46.08-47.104-81.92-102.4-107.52-165.376h204.8z m237.568 622.08h-90.112l141.824-414.72h104.448l142.848 414.72h-93.184l-31.232-106.496h-143.872l-30.72 106.496z m100.864-351.744c-11.264 45.568-24.576 92.672-37.888 135.68l-12.8 45.568h105.472l-13.312-45.568c-13.824-43.008-28.672-90.624-41.472-135.68z",fill:"currentColor"})}),At=({size:e=20,className:t="",style:n})=>Re("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,style:n,children:Re("path",{d:"M512 136.83c-206.88 0-375.17 168.31-375.17 375.17S305.12 887.17 512 887.17 887.17 718.86 887.17 512 718.88 136.83 512 136.83z m265.73 202h-85.94c-12.32-44.9-29.26-84.4-49.88-116.19a319.22 319.22 0 0 1 135.82 116.2zM656.3 512a625.41 625.41 0 0 1-10.54 115.44H378.24a637.45 637.45 0 0 1 0-230.88h267.52A625.41 625.41 0 0 1 656.3 512zM512 829.45c-44.2 0-91.56-54.92-119.52-144.29h239C603.56 774.53 556.2 829.45 512 829.45zM392.48 338.84c28-89.37 75.32-144.29 119.52-144.29s91.56 54.92 119.52 144.29z m-10.39-116.19c-20.62 31.79-37.56 71.29-49.88 116.19h-85.94a319.22 319.22 0 0 1 135.82-116.19z m-165.5 173.91h102.85a709.08 709.08 0 0 0 0 230.88H216.59a313.34 313.34 0 0 1 0-230.88z m29.68 288.6h85.94c12.32 44.9 29.26 84.4 49.88 116.19a319.22 319.22 0 0 1-135.82-116.19z m395.64 116.19c20.62-31.79 37.56-71.29 49.88-116.19h85.94a319.22 319.22 0 0 1-135.82 116.19z m165.5-173.91H704.56a709.08 709.08 0 0 0 0-230.88h102.85a313.34 313.34 0 0 1 0 230.88z",fill:"currentColor"})}),Mt=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ Re("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",ry:"2"}), Re("line",{x1:"6",y1:"8",x2:"6",y2:"8"}), Re("line",{x1:"10",y1:"8",x2:"10",y2:"8"}), Re("line",{x1:"14",y1:"8",x2:"14",y2:"8"}), Re("line",{x1:"18",y1:"8",x2:"18",y2:"8"}), Re("line",{x1:"6",y1:"12",x2:"6",y2:"12"}), Re("line",{x1:"10",y1:"12",x2:"10",y2:"12"}), Re("line",{x1:"14",y1:"12",x2:"14",y2:"12"}), Re("line",{x1:"18",y1:"12",x2:"18",y2:"12"}), Re("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]}),It=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}), Re("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),Lt=({size:e=18,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:[ Re("path",{d:"M632.96 954.88H201.813333a132.906667 132.906667 0 0 1-132.693333-132.693333V391.04a132.906667 132.906667 0 0 1 132.693333-132.906667h431.146667a132.906667 132.906667 0 0 1 132.906667 132.906667v431.146667a132.906667 132.906667 0 0 1-132.906667 132.693333zM201.813333 352a39.04 39.04 0 0 0-38.826666 39.04v431.146667a39.04 39.04 0 0 0 38.826666 38.826666h431.146667a39.04 39.04 0 0 0 39.04-38.826666V391.04a39.04 39.04 0 0 0-39.04-39.04z",fill:t}), Re("path",{d:"M907.946667 846.293333a47.146667 47.146667 0 0 1-46.933334-46.933333V234.666667A71.04 71.04 0 0 0 789.333333 162.986667H224.64a46.933333 46.933333 0 1 1 0-93.866667H789.333333A164.906667 164.906667 0 0 1 954.88 234.666667v565.333333a46.933333 46.933333 0 0 1-46.933333 46.293333z",fill:t}), Re("path",{d:"M531.626667 561.066667h-241.066667a46.933333 46.933333 0 0 1 0-93.866667h241.066667a46.933333 46.933333 0 0 1 0 93.866667zM531.626667 731.733333h-241.066667a46.933333 46.933333 0 0 1 0-93.866666h241.066667a46.933333 46.933333 0 0 1 0 93.866666z",fill:t})]}),Nt=({size:e=16,className:t="",...n})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",strokeLinecap:"round",strokeLinejoin:"round",className:`more-horizontal-icon ${t}`,style:{display:"block",width:e,height:e},...n,children:[ Re("circle",{cx:"12",cy:"12",r:"1.5",className:"dot dot-2"}), Re("circle",{cx:"19",cy:"12",r:"1.5",className:"dot dot-3"}), Re("circle",{cx:"5",cy:"12",r:"1.5",className:"dot dot-1"}), Re("style",{children:"\n .more-horizontal-icon .dot {\n transform-box: fill-box;\n transform-origin: center;\n animation: dot-jump 3s infinite;\n }\n .more-horizontal-icon .dot-1 {\n animation-delay: 0s;\n }\n .more-horizontal-icon .dot-2 {\n animation-delay: 0.1s;\n }\n .more-horizontal-icon .dot-3 {\n animation-delay: 0.2s;\n }\n @keyframes dot-jump {\n 0%, 90%, 100% { transform: translateY(0); }\n 5% { transform: translateY(-3px); }\n 10% { transform: translateY(0); }\n }\n "})]}),Rt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M18 15l-6-6-6 6"})}),Dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Re("path",{d:"M6 9l6 6 6-6"})}),Pt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Re("path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}), Re("path",{d:"m14.5 9-5 5"}), Re("path",{d:"m9.5 9 5 5"})]}),qt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Re("path",{d:"M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z"}), Re("path",{d:"M7 7h.01"})]}),Bt=({size:e=24,className:t,color:n="currentColor"})=>De("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ Re("circle",{cx:"12",cy:"12",r:"10"}), Re("circle",{cx:"12",cy:"12",r:"4"}), Re("line",{x1:"21.17",x2:"12",y1:"8",y2:"8"}), Re("line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14"}), Re("line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14"})]}),$t=({size:e=24,className:t,color:n="currentColor"})=>Re("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:Re("path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"})}),_t=({size:e=24,className:t,color:n="currentColor"})=>De("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ Re("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}), Re("polyline",{points:"14 2 14 8 20 8"}), Re("path",{d:"m9 15 2 2 4-4"})]}),Ot=({size:e=24,className:t})=>De("svg",{width:e,height:e,viewBox:"0 0 48 48",className:t,children:[ Re("path",{fill:"#1e88e5",d:"M40.69,35.42c-9.15,11.88-21.41,8.8-26.23,6.1 c-7.35-4.11-12.5-13.68-9.44-23.25c0.9-2.82,2.27-5.23,3.98-7.23c1.67,0.13,3.65,0.13,6-0.04c14-1,18,11,17,14 c-0.51,1.53-2.32,2.02-3.97,2.13c0.16-0.22,0.36-0.54,0.64-1.02c0.87-1.54,0.98-4.49-1.73-6.27c-2.61-1.7-5.43-0.65-6.88,1.28 c-1.45,1.92-0.88,4.81-0.37,6.09c2.2,5.52,6.26,6.95,9.02,7.78c2.76,0.83,6.86,0.71,9.05-0.19c2.18-0.91,2.8-1.43,3.22-0.97 C41.41,34.29,41.11,34.82,40.69,35.42z"}), Re("path",{fill:"#0d47a1",d:"M40.732,35.42c-3.48,4.52-7.41,6.87-11.21,7.91 c-0.03,0.01-0.06,0.01-0.08,0.02c-2.2,0.42-3.95,0.08-5.85-0.29c-3.09-0.6-7.35-4.01-8.38-10.18c-0.88-5.31,1.63-9.81,5.59-12.54 c-0.26,0.24-0.49,0.5-0.7,0.78c-1.45,1.92-0.88,4.81-0.37,6.09c2.2,5.52,6.26,6.95,9.02,7.78c2.76,0.83,6.86,0.71,9.05-0.19 c2.18-0.91,2.8-1.43,3.22-0.97C41.452,34.29,41.152,34.82,40.732,35.42z"}), Re("path",{fill:"#00e5ff",d:"M26.94,4.25c0.02,0.26,0.03,0.54,0.03,0.81c0,3.78-1.75,7.14-4.48,9.32 c-1.02-0.52-2.21-0.94-3.65-1.22c-4.07-0.78-10.63,1.1-13.3,5.77c-0.88,1.53-1.25,3.1-1.41,4.55c0.04-1.71,0.33-3.46,0.89-5.21 C8.31,8.01,17.86,3.05,26.94,4.25z"}), Re("path",{fill:"#00e676",d:"M41.4,27.89c-2.76,2.78-6.27,2.86-8.67,2.73 c-2.41-0.12-3.59-0.82-4.69-1.5c-1.11-0.69-0.48-1.37-0.37-1.52c0.11-0.15,0.38-0.41,1-1.49c0.29-0.51,0.5-1.18,0.54-1.91 c4.62-3.43,7.96-8.49,9.16-14.34c2.92,2.95,4.3,6.21,4.79,7.61C44.04,19.99,44.71,24.56,41.4,27.89z"}), Re("path",{fill:"#1de9b6",d:"M38.37,9.85v0.01c-1.2,5.85-4.54,10.91-9.16,14.34c0.03-0.42,0-0.87-0.1-1.32 c0-0.02-0.01-0.04-0.01-0.05c-0.25-1.47-0.99-3.33-2.22-4.77c-1.22-1.44-2.52-2.73-4.39-3.68c2.73-2.18,4.48-5.54,4.48-9.32 c0-0.27-0.01-0.55-0.03-0.81c0.4,0.05,0.79,0.11,1.19,0.19C32.74,5.33,36.04,7.49,38.37,9.85z"})]}),zt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), Re("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),Ft=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("polyline",{points:"3 6 5 6 21 6"}), Re("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}), Re("line",{x1:"10",y1:"11",x2:"10",y2:"17"}), Re("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]}),Ut=({size:e=18,color:t="currentColor",className:n="",filled:r=false,style:o})=>Re("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...o},children: Re("path",r?{d:"M307.370667 416l54.314666 54.314667-77.056 77.056a4.266667 4.266667 0 0 0 2.986667 7.296h158.421333l1.962667 1.962666V844.8c0 4.693333 3.84 8.533333 8.533333 8.533333h110.933334a8.533333 8.533333 0 0 0 8.533333-8.533333v-160.170667l76.8 76.8V844.8a85.333333 85.333333 0 0 1-85.333333 85.333333h-110.933334a85.333333 85.333333 0 0 1-85.333333-85.333333v-213.333333H287.616c-72.192 0-108.373333-87.296-57.301333-138.368L307.370667 416z m432.64 215.381333L663.296 554.666667h73.088a4.266667 4.266667 0 0 0 2.986667-7.253334l-221.354667-221.354666a8.533333 8.533333 0 0 0-12.032 0l-35.669333 35.626666L416 307.413333l35.669333-35.669333a85.333333 85.333333 0 0 1 120.661334 0l221.354666 221.354667c50.218667 50.176 16.085333 135.424-53.674666 138.282666zM207.530667 207.530667a38.4 38.4 0 0 1 54.272 0l554.666666 554.666666a38.4 38.4 0 1 1-54.272 54.272l-554.666666-554.666666a38.4 38.4 0 0 1 0-54.272zM217.6 128a38.4 38.4 0 0 1 38.4-38.4h512a38.4 38.4 0 1 1 0 76.8H256a38.4 38.4 0 0 1-38.4-38.4z",fill:t}:{d:"M576 554.666667h160.341333a4.266667 4.266667 0 0 0 3.029334-7.253334l-2.986667-3.072-48.341333-48.298666-18.176-18.176-151.850667-151.850667a8.533333 8.533333 0 0 0-12.032 0L354.133333 477.866667l-18.176 18.176L287.573333 544.426667l-2.986666 2.986666a4.266667 4.266667 0 0 0 2.986666 7.253334H448v290.133333c0 4.736 3.84 8.533333 8.533333 8.533333h110.933334a8.533333 8.533333 0 0 0 8.533333-8.533333V554.666667z m160.384 76.8H652.8v213.333333a85.333333 85.333333 0 0 1-85.333333 85.333333h-110.933334a85.333333 85.333333 0 0 1-85.333333-85.333333v-213.333333H287.616c-72.192 0-108.373333-87.338667-57.301333-138.410667l221.354666-221.312a85.333333 85.333333 0 0 1 120.661334 0l221.354666 221.312c51.072 51.072 14.933333 138.410667-57.301333 138.410667zM256 89.6a38.4 38.4 0 0 0 0 76.8h512a38.4 38.4 0 1 0 0-76.8H256z",fill:t})}),Ht=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}), Re("circle",{cx:"12",cy:"12",r:"3"})]}),Wt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M2 8a10.645 10.645 0 0 0 20 0"}), Re("path",{d:"m4 15 1.726-2.05"}), Re("path",{d:"m9 18 .722-3.25"}), Re("path",{d:"m15 18-.722-3.25"}), Re("path",{d:"m20 15-1.726-2.05"})]}),jt=({size:e=16,className:t="",...n})=>Re("svg",{"aria-hidden":"true",focusable:"false",viewBox:"0 0 16 16",width:e,height:e,fill:"currentColor",display:"inline-block",overflow:"visible",className:t,style:{display:"block",width:e,height:e,verticalAlign:"middle"},...n,children:Re("path",{d:"M14.85 3c.63 0 1.15.52 1.14 1.15v7.7c0 .63-.51 1.15-1.15 1.15H1.15C.52 13 0 12.48 0 11.84V4.15C0 3.52.52 3 1.15 3ZM9 11V5H7L5.5 7 4 5H2v6h2V8l1.5 1.92L7 8v3Zm2.99.5L14.5 8H13V5h-2v3H9.5Z"})}),Gt=({size:e=16,className:t="",...n})=>De("svg",{viewBox:"0 0 1024 1024",xmlns:"http://www.w3.org/2000/svg",width:e,height:e,fill:"currentColor",className:t,style:{display:"block",width:e,height:e},...n,children:[ Re("path",{d:"M1008 464h-72c-4.4 0-8-3.6-8-8V314.5c0-17-6.7-33.3-18.7-45.3L658.7 18.7C646.7 6.7 630.5 0 613.5 0H144c-26.5 0-48 21.5-48 48v408c0 4.4-3.6 8-8 8H16c-8.8 0-16 7.2-16 16v400c0 8.8 7.2 16 16 16h80c0 35.3 14.3 67.3 37.5 90.5 23.2 23.2 55.2 37.5 90.5 37.5h656c26.5 0 48-21.5 48-48v-64c0-8.8 7.2-16 16-16h64c8.8 0 16-7.2 16-16V480c0-8.8-7.2-16-16-16zM704 154.5l69.5 69.5H708c-2.2 0-4-1.8-4-4v-65.5zM160 72c0-4.4 3.6-8 8-8h408c35.3 0 64 28.7 64 64v144c0 8.8 7.2 16 16 16h144c35.3 0 64 28.7 64 64v104c0 4.4-3.6 8-8 8H168c-4.4 0-8-3.6-8-8V72z m492.3 603.5c0 32.5-9.5 58.9-28.4 79.1-18.9 20.3-43.7 30.4-74.3 30.4-29.9 0-54.2-9.8-72.9-29.4-18.5-19.6-27.9-44.9-27.9-75.8 0-32.7 9.5-59.3 28.6-79.8s44.3-30.8 75.6-30.8c29.8 0 53.8 9.9 72 29.8 18.2 19.8 27.3 45.4 27.3 76.5z m-365.9 53.3c16.9 13.9 35.9 20.9 57.3 20.9 12.1 0 21.2-2.1 27.3-6.3 6.1-4.2 9.2-9.5 9.2-16.1 0-5.7-2.4-11-7.3-16s-17.6-11.9-38.4-20.5c-32.6-13.8-48.9-33.9-48.9-60.4 0-19.4 7.4-34.5 22.2-45.2s34.3-16.1 58.7-16.1c20.4 0 37.5 2.7 51.3 7.9v41.8c-14-9.5-30.4-14.3-49.2-14.3-11 0-19.7 2-26.3 6-6.6 4-9.8 9.4-9.8 16.1 0 5.4 2.2 10.4 6.7 14.9s15.6 10.7 33.3 18.4c20.7 8.9 35 18.3 42.8 28.2 7.8 9.9 11.7 21.6 11.7 35.3 0 20-7.1 35.3-21.3 45.8S371.3 785 345.2 785c-23.9 0-43.5-3.9-58.7-11.6l-0.1-44.6c0.1 0 0 0 0 0z m-139.6 8.9c7.7 5.8 16.5 8.8 26.4 8.8 21.4 0 32.1-16.2 32.1-48.6V572.7h44.5v126.8h-0.1c0 27.6-6.4 48.7-19.1 63.5-12.7 14.6-30.9 22-54.6 22-10.5 0-20.3-1.8-29.2-5.4v-41.9zM864 952c0 4.4-3.6 8-8 8H224c-35.3 0-64-28.7-64-64h696c4.4 0 8 3.6 8 8v48z m9.2-170.6h-45.5l-88.4-135c-4.6-7-7.9-12.7-10-17h-0.7c0.8 7.2 1.2 18.3 1.2 33.3v118.7h-42.2V572.7h48.5l85.1 131.2c5.7 8.7 9.1 14.2 10.4 16.6h0.7c-0.9-5-1.3-14.6-1.3-28.8v-119h42.2v208.7zM286.5 728.8s-0.1 0 0 0z"}), Re("path",{d:"M605.8 678.2c0 20.9-4.8 37.5-14.5 49.8s-23.3 18.5-40.7 18.5c-17.1 0-30.5-6.4-40.3-19.3-9.8-12.9-14.7-29.5-14.7-49.8 0-20.6 5-37.3 15-50.2 10.1-12.9 23.8-19.4 41.2-19.4 17.2 0 30.5 6.3 39.9 18.9 9.4 12.6 14.1 29.8 14.1 51.5z"})]}),Vt=({size:e=16,className:t="",...n})=>De("svg",{viewBox:"0 0 1024 1024",xmlns:"http://www.w3.org/2000/svg",width:e,height:e,fill:"currentColor",className:t,style:{display:"block",width:e,height:e},...n,children:[ Re("path",{d:"M899.072 403.968h-14.336V275.456c0-8.192-3.072-16.384-9.216-22.016L624.128 11.776c-6.144-5.632-13.312-8.704-21.504-8.704h-465.92C89.088 3.072 50.688 41.472 50.688 89.088v845.824c0 47.616 38.4 86.016 86.016 86.016h662.528c22.528 0 45.056-9.216 60.928-25.6 16.384-16.384 25.088-37.888 24.576-60.416v-60.416h14.848c22.528 0 43.52-8.704 59.392-25.088 15.872-15.872 24.576-36.864 24.064-58.88V487.936c0-46.08-37.888-83.968-83.968-83.968z m-292.864-324.096l185.856 178.176-185.856-4.608V79.872z m217.088 855.04c0.512 6.656-2.048 12.8-6.656 17.408-4.608 4.608-10.752 7.168-17.408 7.168H136.704c-13.312 0-24.576-11.264-24.576-24.576V89.088c0-13.312 11.264-24.576 24.576-24.576h408.064v219.136c0 16.896 12.8 30.208 29.696 30.72l248.832 6.144v83.456h-527.36c-46.08 0-83.968 37.888-83.968 83.968v302.592c0 46.08 37.888 83.968 83.968 83.968h527.36v60.416z m98.304-144.384c0 6.144-2.048 11.776-6.144 15.872s-9.728 6.656-15.872 6.656H295.936c-12.288 0-22.528-10.24-22.528-22.528V487.936c0-12.288 10.24-22.528 22.528-22.528h603.136c12.288 0 22.528 10.24 22.528 22.528v302.592z"}), Re("path",{d:"M309.76 600.064h59.392v132.608h58.88v-132.608h59.904v-43.52H309.76zM696.832 556.544h-64l-32.768 54.272-33.792-54.272H501.76l59.392 83.968L495.616 732.16h66.048l37.376-56.32 37.376 56.32h66.048l-64.512-90.624zM707.072 556.544v43.52h59.904v132.608h58.88v-132.608H885.76v-43.52h-178.176z"})]}),Qt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("circle",{cx:"11",cy:"11",r:"8"}), Re("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),Kt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("circle",{cx:"12",cy:"12",r:"10"}), Re("polyline",{points:"12 6 12 12 16 14"})]}),Zt=({size:e=18,color:t,className:n="",style:r})=>{const o=`sparkle-gradient-${i.useId().replace(/:/g,"")}`,a=!t||"brand"===t,s=a?`url(#${o})`:t,l="number"==typeof e?1.25*e:e; return De("svg",{viewBox:"0 0 1024 1024",width:l,height:l,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,overflow:"visible",transform:"translateY(1px)",filter:a?"drop-shadow(0px 2px 6px rgba(34, 211, 238, 0.4))":"none",...r},children:[ Re("defs",{children:a&&De("linearGradient",{id:o,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[ Re("stop",{offset:"0%",stopColor:"#22d3ee"}), Re("stop",{offset:"100%",stopColor:"#6366f1"})]})}), De("g",{style:{fill:s,stroke:s,strokeWidth:12,strokeLinejoin:"round",strokeLinecap:"round"},children:[ Re("path",{d:"M380.77 475.76c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.2 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.986 4.986 0 0 1-4.84 3.79z m-41.69-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7L380.66 367l-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM513.43 939.45h-0.04c-8-0.02-14.96-5.46-16.93-13.21L415.8 607.36l-319.06-98.3a17.495 17.495 0 0 1-12.32-17.7c0.45-8.03 6.32-14.72 14.22-16.22l191.92-36.28c9.5-1.8 18.65 4.45 20.45 13.95s-4.45 18.65-13.94 20.45l-122.51 23.16 260.96 80.4c5.84 1.8 10.31 6.51 11.81 12.43l66.26 261.97 46.87-181.85c2.41-9.36 11.95-14.99 21.31-12.58s14.99 11.95 12.58 21.31l-63.97 248.22c-2 7.73-8.97 13.13-16.95 13.13zM826.61 540.39c-7.44 0-14.35-4.79-16.69-12.27-2.89-9.22 2.24-19.04 11.46-21.94l31.03-9.73-261.1-49.94a17.496 17.496 0 0 1-13.69-12.96l-65.07-260.98-47.06 190.3c-2.32 9.38-11.8 15.11-21.19 12.79-9.38-2.32-15.11-11.81-12.79-21.19l63.97-258.72a17.497 17.497 0 0 1 16.97-13.3h0.02c8.03 0 15.04 5.47 16.98 13.27l79.41 318.52 318.43 60.91a17.5 17.5 0 0 1 14.18 16.18c0.46 8.01-4.58 15.3-12.23 17.7l-97.39 30.55c-1.74 0.55-3.5 0.81-5.24 0.81zM842.91 908.24c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.21 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.975 4.975 0 0 1-4.84 3.79z m-41.68-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7l-7.56-30.33-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM874.6 220.76c-1.85 0-3.73-0.3-5.58-0.93l-67.48-23.04c-4.37-1.49-7.9-4.6-9.94-8.76-2.04-4.16-2.34-8.85-0.85-13.22l23.05-67.47c3.09-9.03 12.95-13.87 21.98-10.79l67.48 23.04c4.37 1.49 7.9 4.6 9.94 8.76 2.04 4.16 2.34 8.85 0.85 13.22L891 209.04c-2.45 7.19-9.2 11.72-16.4 11.72z m0.88-19.86z m0 0z m-64.94-22.17l62.4 21.31 21.31-62.39-62.4-21.31-21.31 62.39zM147.92 229.91a9.91 9.91 0 0 1-3.34-0.58 9.982 9.982 0 0 1-6.49-7.61l-17.36-93.88c-0.65-3.51 0.62-7.11 3.34-9.43 2.72-2.32 6.47-3.01 9.83-1.82l89.99 31.91a9.982 9.982 0 0 1 6.49 7.61c0.65 3.51-0.62 7.11-3.34 9.43l-72.63 61.97a9.951 9.951 0 0 1-6.49 2.4z m-4.38-88.67l11.06 59.82 46.28-39.49-57.34-20.33zM170.16 908.56c-29.21 0-52.97-23.76-52.97-52.96s23.76-52.96 52.97-52.96 52.97 23.76 52.97 52.96-23.76 52.96-52.97 52.96z m0-85.92c-18.18 0-32.97 14.79-32.97 32.96 0 18.18 14.79 32.96 32.97 32.96s32.97-14.79 32.97-32.96c0-18.18-14.79-32.96-32.97-32.96z"}), Re("path",{d:"M720.52 570.25c-4.83 0-9.57-2.33-12.46-6.63-4.62-6.88-2.79-16.2 4.08-20.82 59.91-40.27 107.08-81.41 136.42-118.97 27-34.56 36.95-64.05 28.02-83.02-9.9-21.04-43.7-32.21-95.17-31.46-55 0.81-127.81 15.68-205.01 41.87-7.84 2.66-16.36-1.54-19.02-9.38-2.66-7.84 1.54-16.36 9.38-19.02 81.25-27.57 155.32-42.6 214.21-43.46 81.98-1.2 112 25.81 122.76 48.69 9.9 21.04 12.46 57.94-31.53 114.26-31.26 40.03-80.82 83.39-143.33 125.4a15.005 15.005 0 0 1-8.35 2.54zM206.58 758.85c-19.37 0-36.69-1.63-51.82-4.9-32.77-7.08-54.56-21.65-64.74-43.3-12.12-25.77-6.13-57.5 17.79-94.3 20.83-32.03 55.73-67.88 100.95-103.69 6.49-5.14 15.93-4.05 21.07 2.45 5.14 6.49 4.05 15.93-2.45 21.07-42.7 33.81-75.35 67.19-94.42 96.53-12.3 18.91-25.02 45.57-15.8 65.17 12.64 26.87 65.89 37.07 142.46 27.28 84.33-10.77 188.04-43.64 292.05-92.54 9.16-4.31 18.36-8.76 27.37-13.24 7.42-3.69 16.42-0.67 20.11 6.74 3.69 7.42 0.67 16.42-6.74 20.11-9.2 4.58-18.61 9.14-27.97 13.54-106.76 50.2-213.66 83.99-301.01 95.15-20.52 2.62-39.51 3.93-56.85 3.93z"}), Re("path",{d:"M598.89 616.45a16.71 16.71 0 1 0 33.42 0 16.71 16.71 0 1 0-33.42 0Z"}), Re("path",{d:"M664.77 608.33h-18.14c-4.2 0-7.64-3.44-7.64-7.64v-18.14c0-4.2 3.44-7.64 7.64-7.64h18.14c4.2 0 7.64 3.44 7.64 7.64v18.14c0 4.2-3.44 7.64-7.64 7.64zM690.73 554.4l-12.28 21.27c-0.98 1.7 0.25 3.83 2.21 3.83h24.57c1.97 0 3.2-2.13 2.21-3.83l-12.28-21.27c-0.99-1.7-3.45-1.7-4.43 0z"})]})]})},Yt=({size:e=15,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0},children:Re("path",{d:"M674.432 64c20.224 0 37.888 18.944 37.888 40.576v297.792h232.192c7.616 0 15.168 2.752 20.16 8.128a41.92 41.92 0 0 1 10.176 56.832l-295.36 473.728a34.688 34.688 0 0 1-30.272 18.944c-20.16 0-37.824-18.944-37.824-40.576V621.632h-232.32a27.584 27.584 0 0 1-20.16-8.128 41.92 41.92 0 0 1-10.048-56.832l295.296-473.728A34.688 34.688 0 0 1 674.432 64zM44.8 140.8h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z m0 640h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 0 1 0-89.6z m0-320h166.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z",fill:t})}),Xt=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:Re("polyline",{points:"20 6 9 17 4 12"})}),Jt=({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Re("line",{x1:"2",y1:"2",x2:"2",y2:"22"}), Re("rect",{x:"6",y:"4",width:"16",height:"16",rx:"2"}), Re("polyline",{points:"15 9 11 12 15 15"})]}),en=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",width:e,height:e},children:Re("path",{d:"M701.312 579.84l132.288-238.08 83.712 12.032a32 32 0 0 0 27.2-54.272L703.168 58.176 698.88 54.528a32 32 0 0 0-50.048 30.848l12.16 83.84-237.632 131.712-7.808-3.648c-79.04-35.328-151.168-26.624-209.984 32.192l-3.712 4.48a32 32 0 0 0 3.712 40.768l145.664 145.664-239.552 325.888-2.944 4.672c-14.912 28.608 19.84 60.672 47.744 40l324.992-240.32 146.496 146.496a32 32 0 0 0 45.248 0c58.176-58.24 66.176-124.736 32.32-207.36l-4.224-9.92z m24.704-408.256l105.152 105.152-10.24-1.408a32 32 0 0 0-32.576 16.128L637.44 563.072a32 32 0 0 0-0.768 29.632l5.888 12.416c21.824 48.768 24.96 84.608 8.512 116.224l-3.136 5.248-140.672-140.672-4.48-3.776a32 32 0 0 0-37.12 0.64l-177.088 130.88 130.56-177.472 3.008-4.992a32 32 0 0 0-6.144-36.608L276.032 354.688l6.208-3.456c35.584-18.24 76.544-13.312 126.464 14.08a32 32 0 0 0 30.848-0.064l271.872-150.72a32 32 0 0 0 16.128-32.576l-1.536-10.368z",fill:t})}),tn=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"})}),nn=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Re("path",{d:"M1018.912 381.792c-32.992-174.304-207.328-195.968-207.328-195.968H30.816c-25.76 0-28.96 34.048-28.96 34.048s-3.488 312.48-0.928 504.416c7.008 103.424 110.336 114.016 110.336 114.016s352.736-0.992 510.56-2.08c104.032-18.176 114.464-109.472 113.408-159.328 185.696 10.24 316.672-120.8 283.68-295.072z m-471.968 149.792c-53.152 61.984-171.136 169.632-171.136 169.632s-5.152 5.088-13.216 0.992c-3.232-2.432-4.608-3.84-4.608-3.84-18.912-18.816-143.712-130.08-172.128-168.704-30.24-41.184-44.416-115.2-3.872-158.304 40.576-43.104 128.224-46.336 186.144 17.376 0 0 66.784-76.032 147.968-41.088 81.248 34.976 78.176 128.48 30.848 183.936z m263.392 20.384c-39.584 4.96-71.776 1.184-71.776 1.184V310.752h75.52s84.096 23.52 84.096 112.544c0 81.632-42.016 113.792-87.84 128.64z"})}),rn=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block",...r},fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"}), Re("polyline",{points:"17 21 17 13 7 13 7 21"}), Re("polyline",{points:"7 3 7 8 15 8"})]}),on=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block",...r},fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}), Re("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),an=({size:e=20,color:t="currentColor",className:n="",style:r})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},fill:t,children:[ Re("path",{d:"M876.89 535.11c3.22-107.02-35.43-208.89-108.85-286.85-139.4-148.03-365.98-166.35-526.67-50.07l-5.56-57.66c-2.36-24.48-24.16-42.41-48.61-40.07-24.48 2.36-42.43 24.12-40.07 48.61l17.92 185.8a44.52 44.52 0 0 0 17.77 31.48c1.51 1.13 3.07 2.13 4.68 3.04a44.528 44.528 0 0 0 30.61 4.89l178.1-35.47c24.11-4.8 39.77-28.25 34.96-52.39-4.78-24.15-28.22-39.78-52.39-34.96l-81.37 16.2c124.67-87.44 298.4-72.49 405.79 41.7 57.09 60.62 87.16 139.85 84.68 223.08-2.51 83.24-37.26 160.52-97.91 217.62C564.83 867.92 367 862.07 249.25 736.82c-16.83-17.92-45.05-18.76-62.97-1.88-17.89 16.87-18.74 45.06-1.88 62.97 28.36 30.1 60.28 54.83 94.56 74.18 148.83 83.98 341.29 66 472.1-57.18C829 741.5 873.69 642.14 876.89 535.11z"}), Re("path",{d:"M423.44 378.04c-24.59 0.46-44.16 20.78-43.7 45.37l3.34 178.13c0.46 24.59 20.78 44.16 45.37 43.7l178.13-3.34c24.59-0.46 44.16-20.78 43.7-45.37s-20.78-44.16-45.37-43.7l-133.6 2.51-2.51-133.6c-0.46-24.59-20.77-44.16-45.36-43.7z"})]}),sn=({size:e=16,color:t="currentColor",accentColor:n="#ff8910",className:r=""})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:r,style:{display:"block"},children:[ Re("path",{d:"M950.857143 731.428571a73.142857 73.142857 0 0 1 73.142857 73.142858v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142857H146.285714a73.142857 73.142857 0 0 1-73.142857-73.142857v-146.285714a73.142857 73.142857 0 0 1 73.142857-73.142858h804.571429z m0 73.142858H146.285714v146.285714h804.571429v-146.285714z m0-438.857143a73.142857 73.142857 0 0 1 73.142857 73.142857v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142857H512v-73.142857h438.857143v-146.285714H512v-73.142857h438.857143z m0-365.714286a73.142857 73.142857 0 0 1 73.142857 73.142857v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142858H146.285714a73.142857 73.142857 0 0 1-73.142857-73.142858V73.142857a73.142857 73.142857 0 0 1 73.142857-73.142857h804.571429z m0 73.142857H146.285714v146.285714h804.571429V73.142857z",fill:t}), Re("path",{d:"M3.364571 558.592h227.584v146.285714l189.622858-182.857143-189.622858-182.857142v146.285714H3.364571z",fill:n})]}),ln=({size:e=16,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ Re("path",{d:"M186.7 532.8c-14.8 0-26.8-2.3-26.8-16.9 0-14.6 12-28.9 26.8-28.9v45.8z m605.8 144.3L678.9 763c-8 7.9-32.9 11.4-40.9 3.5v-54H508L347.4 532.8H186.7v-45.9h187.5l160.7 187.4H638v-78.9c8-7.9 32.9-10 40.9-2.1l113.6 83.8z m0-342L678.9 421c-8 7.9-32.9 11.4-40.9 3.5V356.6H534.8l-93.9 128.6-33.7-28.3s94-129.8 100.8-138.5h130v-65c8-7.9 32.9-10 40.9-2.1l113.6 85.9v-2.1z",fill:t}), Re("path",{d:"M511.3 960.2c-60.5 0-119.1-11.8-174.4-35.2-53.4-22.6-101.3-54.9-142.4-96-41.1-41.1-73.4-89-96-142.4-23.4-55.2-35.2-113.9-35.2-174.4s11.8-119.1 35.2-174.4c22.6-53.4 54.9-101.3 96-142.4 41.1-41.1 89-73.4 142.4-96C392.1 76 450.8 64.2 511.3 64.2S630.4 76 685.7 99.4c53.4 22.6 101.3 54.9 142.4 96 41.1 41.1 73.4 89 96 142.4 23.4 55.2 35.2 113.9 35.2 174.4s-11.8 119.1-35.2 174.4c-22.6 53.4-54.9 101.3-96 142.4-41.1 41.1-89 73.4-142.4 96-55.2 23.4-113.9 35.2-174.4 35.2z m0-854.7c-224.3 0-406.7 182.4-406.7 406.7 0 224.3 182.4 406.7 406.7 406.7 224.3 0 406.7-182.4 406.7-406.7 0-224.2-182.4-406.7-406.7-406.7z",fill:t})]}),cn="scrollTop",dn="scrollBottom",un="goToAnchor",hn="togglePanel",gn="togglePanelMode",pn="toggleTheme",mn="openSettings",fn="switchTab1",bn="switchTab2",yn="switchTab3",vn="toggleUserQueries",xn="onlyUserQueries",wn="toggleBookmarks",Sn="locateOutline",Cn="searchOutline",kn="refreshOutline",Tn="prevHeading",En="nextHeading",An="toggleOutlineExpand",Mn="expandLevel1",In="expandLevel2",Ln="expandLevel3",Nn="expandLevel4",Rn="expandLevel5",Dn="expandLevel6",Pn="newConversation",qn="refreshConversations",Bn="locateConversation",$n="prevConversation",_n="nextConversation",On="exportConversation",zn="copyLatestReply",Fn="copyLastCodeBlock",Un="toggleScrollLock",Hn="toggleZenMode",Wn="focusInput",jn="openGlobalSearch",Gn="stopGeneration",Vn="togglePromptQueue",Qn="showShortcuts",Kn="showModelSelector",Zn="openClaudeSettings",Yn="switchClaudeKey",Xn="openGeminiSettings",Jn="openThemeSettings",er="openModelLockSettings",tr={scrollTop:{labelKey:"shortcutScrollTop",label:"去顶部",category:"navigation"},scrollBottom:{labelKey:"shortcutScrollBottom",label:"去底部",category:"navigation"},goToAnchor:{labelKey:"shortcutGoToAnchor",label:"返回锚点",category:"navigation"},togglePanel:{labelKey:"shortcutTogglePanel",label:"展开/收起面板",category:"panel"},togglePanelMode:{labelKey:"shortcutTogglePanelMode",label:"切换面板模式(吸附/悬浮)",category:"panel"},toggleTheme:{labelKey:"shortcutToggleTheme",label:"切换主题",category:"panel"},switchTab1:{labelKey:"shortcutSwitchTab1",label:"切换到第 1 个标签",category:"panel"},switchTab2:{labelKey:"shortcutSwitchTab2",label:"切换到第 2 个标签",category:"panel"},switchTab3:{labelKey:"shortcutSwitchTab3",label:"切换到第 3 个标签",category:"panel"},toggleUserQueries:{labelKey:"shortcutToggleUserQueries",label:"显示用户问题",category:"outline"},onlyUserQueries:{labelKey:"shortcutOnlyUserQueries",label:"只显示用户问题",category:"outline"},toggleBookmarks:{labelKey:"shortcutToggleBookmarks",label:"显示用户收藏",category:"outline"},locateOutline:{labelKey:"shortcutLocateOutline",label:"定位大纲",category:"outline"},searchOutline:{labelKey:"shortcutSearchOutline",label:"搜索大纲",category:"outline"},prevHeading:{labelKey:"shortcutPrevHeading",label:"上一个标题",category:"outline"},nextHeading:{labelKey:"shortcutNextHeading",label:"下一个标题",category:"outline"},refreshOutline:{labelKey:"shortcutRefreshOutline",label:"刷新大纲",category:"outline"},toggleOutlineExpand:{labelKey:"shortcutToggleOutlineExpand",label:"展开/折叠全部",category:"outline"},expandLevel1:{labelKey:"shortcutExpandLevel1",label:"展开到 1 级",category:"outline"},expandLevel2:{labelKey:"shortcutExpandLevel2",label:"展开到 2 级",category:"outline"},expandLevel3:{labelKey:"shortcutExpandLevel3",label:"展开到 3 级",category:"outline"},expandLevel4:{labelKey:"shortcutExpandLevel4",label:"展开到 4 级",category:"outline"},expandLevel5:{labelKey:"shortcutExpandLevel5",label:"展开到 5 级",category:"outline"},expandLevel6:{labelKey:"shortcutExpandLevel6",label:"展开到 6 级",category:"outline"},newConversation:{labelKey:"shortcutNewConversation",label:"新会话",category:"conversation"},refreshConversations:{labelKey:"shortcutRefreshConversations",label:"刷新会话列表",category:"conversation"},locateConversation:{labelKey:"shortcutLocateConversation",label:"定位当前会话",category:"conversation"},prevConversation:{labelKey:"shortcutPrevConversation",label:"上一个会话",category:"conversation"},nextConversation:{labelKey:"shortcutNextConversation",label:"下一个会话",category:"conversation"},exportConversation:{labelKey:"shortcutExportConversation",label:"导出对话",category:"edit"},copyLatestReply:{labelKey:"shortcutCopyLatestReply",label:"复制最新回复",category:"edit"},copyLastCodeBlock:{labelKey:"shortcutCopyLastCodeBlock",label:"复制最后代码块",category:"edit"},toggleScrollLock:{labelKey:"shortcutToggleScrollLock",label:"锁定滚动",category:"edit"},toggleZenMode:{labelKey:"shortcutToggleZenMode",label:"切换禅模式",category:"edit"},focusInput:{labelKey:"shortcutFocusInput",label:"聚焦输入框",category:"edit"},openGlobalSearch:{labelKey:"navGlobalSearch",label:"全局搜索",category:"edit"},stopGeneration:{labelKey:"shortcutStopGeneration",label:"停止生成",category:"edit"},togglePromptQueue:{labelKey:"shortcutTogglePromptQueue",label:"显示/隐藏提示词队列",category:"edit"},showModelSelector:{labelKey:"shortcutShowModelSelector",label:"模型选择菜单",category:"edit"},openSettings:{labelKey:"shortcutOpenSettings",label:"打开设置",category:"settings"},showShortcuts:{labelKey:"shortcutShowShortcuts",label:"快捷键一览",category:"settings"},openThemeSettings:{labelKey:"shortcutOpenThemeSettings",label:"打开外观主题",category:"settings"},openModelLockSettings:{labelKey:"shortcutOpenModelLockSettings",label:"打开模型锁定",category:"settings"},openGeminiSettings:{labelKey:"shortcutOpenGeminiSettings",label:"打开 Gemini 专属",category:"settings"},openClaudeSettings:{labelKey:"shortcutOpenClaudeSettings",label:"打开 Claude 专属",category:"settings"},switchClaudeKey:{labelKey:"shortcutSwitchClaudeKey",label:"一键切换可用 Claude Key",category:"settings"}},nr={navigation:{labelKey:"shortcutCategoryNavigation",label:"导航"},panel:{labelKey:"shortcutCategoryPanel",label:"面板"},outline:{labelKey:"shortcutCategoryOutline",label:"大纲"},conversation:{labelKey:"shortcutCategoryConversation",label:"会话"},edit:{labelKey:"shortcutCategoryEdit",label:"交互控制"},settings:{labelKey:"shortcutCategorySettings",label:"设置"}},rr={scrollTop:{key:"t",alt:true},scrollBottom:{key:"b",alt:true},goToAnchor:{key:"z",alt:true},togglePanel:{key:"p",alt:true},togglePanelMode:{key:"m",alt:true},toggleTheme:{key:"d",alt:true},switchTab1:{key:"1",alt:true},switchTab2:{key:"2",alt:true},switchTab3:{key:"3",alt:true},refreshOutline:{key:"r",alt:true},toggleOutlineExpand:{key:"e",alt:true},expandLevel1:{key:"1",alt:true,shift:true},expandLevel2:{key:"2",alt:true,shift:true},expandLevel3:{key:"3",alt:true,shift:true},expandLevel4:{key:"4",alt:true,shift:true},expandLevel5:{key:"5",alt:true,shift:true},expandLevel6:{key:"6",alt:true,shift:true},toggleUserQueries:{key:"q",alt:true},toggleBookmarks:{key:"c",alt:true},onlyUserQueries:{key:"q",alt:true,shift:true},prevHeading:{key:"ArrowUp",alt:true},nextHeading:{key:"ArrowDown",alt:true},locateOutline:{key:"l",alt:true},searchOutline:{key:"f",alt:true},newConversation:{key:"o",ctrl:true,shift:true},refreshConversations:{key:"r",alt:true,shift:true},locateConversation:{key:"l",alt:true,shift:true},prevConversation:{key:"[",alt:true},nextConversation:{key:"]",alt:true},exportConversation:{key:"e",ctrl:true,shift:true},copyLatestReply:{key:"c",ctrl:true,shift:true},copyLastCodeBlock:{key:";",alt:true},toggleScrollLock:{key:"s",alt:true},toggleZenMode:{key:"z",ctrl:true,shift:true},focusInput:{key:"i",alt:true},openGlobalSearch:{key:"k",ctrl:true},stopGeneration:{key:"k",alt:true},togglePromptQueue:{key:"j",alt:true},showModelSelector:{key:"/",alt:true},showShortcuts:{key:"\\",alt:true},openSettings:{key:",",alt:true},openClaudeSettings:{key:"c",ctrl:true,alt:true},switchClaudeKey:{key:"s",ctrl:true,alt:true},openGeminiSettings:{key:"g",ctrl:true,alt:true},openThemeSettings:{key:"t",ctrl:true,alt:true},openModelLockSettings:{key:"l",ctrl:true,alt:true}},or={enabled:true,globalUrl:"https://gemini.google.com",keybindings:rr},ir={Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/"},ar={"å":"a","∫":"b","ç":"c","∂":"d","´":"e","ƒ":"f","©":"g","˙":"h","ˆ":"i","∆":"j","˚":"k","¬":"l","µ":"m","˜":"n","ø":"o","π":"p","œ":"q","®":"r","ß":"s","†":"t","¨":"u","√":"v","∑":"w","≈":"x","¥":"y","Ω":"z","¡":"1","™":"2","£":"3","¢":"4","∞":"5","§":"6","¶":"7","•":"8","ª":"9","º":"0","⁄":"1","€":"2","‹":"3","›":"4","fi":"5","fl":"6","‡":"7","°":"8","·":"9","‚":"0","–":"-","—":"-","≠":"=","±":"=","“":"[","”":"[","‘":"]","’":"]","«":"\\","»":"\\","…":";","æ":"'","Æ":"'","≤":",","¯":",","≥":".","˘":".","÷":"/","¿":"/"};function sr(e,t){if(t){if(/^Key[A-Z]$/.test(t))return t.slice(3).toLowerCase();if(/^Digit[0-9]$/.test(t))return t.slice(5);if(ir[t])return ir[t]}return ar[e]?ar[e]:e}function lr(e){if(!e)return e;return {key:sr(e.key),alt:!!e.alt,ctrl:!!e.ctrl||!!e.meta,shift:!!e.shift}}function cr(e){return e?{enabled:e.enabled??true,globalUrl:e.globalUrl||or.globalUrl,keybindings:(t=e.keybindings,(t?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,null===t?null:lr(t)])):t)||or.keybindings)}:e;var t;}function dr(e,t=false){const n=lr(e);if(!n)return "";const r=[];n.ctrl&&r.push(t?"⌘":"Ctrl"),n.meta&&t&&r.push("⌘"),n.alt&&r.push(t?"⌥":"Alt"),n.shift&&r.push(t?"⇧":"Shift");const o=sr(n.key),i={ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",",":","}[o]||o.toUpperCase();return r.push(i),r.join(t?"":"+")}function ur(){if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"",n=navigator.userAgentData?.platform?.toLowerCase?.();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")||!!n?.includes("mac")||t.includes("mac os")||t.includes("macintosh")||t.includes("iphone")||t.includes("ipad")||t.includes("ipod")}const hr="prompts",gr="outline",pr="conversations",mr="settings",fr="general",br="appearance",yr="features",vr="siteSettings",xr="globalSearch",wr="shortcuts",Sr="backup",Cr="permissions",kr="about",Tr="outline",Er="conversations",Ar="prompts",Mr="tab",Ir="reminder",Lr="content",Nr="readingHistory",Rr="toolbox",Dr="presets",Pr="custom",qr="layout",Br="modelLock",$r={"appearance-sync-native-page-theme":{page:br},"appearance-preset-light":{page:br,subTab:Dr},"appearance-preset-dark":{page:br,subTab:Dr},"appearance-custom-styles":{page:br,subTab:Pr},"tab-show-notification":{page:yr,subTab:Ir},"tab-notification-sound":{page:yr,subTab:Ir},"tab-notification-sound-preset":{page:yr,subTab:Ir},"tab-notification-volume":{page:yr,subTab:Ir},"tab-notification-repeat-count":{page:yr,subTab:Ir},"tab-notification-repeat-interval":{page:yr,subTab:Ir},"tab-notify-when-focused":{page:yr,subTab:Ir},"tab-auto-focus":{page:yr,subTab:Ir},"usage-monitor-enabled":{page:yr,subTab:Ir},"usage-monitor-daily-limit":{page:yr,subTab:Ir},"usage-monitor-auto-reset":{page:yr,subTab:Ir}},_r=[{prefix:"panel-",route:{page:fr,subTab:"panel"}},{prefix:"quick-buttons-",route:{page:fr,subTab:"shortcuts"}},{prefix:"tools-menu-",route:{page:fr,subTab:"toolsMenu"}},{prefix:"shortcuts-",route:{page:wr}},{prefix:"shortcut-binding-",route:{page:wr}},{prefix:"layout-",route:{page:vr,subTab:qr}},{prefix:"model-lock-",route:{page:vr,subTab:Br}},{prefix:"gemini-",route:{page:vr,subTab:"gemini"}},{prefix:"aistudio-",route:{page:vr,subTab:"aistudio"}},{prefix:"chatgpt-",route:{page:vr,subTab:"chatgpt"}},{prefix:"claude-",route:{page:vr,subTab:"claude"}},{prefix:"global-search-",route:{page:xr}},{prefix:"tab-",route:{page:yr,subTab:Mr}},{prefix:"outline-",route:{page:yr,subTab:Tr}},{prefix:"conversation-",route:{page:yr,subTab:Er}},{prefix:"export-",route:{page:yr,subTab:Er}},{prefix:"prompt-",route:{page:yr,subTab:Ar}},{prefix:"reading-history-",route:{page:yr,subTab:Nr}},{prefix:"content-",route:{page:yr,subTab:Lr}},{prefix:"appearance-preset-",route:{page:br,subTab:Dr}},{prefix:"appearance-custom-",route:{page:br,subTab:Pr}}],Or={"general.panel.panelMode":"panel-mode","general.panel.defaultPosition":"panel-default-position","general.panel.defaultEdgeDistance":"panel-edge-distance","general.panel.width":"panel-width","general.panel.height":"panel-height","general.panel.edgeSnapThreshold":"panel-edge-snap-threshold","general.shortcuts.quickButtonsOpacity":"quick-buttons-opacity","general.toolsMenu":"tools-menu-scrollTop","siteSettings.layout.pageWidth.enabled":"layout-page-width-enabled","siteSettings.layout.pageWidth.value":"layout-page-width-value","siteSettings.layout.userQueryWidth.enabled":"layout-user-query-width-enabled","siteSettings.layout.userQueryWidth.value":"layout-user-query-width-value","siteSettings.layout.zenMode.enabled":"layout-zen-mode-enabled","siteSettings.layout.zenMode.showExitButton":"layout-zen-mode-exit-button-visible","siteSettings.modelLock":"model-lock-gemini","globalSearch.promptEnterBehavior":"global-search-prompt-enter-behavior","globalSearch.enableFuzzySearch":"global-search-fuzzy-search","globalSearch.doubleShift":"global-search-double-shift","shortcuts.enabled":"shortcuts-enabled","shortcuts.globalUrl":"shortcuts-global-url","features.prompts.submitShortcut":"shortcuts-prompt-submit-shortcut","features.tab.openInNewTab":"tab-open-new","features.tab.autoRename":"tab-auto-rename","usageMonitor.enabled":"usage-monitor-enabled","usageMonitor.dailyLimit":"usage-monitor-daily-limit","usageMonitor.autoResetEnabled":"usage-monitor-auto-reset","features.outline.autoUpdate":"outline-auto-update","features.outline.inlineBookmarkMode":"outline-inline-bookmark-mode","features.outline.panelBookmarkMode":"outline-panel-bookmark-mode","features.outline.preventAutoScroll":"outline-prevent-auto-scroll","features.prompts.promptQueue":"prompt-queue","features.export.packaging":"export-packaging","features.export.includeThoughts":"export-include-thoughts","export.packaging":"export-packaging","features.readingHistory.persistence":"reading-history-persistence","features.content.assistantMermaid":"content-assistant-mermaid","features.content.formulaCopy":"content-formula-copy","features.content.formulaCopyFormat":"content-formula-copy-format","panel.preventAutoScroll":"outline-prevent-auto-scroll","content.markdownFix":"gemini-markdown-fix","content.watermarkRemoval":"gemini-watermark-removal","geminiEnterprise.policyRetry.enabled":"gemini-policy-retry","geminiEnterprise.policyRetry.maxRetries":"gemini-policy-max-retries","aistudio.collapseNavbar":"aistudio-collapse-navbar","aistudio.collapseRunSettings":"aistudio-collapse-run-settings","aistudio.collapseTools":"aistudio-collapse-tools","aistudio.collapseAdvanced":"aistudio-collapse-advanced","aistudio.enableSearch":"aistudio-enable-search","aistudio.removeWatermark":"aistudio-remove-watermark","aistudio.markdownFix":"aistudio-markdown-fix","chatgpt.markdownFix":"chatgpt-markdown-fix","claude.sessionKeys":"claude-session-keys","appearance.syncNativePageTheme":"appearance-sync-native-page-theme","appearance.presets.light":"appearance-preset-light","appearance.presets.dark":"appearance-preset-dark","appearance.custom.styles":"appearance-custom-styles"},zr=e=>{const t=e?.trim();if(t)return Or[t]??t},Fr=e=>{const t=zr(e);if(t)return $r[t]?$r[t]:_r.find(e=>t.startsWith(e.prefix))?.route},Ur=[{settingId:"panel-mode",title:"面板模式",keywords:["panel","mode","edge snap","floating","模式","吸附","悬浮","默认打开","自动隐藏"]},{settingId:"panel-default-position",title:"默认位置",keywords:["panel","left","right","默认侧边"]},{settingId:"panel-edge-distance",title:"默认边距",keywords:["panel","edge distance","margin"]},{settingId:"panel-width",title:"面板宽度",keywords:["panel width","宽度"]},{settingId:"panel-height",title:"面板高度",keywords:["panel height","高度"]},{settingId:"panel-edge-snap-threshold",title:"边缘吸附阈值",keywords:["snap threshold","edge snap","吸附阈值"]},{settingId:"quick-buttons-opacity",title:"快捷按钮透明度",keywords:["quick buttons","opacity","透明度"]},{settingId:"quick-buttons-hide-when-panel-open",title:"面板展开时隐藏快捷按钮组",keywords:["quick buttons","hide","panel open","快捷按钮","隐藏","面板展开"]},{settingId:"quick-buttons-proximity-radius",title:"感应唤醒距离",keywords:["quick buttons","proximity","radius","唤醒距离","感应"]},{settingId:"tools-menu-export",title:"工具箱:显示导出按钮",keywords:["tools menu","export","工具箱","导出"]},{settingId:"tools-menu-copyMarkdown",title:"工具箱:显示复制 Markdown",keywords:["tools menu","copy","markdown","工具箱"]},{settingId:"tools-menu-move",title:"工具箱:显示移动按钮",keywords:["tools menu","move","folder","工具箱"]},{settingId:"tools-menu-setTag",title:"工具箱:显示标签按钮",keywords:["tools menu","tag","标签","工具箱"]},{settingId:"tools-menu-scrollLock",title:"工具箱:显示滚动锁定",keywords:["tools menu","scroll lock","锁定滚动","工具箱"]},{settingId:"tools-menu-modelLock",title:"工具箱:显示模型锁定",keywords:["tools menu","model lock","模型锁定","工具箱"]},{settingId:"tools-menu-cleanup",title:"工具箱:显示清理按钮",keywords:["tools menu","cleanup","清理","工具箱"]},{settingId:"tools-menu-settings",title:"工具箱:显示设置按钮",keywords:["tools menu","settings","设置","工具箱"]},{settingId:"tab-open-new",title:"新会话打开方式",keywords:["tab","new conversation","open in new tab","新标签页"]},{settingId:"tab-auto-rename",title:"自动重命名标签页",keywords:["tab","auto rename","自动命名"]},{settingId:"tab-rename-interval",title:"标签页重命名间隔",keywords:["tab","rename interval","重命名间隔"]},{settingId:"tab-title-format",title:"标签页标题格式",keywords:["tab","title format","标题模板"]},{settingId:"tab-show-status",title:"显示状态图标",keywords:["tab","status","状态图标"]},{settingId:"tab-hide-status-when-read",title:"仅在未读时显示完成标记",keywords:["tab","hide status","unread","未读","完成标记","✅"]},{settingId:"tab-show-notification",title:"启用新消息通知",keywords:["tab","notification","消息提醒"]},{settingId:"tab-notification-sound",title:"通知音效",keywords:["tab","notification sound","声音提醒"]},{settingId:"tab-notification-volume",title:"通知音量",keywords:["tab","notification volume","音量"]},{settingId:"tab-notify-when-focused",title:"标签页聚焦时也提醒",keywords:["tab","focused","notify","聚焦提醒"]},{settingId:"tab-auto-focus",title:"自动聚焦到对话页",keywords:["tab","auto focus","自动聚焦"]},{settingId:"usage-monitor-enabled",title:"启用高级模型对话本地计数与预估",keywords:["usage","counter","estimate","token","quota","limit","advanced model","高级模型","本地计数","预估"]},{settingId:"usage-monitor-daily-limit",title:"每日对话次数预估上限",keywords:["daily limit","quota","limit","每日上限","次数上限","token"]},{settingId:"usage-monitor-auto-reset",title:"自动归零",keywords:["auto reset","reset","midnight","自动归零","重置","清零"]},{settingId:"tab-privacy-mode",title:"隐私模式",keywords:["tab","privacy","隐私"]},{settingId:"tab-privacy-title",title:"隐私模式标题",keywords:["tab","privacy title","隐私标题"]},{settingId:"outline-auto-update",title:"自动更新大纲",keywords:["outline","auto update","自动刷新"]},{settingId:"outline-update-interval",title:"大纲更新间隔",keywords:["outline","interval","刷新频率"]},{settingId:"outline-follow-mode",title:"自动跟随浏览位置",keywords:["outline","follow","自动跟随"]},{settingId:"outline-show-word-count",title:"显示字数统计",keywords:["outline","word count","字数"]},{settingId:"outline-inline-bookmark-mode",title:"内联收藏模式",keywords:["outline","bookmark","收藏","inline"]},{settingId:"outline-panel-bookmark-mode",title:"面板收藏模式",keywords:["outline","bookmark","收藏","panel"]},{settingId:"outline-prevent-auto-scroll",title:"阻止自动滚动页面",keywords:["outline","auto scroll","禁止滚动"]},{settingId:"conversation-folder-rainbow",title:"会话文件夹彩虹色",keywords:["conversation","folder","rainbow","文件夹颜色"]},{settingId:"conversation-sync-unpin",title:"同步时自动取消置顶",keywords:["conversation","sync","unpin","置顶"]},{settingId:"conversation-sync-delete",title:"删除时同步删除云端",keywords:["conversation","sync","delete","cloud","删除","云端"]},{settingId:"export-packaging",title:"Markdown 导出方式",keywords:["export","packaging","markdown","zip","assets","导出","附件"]},{settingId:"export-custom-user-name",title:"导出:自定义用户名称",keywords:["export","user name","导出用户名"]},{settingId:"export-custom-model-name",title:"导出:自定义模型名称",keywords:["export","model name","导出模型名"]},{settingId:"export-filename-timestamp",title:"导出文件名包含时间戳",keywords:["export","filename","timestamp","时间戳"]},{settingId:"export-include-thoughts",title:"导出包含思维链",keywords:["export","thoughts","reasoning","thinking","思维链","思路","推理"]},{settingId:"export-images-base64",title:"导出时将图片转 Base64",keywords:["export","image","base64","图片"]},{settingId:"prompt-double-click-send",title:"提示词双击发送",keywords:["prompt","double click","send","双击发送"]},{settingId:"prompt-queue",title:"提示词队列",keywords:["prompt","queue","提示词队列","连续提问"]},{settingId:"reading-history-persistence",title:"阅读记录持久化",keywords:["reading history","persistence","持久化"]},{settingId:"reading-history-auto-restore",title:"自动恢复阅读位置",keywords:["reading history","restore","恢复位置"]},{settingId:"reading-history-cleanup-days",title:"阅读记录清理天数",keywords:["reading history","cleanup","days","清理周期"]},{settingId:"content-assistant-mermaid",title:"AI 回复 Mermaid 渲染",keywords:["content","mermaid","diagram","assistant response","AI 回复"]},{settingId:"content-user-query-markdown",title:"用户提问样式优化",keywords:["content","markdown","latex","math","user query","用户提问","数学公式"]},{settingId:"content-formula-copy",title:"公式复制增强",keywords:["content","formula","copy","数学公式"]},{settingId:"content-formula-copy-format",title:"公式复制格式",keywords:["content","formula","copy","format","latex","mathml","复制格式","LaTeX","MathML"]},{settingId:"content-formula-delimiter",title:"公式分隔符",keywords:["content","formula delimiter","分隔符"]},{settingId:"content-table-copy",title:"表格复制增强",keywords:["content","table copy","复制表格"]},{settingId:"layout-page-width-enabled",title:"页面宽度覆盖",keywords:["layout","page width","页面宽度"]},{settingId:"layout-page-width-value",title:"页面宽度值",keywords:["layout","page width value","页面宽度值"]},{settingId:"layout-user-query-width-enabled",title:"用户问题宽度覆盖",keywords:["layout","user query width","提问宽度"]},{settingId:"layout-user-query-width-value",title:"用户问题宽度值",keywords:["layout","user query width value","提问宽度值"]},{settingId:"layout-zen-mode-enabled",title:"布局:启用禅模式 (Zen Mode)",keywords:["layout","zen mode","禅模式","disclaimer","免责声明","隐藏"]},{settingId:"layout-zen-mode-exit-button-visible",title:"布局:显示退出禅模式按钮",keywords:["layout","zen mode","exit button","禅模式","退出按钮","隐藏"]},{settingId:"model-lock-gemini",title:"模型锁定:Gemini",keywords:["model lock","gemini","模型锁定"]},{settingId:"model-lock-gemini-enterprise",title:"模型锁定:Gemini Enterprise",keywords:["model lock","gemini enterprise","模型锁定"]},{settingId:"model-lock-aistudio",title:"模型锁定:AI Studio",keywords:["model lock","aistudio","模型锁定"]},{settingId:"model-lock-chatgpt",title:"模型锁定:ChatGPT",keywords:["model lock","chatgpt","模型锁定"]},{settingId:"model-lock-claude",title:"模型锁定:Claude",keywords:["model lock","claude","模型锁定"]},{settingId:"model-lock-grok",title:"模型锁定:Grok",keywords:["model lock","grok","模型锁定"]},{settingId:"model-lock-qianwen",title:"模型锁定:Qianwen",keywords:["model lock","qianwen","tongyi","通义千问","模型锁定"]},{settingId:"model-lock-qwenai",title:"模型锁定:Qwen Studio",keywords:["model lock","qwen studio","qwenai","chat.qwen.ai","国际版千问","模型锁定"]},{settingId:"model-lock-yuanbao",title:"模型锁定:Yuanbao",keywords:["model lock","yuanbao","腾讯元宝","模型锁定"]},{settingId:"model-lock-ima",title:"模型锁定:ima",keywords:["model lock","ima","ima.qq.com","腾讯 ima","模型锁定"]},{settingId:"model-lock-zai",title:"模型锁定:Z.ai",keywords:["model lock","z.ai","zai","模型锁定"]},{settingId:"gemini-markdown-fix",title:"Gemini:Markdown 修复",keywords:["gemini","markdown","fix","修复"]},{settingId:"gemini-watermark-removal",title:"Gemini:去水印",keywords:["gemini","watermark","去水印"]},{settingId:"gemini-policy-retry",title:"Gemini:策略重试",keywords:["gemini","policy retry","策略重试"]},{settingId:"gemini-policy-max-retries",title:"Gemini:最大重试次数",keywords:["gemini","max retries","最大重试"]},{settingId:"aistudio-collapse-navbar",title:"AI Studio:折叠左侧导航",keywords:["aistudio","collapse navbar","折叠导航"]},{settingId:"aistudio-collapse-run-settings",title:"AI Studio:折叠 Run settings",keywords:["aistudio","run settings","折叠运行设置"]},{settingId:"aistudio-collapse-tools",title:"AI Studio:折叠 Tools",keywords:["aistudio","tools","折叠工具"]},{settingId:"aistudio-collapse-advanced",title:"AI Studio:折叠 Advanced",keywords:["aistudio","advanced","折叠高级选项"]},{settingId:"aistudio-enable-search",title:"AI Studio:启用搜索",keywords:["aistudio","search","启用搜索"]},{settingId:"aistudio-remove-watermark",title:"AI Studio:去水印",keywords:["aistudio","watermark","去水印"]},{settingId:"aistudio-markdown-fix",title:"AI Studio:Markdown 修复",keywords:["aistudio","markdown","fix","修复"]},{settingId:"chatgpt-markdown-fix",title:"ChatGPT:Markdown 修复",keywords:["chatgpt","markdown","fix","修复"]},{settingId:"claude-session-keys",title:"Claude:Session Keys",keywords:["claude","session key","token","密钥"]},{settingId:"global-search-prompt-enter-behavior",title:"全局搜索:提示词回车行为",keywords:["global search","prompt","enter","全局搜索","提示词","回车"]},{settingId:"global-search-fuzzy-search",title:"Global Search: Enable fuzzy search",keywords:["global search","fuzzy","search everywhere","matching"]},{settingId:"global-search-double-shift",title:"全局搜索:双击 Shift 触发",keywords:["global search","double shift","shortcut","全局搜索","双击 shift","快捷键"]},{settingId:"global-search-shortcut-setting-link",title:"全局搜索:快捷键设置入口",keywords:["global search","shortcut","keybinding","全局搜索","快捷键","键位设置"]},{settingId:"shortcuts-enabled",title:"启用自定义快捷键",keywords:["shortcuts","enable","快捷键","自定义","总开关"]},{settingId:"shortcuts-global-url",title:"全局快捷键 URL",keywords:["shortcuts","global url","alt+o","快捷键","url"]},{settingId:"shortcuts-browser-shortcuts",title:"浏览器快捷键设置入口",keywords:["shortcuts","browser shortcuts","chrome://extensions/shortcuts","快捷键"]},{settingId:"shortcuts-prompt-submit-shortcut",title:"发送快捷键",keywords:["shortcuts","submit","enter","ctrl+enter","发送","快捷键"]},{settingId:"appearance-sync-native-page-theme",title:"同步原生页面主题",keywords:["appearance","theme","native page theme","sync native page theme","sync page theme","同步原生页面主题","原生页面主题","同步主题","亮暗模式联动","宿主页面主题"]},{settingId:"appearance-preset-light",title:"浅色主题预设",keywords:["appearance","theme","light","浅色"]},{settingId:"appearance-preset-dark",title:"深色主题预设",keywords:["appearance","theme","dark","深色"]},{settingId:"appearance-custom-styles",title:"自定义主题样式",keywords:["appearance","custom style","主题样式","css"]},...Object.entries(tr).map(([e,t])=>({settingId:`shortcut-binding-${e}`,title:`快捷键:${t.label}`,keywords:["shortcut","shortcuts","keybinding","hotkey","keyboard","快捷键","键位","按键",t.label,t.labelKey,e,t.category]}))],Hr=Object.entries(Or).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),Wr=e=>e.trim().toLowerCase(),jr=(e,t)=>{const n=Wr(e),r=(e=>Wr(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0))(n);return Ur.map((e,t)=>{const o=Wr(e.title),i=Wr((e.keywords||[]).join(" ")),a=Wr(e.settingId),s=Wr((Hr[e.settingId]||[]).join(" ")),l=`${o} ${i} ${a} ${s}`;if(r.some(e=>!l.includes(e)))return null;let c=0;return n?(o===n&&(c+=200),o.startsWith(n)&&(c+=120),o.includes(n)&&(c+=80),i.includes(n)&&(c+=70),a.includes(n)&&(c+=60),s.includes(n)&&(c+=50),r.forEach(e=>{o.startsWith(e)&&(c+=16),o.includes(e)&&(c+=8),i.includes(e)&&(c+=6),a.includes(e)&&(c+=5),s.includes(e)&&(c+=4);}),c+=Math.max(0,24-Math.min(24,o.length))):c=1e3-t,{item:e,score:c,index:t}}).filter(e=>!!e).sort((e,t)=>t.score!==e.score?t.score-e.score:e.index-t.index).map(({item:e})=>e)},Gr={[hr]:{label:"tabPrompts",icon:"✏️",IconComponent:Ge},[pr]:{label:"tabConversations",icon:"💬",IconComponent:Qe},[gr]:{label:"tabOutline",icon:"📑",IconComponent:We},[mr]:{label:"tabSettings",icon:"⚙️"}},Vr={scrollTop:{icon:"⬆",labelKey:"scrollTop",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:rt},panel:{icon:"✨",labelKey:"panelTitle",canToggle:false,isPanelOnly:true,IconComponent:Zt},floatingToolbar:{icon:"🧰",labelKey:"tools",canToggle:true,isPanelOnly:false,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(0 12 12)"}), Re("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(60 12 12)"}), Re("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(120 12 12)"}), Re("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})},globalSearch:{icon:"🔎",labelKey:"navGlobalSearch",canToggle:true,isPanelOnly:false,IconComponent:Qt},anchor:{icon:"⚓",canToggle:true,labelKey:"showCollapsedAnchorLabel",isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:_e},theme:{icon:"☀",labelKey:"showCollapsedThemeLabel",canToggle:true,isPanelOnly:false,IconComponent:Be},manualAnchor:{icon:"📍",labelKey:"manualAnchorLabel",canToggle:true,isPanelOnly:false,isGroup:true,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Re("path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}), Re("line",{x1:"12",y1:"7",x2:"12",y2:"13"}), Re("line",{x1:"9",y1:"10",x2:"15",y2:"10"})]})},scrollBottom:{icon:"⬇",labelKey:"scrollBottom",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:ot},zenMode:{icon:"🧘",labelKey:"zenModeTitle",canToggle:true,isPanelOnly:false,IconComponent:Ht},settings:{icon:"⚙️",labelKey:"tabSettings",canToggle:true,isPanelOnly:false,IconComponent:Fe}},Qr=["📁","📂","📥","🗂️","📊","📈","📉","📋","💼","📅","📌","📎","📝","✒️","🔍","💡","💻","⌨️","🖥️","🖱️","🐛","🔧","🔨","⚙️","🤖","👾","🧠","⚡","🔥","✨","🎓","📚","🎨","🎭","🎬","🎹","🎵","📷","🖌️","🖍️","🏠","🛒","✈️","🎮","⚽","🍔","☕","❤️","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","⭐","🌟","🎉","🔒","🔑","🚫","✅","❓"],Kr=["#FF461F","#FF6B6B","#FA8072","#DC143C","#CD5C5C","#FF4500","#FFA500","#FFB347","#F0E68C","#DAA520","#FFD700","#9ACD32","#32CD32","#3CB371","#20B2AA","#00CED1","#5F9EA0","#4682B4","#6495ED","#4169E1","#0000CD","#8A2BE2","#9370DB","#BA55D3","#DB7093","#C71585","#8B4513","#A0522D","#708090","#2F4F4F"],Zr=1500,Yr=2e3,Xr=3e3,Jr="#10b981",eo="#ef4444",to="var(--gh-text-secondary)",no=[{id:"default",labelKey:"notificationSoundPresetDefault",fallback:"Default"},{id:"softChime",labelKey:"notificationSoundPresetSoftChime",fallback:"Soft Chime"},{id:"glassPing",labelKey:"notificationSoundPresetGlassPing",fallback:"Glass Ping"},{id:"brightAlert",labelKey:"notificationSoundPresetBrightAlert",fallback:"Bright Alert"}],ro=["settings","prompts","folders","tags","conversations","readingHistory"],oo=["conversations","readingHistory"],io=()=>[{id:"default_1",title:le("defaultPromptCodeOptTitle"),content:le("defaultPromptCodeOptContent"),category:le("defaultPromptCodeOptCategory")},{id:"default_2",title:le("defaultPromptTranslateTitle"),content:le("defaultPromptTranslateContent"),category:le("defaultPromptTranslateCategory")}],ao=[{id:"inbox",name:"收件箱",icon:"📥",isDefault:true}],so={PAGE_WIDTH:{DEFAULT_PX:"1280",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:1200},USER_QUERY_WIDTH:{DEFAULT_PX:"600",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:600}},lo={CLAUDE_KEY:/^sk-ant-sid\d{2}-/},co=500,uo="claude",ho="gemini",go="chatgpt",po="chatglm",mo="gemini-enterprise",fo="grok",bo="aistudio",yo="doubao",vo="ima",xo="deepseek",wo="kimi",So="qianwen",Co="qwenai",ko="yuanbao",To="zai",Eo=[{id:go,name:"ChatGPT",pattern:/chatgpt\.com/,url:"https://chatgpt.com",icon:"💬"},{id:ho,name:"Gemini",pattern:/gemini\.google\.com/,url:"https://gemini.google.com",icon:"🌟"},{id:uo,name:"Claude",pattern:/claude\.(ai|com)/,url:"https://claude.ai",icon:"🎭"},{id:bo,name:"AI Studio",pattern:/aistudio\.google\.com/,url:"https://aistudio.google.com",icon:"🧪"},{id:fo,name:"Grok",pattern:/grok\.com/,url:"https://grok.com",icon:"🤖"},{id:mo,name:"Gemini Enterprise",pattern:/business\.gemini\.google/,url:"https://business.gemini.google",icon:"🏢"},{id:yo,name:"Doubao",pattern:/www\.doubao\.com/,url:"https://www.doubao.com",icon:"🌱"},{id:xo,name:"DeepSeek",pattern:/chat\.deepseek\.com/,url:"https://chat.deepseek.com",icon:"🌀"},{id:wo,name:"Kimi",pattern:/www\.kimi\.com/,url:"https://www.kimi.com",icon:"🌙"},{id:To,name:"Z.ai",pattern:/chat\.z\.ai/,url:"https://chat.z.ai",icon:"⚡"},{id:po,name:"ChatGLM",pattern:/chatglm\.cn/,url:"https://chatglm.cn/main/alltoolsdetail?lang=zh",icon:"🧠"},{id:ko,name:"Yuanbao",pattern:/yuanbao\.tencent\.com/,url:"https://yuanbao.tencent.com",icon:"💎"},{id:So,name:"Qianwen",pattern:/www\.qianwen\.com/,url:"https://www.qianwen.com",icon:"🔮"},{id:Co,name:"Qwen Studio",pattern:/chat\.qwen\.ai/,url:"https://chat.qwen.ai",icon:"🪄"},{id:vo,name:"ima",pattern:/ima\.qq\.com/,url:"https://ima.qq.com",icon:"🐼"}],Ao="__all__",Mo="__recent__",Io="export",Lo="copyMarkdown",No="move",Ro="setTag",Do="scrollLock",Po="modelLock",qo="cleanup",Bo="settings",$o=[{id:Io,labelKey:"export",defaultLabel:"Export",IconComponent:Ze,defaultVisible:true},{id:Lo,labelKey:"exportToClipboard",defaultLabel:"Copy Markdown",IconComponent:It,defaultVisible:true},{id:No,labelKey:"conversationsMoveTo",defaultLabel:"Move",IconComponent:Oe,defaultVisible:true},{id:Ro,labelKey:"conversationsSetTag",defaultLabel:"Set Tag",IconComponent:qt,defaultVisible:true},{id:Do,labelKey:"shortcutToggleScrollLock",defaultLabel:"Scroll Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Re("path",{d:"M12 3v12"}), Re("path",{d:"m8 11 4 4 4-4"}), Re("path",{d:"M19 19H5"}), Re("circle",{cx:"12",cy:"11",r:"9",strokeOpacity:"0.3"}), Re("path",{d:"m4.9 4.9 14.2 14.2"})]}),isToggle:true,defaultVisible:true},{id:Po,labelKey:"modelLockTitle",defaultLabel:"Model Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>De("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Re("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}), Re("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}), Re("circle",{cx:"9",cy:"15",r:"1.5",fill:t,stroke:"none"}), Re("circle",{cx:"15",cy:"15",r:"1.5",fill:t,stroke:"none"}), Re("path",{d:"M9 19h6"})]}),isToggle:true,defaultVisible:true},{id:qo,labelKey:"cleanup",defaultLabel:"Cleanup",IconComponent:Pt,isDanger:true,defaultVisible:true},{id:Bo,labelKey:"tabSettings",defaultLabel:"Settings",IconComponent:Fe,isSystem:true,defaultVisible:true}],_o=e=>{let t;const n=new Set,r=(e,r)=>{const o="function"==typeof e?e(t):e;if(!Object.is(o,t)){const e=t;t=(null!=r?r:"object"!=typeof o||null===o)?o:Object.assign({},t,o),n.forEach(n=>n(t,e));}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e))},a=t=e(r,o,i);return i},Oo=e=>e;const zo=e=>{const t=(e=>e?_o(e):_o)(e),n=e=>function(e,t=Oo){const n=i.useSyncExternalStore(e.subscribe,i.useCallback(()=>t(e.getState()),[e,t]),i.useCallback(()=>t(e.getInitialState()),[e,t]));return i.useDebugValue(n),n}(t,e);return Object.assign(n,t),n},Fo=e=>zo;function Uo(e,t){let n;try{n=e();}catch(r){return}return {getItem:e=>{var t;const r=e=>null===e?null:JSON.parse(e,void 0),o=null!=(t=n.getItem(e))?t:null;return o instanceof Promise?o.then(r):r(o)},setItem:(e,t)=>n.setItem(e,JSON.stringify(t,void 0)),removeItem:e=>n.removeItem(e)}}const Ho=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then:e=>Ho(e)(n),catch(e){return this}}}catch(n){return {then(e){return this},catch:e=>Ho(e)(n)}}},Wo=(e,t)=>(n,r,o)=>{let i={storage:Uo(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},a=false,s=0;const l=new Set,c=new Set;let d=i.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...e);},r,o);const u=()=>{const e=i.partialize({...r()});return d.setItem(i.name,{state:e,version:i.version})},h=o.setState;o.setState=(e,t)=>(h(e,t),u());const g=e((...e)=>(n(...e),u()),r,o);let p;o.getInitialState=()=>g;const m=()=>{var e,t;if(!d)return;const o=++s;a=false,l.forEach(e=>{var t;return e(null!=(t=r())?t:g)});const h=(null==(t=i.onRehydrateStorage)?void 0:t.call(i,null!=(e=r())?e:g))||void 0;return Ho(d.getItem.bind(d))(i.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===i.version)return [false,e.state];if(i.migrate){const t=i.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[true,e]):[true,t]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided");}return [false,void 0]}).then(e=>{var t;if(o!==s)return;const[a,l]=e;return p=i.merge(l,null!=(t=r())?t:g),n(p,true),a?u():void 0}).then(()=>{o===s&&(null==h||h(p,void 0),p=r(),a=true,c.forEach(e=>e(p)));}).catch(e=>{o===s&&(null==h||h(void 0,e));})};return o.persist={setOptions:e=>{i={...i,...e},e.storage&&(d=e.storage);},clearStorage:()=>{null==d||d.removeItem(i.name);},getOptions:()=>i,rehydrate:()=>m(),hasHydrated:()=>a,onHydrate:e=>(l.add(e),()=>{l.delete(e);}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e);})},i.skipHydration||m(),p||g};const jo=true;new class{area;constructor(e){this.area=e?.area||"local";}async get(e){const t=GM_getValue(e);if(null!=t)return t}async set(e,t){GM_setValue(e,t);}async remove(e){GM_deleteValue(e);}async getAll(){return console.warn("[Storage Polyfill] getAll() is not supported in userscript"),{}}async setMany(e){for(const[t,n]of Object.entries(e))GM_setValue(t,n);}watch(e){if("string"==typeof e){const t=GM_addValueChangeListener(e,(e,t,n,r)=>{});return ()=>GM_removeValueChangeListener(t)}{const t=[];for(const[n,r]of Object.entries(e)){const e=GM_addValueChangeListener(n,(e,t,n,o)=>{r({newValue:n,oldValue:t});});t.push(e);}return ()=>t.forEach(e=>GM_removeValueChangeListener(e))}}}({area:"local"});const Go="ophel:clearAllFlag",Vo="ophel_skip_restore",Qo={mode:"light",lightStyleId:"google-gradient",darkStyleId:"classic-dark"},Ko={enabled:false,value:"81",unit:"%"},Zo={enabled:false,value:"81",unit:"%"},Yo={enabled:false,showExitButton:true},Xo={enabled:true},Jo=[{id:"panel",enabled:true},{id:"floatingToolbar",enabled:true},{id:"globalSearch",enabled:true},{id:"theme",enabled:true},{id:"zenMode",enabled:true},{id:"settings",enabled:true},{id:"scrollTop",enabled:true},{id:"manualAnchor",enabled:false},{id:"anchor",enabled:true},{id:"scrollBottom",enabled:true}],ei={collapsed:Jo.map(e=>({...e})),opacity:1,floatingToolbar:{open:true},hideWhenPanelOpen:false,proximityRadius:150},ti={language:"auto",hasAgreedToTerms:false,hasSeenOphelAdvancedGuide:false,panel:{panelExpanded:true,panelMode:"edge-snap",preventAutoScroll:false,defaultPosition:"right",defaultEdgeDistance:0,edgeSnapThreshold:30,height:85,width:320},geminiEnterprise:{policyRetry:{enabled:false,maxRetries:3}},content:{assistantMermaid:true,markdownFix:false,watermarkRemoval:jo,formulaCopy:true,formulaCopyFormat:"latex",formulaDelimiter:true,tableCopy:true,exportImagesToBase64:false,userQueryMarkdown:true},export:{customUserName:"",customModelName:"",exportFilenameTimestamp:false,includeThoughts:true,packaging:"markdown"},theme:{syncNativePageTheme:true,sites:{gemini:{...Qo},"gemini-enterprise":{...Qo},doubao:{...Qo},ima:{...Qo},deepseek:{...Qo},yuanbao:{...Qo},zai:{...Qo},_default:{...Qo}},customStyles:[]},layout:{pageWidth:{gemini:{...Ko},"gemini-enterprise":{...Ko},aistudio:{...Ko},doubao:{...Ko},ima:{...Ko},deepseek:{...Ko},yuanbao:{...Ko},zai:{...Ko},_default:{...Ko}},userQueryWidth:{gemini:{...Zo},"gemini-enterprise":{...Zo},aistudio:{...Zo},doubao:{...Zo},ima:{...Zo},deepseek:{...Zo},yuanbao:{...Zo},zai:{...Zo},_default:{...Zo}},zenMode:{gemini:{...Yo},"gemini-enterprise":{...Yo},aistudio:{...Yo},doubao:{...Yo},ima:{...Yo},deepseek:{...Yo},yuanbao:{...Yo},zai:{...Yo},_default:{...Yo}},cleanMode:{gemini:{...Xo},"gemini-enterprise":{...Xo},aistudio:{...Xo},doubao:{...Xo},ima:{...Xo},deepseek:{...Xo},yuanbao:{...Xo},zai:{...Xo},_default:{...Xo}}},modelLock:{gemini:{enabled:false,keyword:""},"gemini-enterprise":{enabled:false,keyword:""},ima:{enabled:false,keyword:""},qwenai:{enabled:false,keyword:""},yuanbao:{enabled:false,keyword:""}},globalSearch:{promptEnterBehavior:"smart",enableFuzzySearch:false,doubleShift:false},usageMonitor:{enabled:false,dailyLimit:100,autoResetEnabled:false},features:{order:["outline","conversations","prompts"],prompts:{enabled:true,doubleClickToSend:false,submitShortcut:"enter",promptQueue:false},conversations:{enabled:true,syncUnpin:false,syncDelete:true,folderRainbow:true},outline:{enabled:true,maxLevel:6,autoUpdate:true,updateInterval:2,showUserQueries:true,followMode:"current",expandLevel:6,inlineBookmarkMode:"always",panelBookmarkMode:"always",showWordCount:false}},tab:{openInNewTab:false,autoRename:true,renameInterval:3,showStatus:true,hideStatusWhenRead:false,titleFormat:"{status}{title}->{model}",showNotification:jo,notificationSound:true,notificationSoundPreset:"softChime",notificationVolume:.5,notificationRepeatCount:3,notificationRepeatInterval:2,notifyWhenFocused:false,autoFocus:false,privacyMode:false,privacyTitle:"Google",customIcon:"default"},readingHistory:{persistence:true,autoRestore:true,cleanupDays:3},quickButtons:{collapsed:Jo.map(e=>({...e})),opacity:ei.opacity,floatingToolbar:{...ei.floatingToolbar},hideWhenPanelOpen:ei.hideWhenPanelOpen,proximityRadius:ei.proximityRadius},claude:{currentKeyId:""},webdav:{enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:"ophel",dataSources:["settings","conversations","prompts","claudeSessionKeys"]},shortcuts:or,aistudio:{collapseNavbar:false,collapseTools:false,collapseAdvanced:false,enableSearch:true,defaultModel:"",markdownFix:jo,removeWatermark:jo},chatgpt:{markdownFix:false}};function ni(e,t){const n=e.theme?.sites;return n&&t in n?n[t]:n?._default??Qo}function ri(e,t){const n=e.layout?.pageWidth;return n&&t in n?n[t]:n?._default??Ko}function oi(e,t){return e.modelLock?.[t]??{enabled:false,keyword:""}}function ii(e,t){const n=e.layout?.userQueryWidth;return n&&t in n?n[t]:n?._default??Zo}function ai(e,t){const n=e.layout?.zenMode;return n&&t in n?n[t]:n?._default??Yo}function si(e,t){const n=e.layout?.cleanMode;return n&&t in n?n[t]:n?._default??Xo}let li=null;const ci="ophel:restoreFlag";let di=null;function ui(){if("undefined"==typeof window)return false;const e=new URL(window.location.href);if("1"!==e.searchParams.get(Vo))return false;e.searchParams.delete(Vo);const t=`${e.pathname}${e.search}${e.hash}`||window.location.pathname+window.location.search+window.location.hash;return window.history.replaceState(window.history.state,"",t),true}const hi=(e,t)=>{if(null==t)return null;const n="string"==typeof t?(e=>{try{return JSON.parse(e)}catch{return}})(t):t;return "settings"===e&&void 0!==n&&!(e=>"object"==typeof e&&null!==e&&"state"in e)(n)&&(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&["hasAgreedToTerms","panel","content","theme","layout"].some(t=>t in e))(n)?JSON.stringify({state:{settings:n},version:0}):"string"==typeof t?t:JSON.stringify(t)},gi={getItem:e=>{try{const t=GM_getValue(e);return hi(e,t)}catch(t){throw console.error(`[ophel] userscriptStorageAdapter.getItem("${e}") THREW:`,t),t}},setItem:(e,t)=>{GM_setValue(e,t);},removeItem:e=>{GM_deleteValue(e);}};let pi=0;const mi=e=>{pi+=1;try{return e()}finally{(()=>{const e=()=>{pi=Math.max(0,pi-1);};"function"!=typeof queueMicrotask?Promise.resolve().then(e):queueMicrotask(e);})();}},fi=(e,t,n)=>{if(e.some(e=>e.id===t.id))return e;const r=[...e],o=n?r.findIndex(e=>e.id===n)+1:r.length;return r.splice(o>0?o:r.length,0,t),r},bi=e=>{if(!e)return;const t=Number(e.xRatio),n=Number(e.yRatio);return Number.isFinite(t)&&Number.isFinite(n)?{xRatio:Math.min(1,Math.max(0,t)),yRatio:Math.min(1,Math.max(0,n))}:void 0},yi=e=>{const t=Array.isArray(e.collapsedButtons)?e.collapsedButtons:[],n=e.quickButtons||{},r=n.collapsed??t;let o=r.length>0?r.filter(e=>Boolean(e?.id)).map(e=>({id:e.id,enabled:false!==e.enabled})):ei.collapsed.map(e=>({...e}));return o=fi(o,{id:"floatingToolbar",enabled:true},"panel"),o=fi(o,{id:"globalSearch",enabled:true},"floatingToolbar"),o=fi(o,{id:"zenMode",enabled:true},"theme"),o=fi(o,{id:"settings",enabled:true},"zenMode"),{collapsed:o,opacity:n.opacity??e.quickButtonsOpacity??ei.opacity,hideWhenPanelOpen:n.hideWhenPanelOpen??ei.hideWhenPanelOpen,toolsMenu:n.toolsMenu??e.toolsMenu,floatingToolbar:{...ei.floatingToolbar,...e.floatingToolbar||{},...n.floatingToolbar||{}},position:bi(n.position),proximityRadius:(()=>{const e=Number(n.proximityRadius);return Number.isFinite(e)?Math.min(300,Math.max(0,e)):ei.proximityRadius})()}},vi=(e,t,n)=>{const r={...n}; return new Set([...Object.keys(n),...Object.keys(e??{})]).forEach(o=>{r[o]=((e,t)=>{const n=so[t],r=Number.parseInt(n.DEFAULT_PERCENT,10),o=Number.parseInt(n.DEFAULT_PX,10),i=Number.parseInt(String(e?.value??n.DEFAULT_PERCENT),10),a="px"===e?.unit?"px":"%";let s=Number.isNaN(i)?r:i;return "px"===a&&(s=Math.round(s/o*r)),{enabled:e?.enabled??false,value:String((l=s,c=n.MIN_PERCENT,d=n.MAX_PERCENT,Math.min(d,Math.max(c,l)))),unit:"%"};var l,c,d;})(e?.[o]??n[o],t);}),r},xi=e=>{const t={...ti.theme.sites}; return new Set([...Object.keys(ti.theme.sites),...Object.keys(e??{})]).forEach(n=>{t[n]={...ti.theme.sites[n]??ti.theme.sites._default,...e?.[n]??{}};}),t},wi=(e,t)=>{const n={...t}; return new Set([...Object.keys(t),...Object.keys(e??{})]).forEach(r=>{n[r]={...t[r]??t._default??{},...e?.[r]??{}};}),n},Si=e=>{const t=ti.panel;return {panelExpanded:e?.panelExpanded??t.panelExpanded,panelMode:"edge-snap"===e?.panelMode||"floating"===e?.panelMode?e.panelMode:t.panelMode,preventAutoScroll:e?.preventAutoScroll??t.preventAutoScroll,defaultPosition:"left"===e?.defaultPosition||"right"===e?.defaultPosition?e.defaultPosition:t.defaultPosition,defaultEdgeDistance:e?.defaultEdgeDistance??t.defaultEdgeDistance,edgeSnapThreshold:e?.edgeSnapThreshold??t.edgeSnapThreshold,height:e?.height??t.height,width:e?.width??t.width}},Ci=e=>{const t=ti.export,n="zip"===e?.packaging||"markdown"===e?.packaging?e.packaging:t.packaging;return {...t,...e,packaging:n}},ki=e=>{const{collapsedButtons:t,quickButtonsOpacity:n,toolsMenu:r,floatingToolbar:o,quickButtons:i,...a}=e;return {...ti,...a,panel:Si(e.panel),content:{...ti.content,...e.content},theme:{...ti.theme,...e.theme,sites:xi(e.theme?.sites),customStyles:e.theme?.customStyles??ti.theme.customStyles},layout:{...ti.layout,...e.layout,pageWidth:vi(e.layout?.pageWidth,"PAGE_WIDTH",ti.layout.pageWidth),userQueryWidth:vi(e.layout?.userQueryWidth,"USER_QUERY_WIDTH",ti.layout.userQueryWidth),zenMode:wi(e.layout?.zenMode,ti.layout.zenMode),cleanMode:wi(e.layout?.cleanMode,ti.layout.cleanMode)},modelLock:wi(e.modelLock,ti.modelLock),globalSearch:{...ti.globalSearch,...e.globalSearch},usageMonitor:{...ti.usageMonitor,...e.usageMonitor},features:{...ti.features,...e.features,outline:{...ti.features.outline,...e.features?.outline},prompts:{...ti.features.prompts,...e.features?.prompts},conversations:{...ti.features.conversations,...e.features?.conversations}},tab:{...ti.tab,...e.tab},readingHistory:{...ti.readingHistory,...e.readingHistory},export:Ci(e.export),geminiEnterprise:{...ti.geminiEnterprise,...e.geminiEnterprise,policyRetry:{...ti.geminiEnterprise?.policyRetry,...e.geminiEnterprise?.policyRetry}},webdav:{...ti.webdav,...e.webdav},aistudio:{...ti.aistudio,...e.aistudio},chatgpt:{...ti.chatgpt,...e.chatgpt},shortcuts:cr(e.shortcuts)||ti.shortcuts,quickButtons:yi(e)}},Ti={...gi,setItem:async(e,t)=>{if(!(pi>0))return gi.setItem(e,t)}},Ei=(e,t)=>t?ki({...e,...t}):e;let Ai=null;const Mi=Fo()(Wo((e,t)=>(Ai=e,{settings:ti,persistedSettings:ti,previewSettings:null,_hasHydrated:false,_syncVersion:0,setSettings:t=>e(e=>{const n=ki({...e.persistedSettings,...t});return {persistedSettings:n,previewSettings:null,settings:n}}),setPreviewSettings:t=>mi(()=>e(e=>({previewSettings:t,settings:Ei(e.persistedSettings,t)}))),clearPreviewSettings:()=>mi(()=>e(e=>({previewSettings:null,settings:e.persistedSettings}))),updateNestedSetting:(t,n,r)=>e(e=>{const o=ki({...e.persistedSettings,[t]:{...e.persistedSettings[t],[n]:r}});return {persistedSettings:o,previewSettings:null,settings:o}}),updateDeepSetting:(t,n,r,o)=>e(e=>{const i=e.persistedSettings[t],a=i?.[n]||{},s=ki({...e.persistedSettings,[t]:{...i,[n]:{...a,[r]:o}}});return {persistedSettings:s,previewSettings:null,settings:s}}),replaceSettings:t=>e(()=>{const e=ki({...ti,...t});return {persistedSettings:e,previewSettings:null,settings:e}}),resetSettings:()=>e(()=>{const e=ki(ti);return {persistedSettings:e,previewSettings:null,settings:e}}),setHasHydrated:t=>mi(()=>e({_hasHydrated:t}))}),{name:"settings",storage:Uo(()=>Ti),partialize:e=>({settings:e.persistedSettings}),merge:(e,t)=>{try{const n=e?.settings,r=ki(n??t.persistedSettings);return {...t,settings:r,persistedSettings:r,previewSettings:null}}catch(n){throw console.error("[ophel] settings merge THREW:",n),n}},onRehydrateStorage:()=>(e,t)=>{mi(()=>{if(e){const t=ki(e.settings);return void Ai?.({persistedSettings:t,previewSettings:null,settings:t,_hasHydrated:!0})}Ai?.({_hasHydrated:!0});});}})),Ii=()=>Mi(e=>e._hasHydrated),Li=()=>Mi.getState().settings,Ni=e=>Mi.subscribe(t=>e(t.settings)),Ri=Object.freeze(Object.defineProperty({__proto__:null,getSettingsState:Li,subscribeSettings:Ni,useSettingsHydrated:Ii,useSettingsStore:Mi},Symbol.toStringTag,{value:"Module"})),Di=new Map;function Pi(e,t=2e3,n={}){let r=document.body,o=null;const i=document.querySelectorAll("plasmo-csui, #ophel-userscript-root");for(const u of i)if(u.shadowRoot){const e=u.shadowRoot.querySelector(".gh-root, #plasmo-shadow-container, .plasmo-csui-container, #ophel-app-container");if(e){r=e,o=u;break}r=u.shadowRoot,o=u;}const a=r.getRootNode(),s=a instanceof ShadowRoot?a:document.head,l=document.getElementById("gh-toast");l&&l.remove();for(const u of i)if(u.shadowRoot){const e=u.shadowRoot.querySelector("#gh-toast");e&&e.remove();}if(!s.querySelector("#gh-toast-style")){const e=document.createElement("style");e.id="gh-toast-style",e.textContent=`\n${he}\n .gh-toast {\n position: fixed !important;\n left: 50% !important;\n background: color-mix(in srgb, var(--gh-bg, #ffffff) 90%, transparent) !important;\n color: var(--gh-text, #1f2937) !important;\n border: 1px solid color-mix(in srgb, var(--gh-primary, #6366f1) 20%, var(--gh-border, #d1d5db)) !important;\n padding: 10px 22px !important;\n border-radius: 9999px !important;\n font-size: 14px !important;\n font-weight: 600 !important;\n box-shadow:\n var(--gh-shadow-lg, 0 8px 32px rgba(0, 0, 0, 0.35)),\n 0 0 0 1px inset color-mix(in srgb, var(--gh-primary, #6366f1) 15%, transparent) !important;\n z-index: 2147483646 !important; /* 刚好在一级最高层(禅模式按钮 2147483647)之下 */\n pointer-events: none !important;\n opacity: 0 !important;\n transform: translateY(-20px) translateX(-50%) scale(0.92) !important;\n transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1), transform 0.3s cubic-bezier(0.16, 1, 0.3, 1) !important;\n font-family: ${be()} !important;\n letter-spacing: 0.2px !important;\n backdrop-filter: blur(16px) saturate(160%) !important;\n -webkit-backdrop-filter: blur(16px) saturate(160%) !important;\n max-width: min(calc(100vw - 32px), 480px);\n white-space: nowrap !important;\n overflow: hidden !important;\n text-overflow: ellipsis !important;\n }\n .gh-toast.show {\n opacity: 1 !important;\n transform: translateY(0) translateX(-50%) scale(1) !important;\n }\n .gh-toast--outline-nav {\n max-width: 360px !important;\n }\n @media (prefers-reduced-motion: reduce) {\n .gh-toast {\n transition: opacity 0.2s ease !important;\n transform: translateX(-50%) !important;\n }\n .gh-toast.show {\n transform: translateX(-50%) !important;\n }\n }\n `,s.appendChild(e);}const c=document.createElement("div");c.id="gh-toast",c.className="gh-toast";const d=!(!document.getElementById("gh-zen-mode-exit-host")&&!o?.shadowRoot?.querySelector("#gh-zen-mode-exit-host"));c.style.setProperty("top",d?"84px":"32px","important"),n.className&&c.classList.add(n.className),n.maxWidth&&Number.isFinite(n.maxWidth)&&(c.style.maxWidth=`${n.maxWidth}px`),c.textContent=e,r.appendChild(c),requestAnimationFrame(()=>{c.classList.add("show");}),setTimeout(()=>{c.classList.remove("show"),setTimeout(()=>{c.parentNode&&c.parentNode.removeChild(c);},300);},t);}function qi(e,t=2e3,n={},r=1500,o=e){const i=Date.now();i-(Di.get(o)||0){t(r,n);});return ()=>GM_removeValueChangeListener(n)}},fetch:async(e,t)=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,data:t?.body,responseType:"text",onload(r){const o=r.status>=200&&r.status<300;n({ok:o,status:r.status,statusText:r.statusText,text:async()=>r.responseText,json:async()=>JSON.parse(r.responseText),blob:async()=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,responseType:"blob",onload(e){n(e.response);},onerror:r});})});},onerror(e){r(e);}});}),notify(e){GM_notification({title:e.title,text:e.message,timeout:e.timeout??5e3,silent:e.silent??true,onclick:()=>{window.focus();}});},getNotificationSoundUrl:e=>window.__OPHEL_NOTIFICATION_SOUND_URLS__?.[e],focusWindow(){window.focus();},openTab(e){window.open(e,"_blank");},hasCapability:e=>!["cookies","permissions","tabs","declarativeNetRequest","commands"].includes(e),async getClaudeSessionKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:le("claudeNotOnSiteHint")};const e=document.cookie.match(/sessionKey=([^;]+)/);return e&&e[1]?{success:true,sessionKey:decodeURIComponent(e[1])}:{success:false,error:le("claudeNoCookieFound")}},testClaudeSessionKey:async e=>new Promise(t=>{GM_xmlhttpRequest({url:"https://claude.ai/api/organizations",method:"GET",headers:{Accept:"application/json",Cookie:`sessionKey=${e}`},onload(e){try{if(200!==e.status)return void t({success:!0,isValid:!1,error:`HTTP ${e.status}`});const n=e.responseText;if(n.toLowerCase().includes("unauthorized"))return void t({success:!0,isValid:!1,error:"Unauthorized"});const r=JSON.parse(n);if(!Array.isArray(r)||0===r.length)return void t({success:!0,isValid:!1,error:"No organizations"});const o=r[0],i=o?.rate_limit_tier,a=o?.capabilities||[],s=o?.api_disabled_reason;let l="Unknown";"default_claude_max_5x"===i?l="Max(5x)":"default_claude_max_20x"===i?l="Max(20x)":"default_claude_ai"===i?l="Free":"auto_api_evaluation"===i?l="out_of_credits"===s?"API(无额度)":"API":a.includes("claude_max")?l="Max":a.includes("api")?l="API":a.includes("chat")&&(l="Free"),t({success:!0,isValid:!0,accountType:l});}catch{t({success:true,isValid:false,error:"Parse error"});}},onerror(){t({success:false,isValid:false,error:"Request failed"});}});}),async setClaudeSessionKey(e){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:le("claudeNotOnSiteHint")};const t=new Date(Date.now()+31536e6).toUTCString();return document.cookie=`sessionKey=${encodeURIComponent(e)}; domain=.claude.ai; path=/; expires=${t}; secure; samesite=lax`,location.href="https://claude.ai/",{success:true}},async switchNextClaudeKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:le("claudeNotOnSiteHint")};try{const e=GM_getValue("claudeSessionKeys"),t=e?.state?.keys||[];if(0===t.length)return {success:!1,error:"noClaudeKeys"};const n=e?.state?.currentKeyId;let r=t.filter(e=>!1!==e.isValid);0===r.length&&(r=[...t]),r.sort((e,t)=>{const n=e.accountType?.toLowerCase()?.includes("pro"),r=t.accountType?.toLowerCase()?.includes("pro");return n&&!r?-1:!n&&r?1:e.name.localeCompare(t.name)});const o=r.findIndex(e=>e.id===n);if(1===r.length&&-1!==o)return {success:!1,error:"claudeOnlyOneKey"};let i=0;-1!==o&&(i=(o+1)%r.length);const a=r[i];if(!a)return {success:!1,error:"nextKeyNotFound"};if(a.key){const e=new Date(Date.now()+31536e6).toUTCString();document.cookie=`sessionKey=${encodeURIComponent(a.key)}; domain=.claude.ai; path=/; expires=${e}; secure; samesite=lax`;}return e?.state&&(e.state.currentKeyId=a.id,GM_setValue("claudeSessionKeys",e)),location.href="https://claude.ai/",{success:!0,keyName:a.name}}catch(e){return {success:false,error:e.message}}}};const _i=Object.freeze(Object.defineProperty({__proto__:null,get platform(){return $i}},Symbol.toStringTag,{value:"Module"})),Oi=String.fromCodePoint(128228),zi=String.fromCodePoint(128587),Fi=String.fromCodePoint(129302),Ui="data-ophel-export-markdown-href";function Hi(e){if(!e)return "";const t=e=>e.replace(/\r\n?/g,"\n"),n=e=>{const t=e?.split(/\r?\n/)[0]?.trim().toLowerCase()||"";return !t||/^(copy|复制)$/.test(t)?"":t.replace(/\s+/g,"")},r=e=>{const n=t(e).replace(/\s*\n\s*/g," ").trim();return n?`$${n}$`:""},o=e=>{const n=t(e).trim();if(!n)return "";return n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n)?`\n$$\n${n}\n$$\n`:`\n$$${n}$$\n`},i=e=>{const t=e.querySelector('annotation[encoding="application/x-tex"]'),n=t?.textContent?.trim();if(n)return n;const r=e.getAttribute("data-tex")||e.getAttribute("data-latex");if(r)return r.trim();const o=e.getAttribute("aria-label");return o?o.trim():""},a=e=>{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const t=e,n=t.tagName?.toLowerCase()||"";return "br"===n?"\n":"style"===n||"script"===n||"template"===n||"noscript"===n||"button"===n||"svg"===n||"annotation"===n||"annotation-xml"===n||t.classList?.contains("gh-assistant-mermaid")||t.classList?.contains("katex-mathml")||t.classList?.contains("katex-html")?"":Array.from(t.childNodes).map(a).join("")},s=e=>{const t=e.querySelector("code"),r=t?.className.match(/language-([A-Za-z0-9_#+-]+)/),o=!!e.querySelector("#code-block-viewer, .cm-editor"),i=[e.getAttribute("data-language"),e.querySelector(".cm-content")?.getAttribute("data-language"),r?.[1],e.querySelector(".code-block-decoration span")?.textContent,o?e.querySelector('.sticky [class*="font-medium"]')?.textContent:null];for(const a of i){const e=n(a);if(e)return e}return ""},l=e=>{const n=!!e.querySelector("#code-block-viewer, .cm-editor"),r=e.matches(".cm-content")?e:e.querySelector(".cm-content")??null;if(r){const n=t(a(r)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}const o=e.matches("code")?e:e.querySelector("pre code, code")??null;if(o){const n=t(a(o)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}if(!n){const n=t(a(e)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}return null},c=(e,t)=>Array.from(e.childNodes).map(e=>h(e,t)).join(""),d=(e,t)=>{const n="ol"===e.tagName.toLowerCase(),r=Array.from(e.children).filter(e=>"li"===e.tagName?.toLowerCase()).map((e,r)=>u(e,t,n?r+1:null)).filter(Boolean).join("\n");return r?`\n${r}\n\n`:""},u=(e,n,r)=>{const o=" ".repeat(n),i=null===r?"-":`${r}.`,a=[],s=[];for(const t of Array.from(e.childNodes)){if(t.nodeType===Node.ELEMENT_NODE){const e=t,r=e.tagName.toLowerCase();if("ul"===r||"ol"===r){const t=d(e,n+1).replace(/^\n+|\n+$/g,"");t&&s.push(t);continue}}a.push(h(t,{listDepth:n,inListItem:true}));}const l=(c=a.join(""),t(c).replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim());var c;let u=l?((e,n,r)=>{const o=t(e).split("\n"),[i="",...a]=o;return 0===a.length?`${n}${i}`:[`${n}${i}`,...a.map(e=>e?`${r}${e}`:"")].join("\n")})(l,`${o}${i} `,`${o} `):`${o}${i}`;return s.length>0&&(u=`${u.trimEnd()}\n${s.join("\n")}`),u},h=(e,t={listDepth:0,inListItem:false})=>{try{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const n=e;if(n.classList?.contains("gh-assistant-mermaid"))return "";if(n.classList?.contains("math-block")){const e=n.getAttribute("data-math");if(e)return o(e)}if(n.classList?.contains("math-inline")){const e=n.getAttribute("data-math");if(e)return r(e)}if(n.classList?.contains("katex-display")){const e=i(n);if(e)return o(e)}if(n.classList?.contains("katex")){const e=i(n);if(e)return r(e)}if(n.classList?.contains("katex-mathml"))return "";if(n.classList?.contains("katex-html"))return "";if("BUTTON"===n.tagName||"SVG"===n.tagName)return "";if(n.classList?.contains("cm-content")&&n.getAttribute("data-language")){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if(n.classList?.contains("cm-cursorLayer")||n.classList?.contains("cm-selectionLayer")||n.classList?.contains("cm-announced"))return "";const a=n.tagName?.toLowerCase()||"";if(!a)return "";if("annotation"===a||"annotation-xml"===a)return "";if("style"===a||"script"===a||"template"===a||"noscript"===a)return "";if("img"===a){const e=n.alt||n.getAttribute("alt")||"图片";return `![${e}](${n.getAttribute("src")||n.src||""})`}if("code-block"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("pre"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("code"===a)return "pre"===n.parentElement?.tagName.toLowerCase()?"":`\`${n.textContent}\``;if("table"===a){const e=[],t=n.querySelector("thead"),r=n.querySelector("tbody"),o=e=>e.textContent?.trim()||"";if(t){const n=t.querySelector("tr");if(n){const t=Array.from(n.querySelectorAll("td, th")).map(o);t.some(e=>e)&&(e.push("| "+t.join(" | ")+" |"),e.push("| "+t.map(()=>"---").join(" | ")+" |"));}}if(r){r.querySelectorAll("tr").forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&e.push("| "+n.join(" | ")+" |");});}if(!t&&!r){const t=n.querySelectorAll("tr");let r=!0;t.forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&(e.push("| "+n.join(" | ")+" |"),r&&(e.push("| "+n.map(()=>"---").join(" | ")+" |"),r=!1));});}return e.length>0?"\n"+e.join("\n")+"\n":""}if("table-block"===a||"ucs-markdown-table"===a){const e=n.querySelector("table");if(e)return h(e)}switch(a){case "h1":return `\n# ${c(n,t)}\n`;case "h2":return `\n## ${c(n,t)}\n`;case "h3":return `\n### ${c(n,t)}\n`;case "h4":return `\n#### ${c(n,t)}\n`;case "h5":return `\n##### ${c(n,t)}\n`;case "h6":return `\n###### ${c(n,t)}\n`;case "strong":case "b":return `**${c(n,t)}**`;case "em":case "i":return `*${c(n,t)}*`;case "a":return `[${c(n,t)}](${n.getAttribute(Ui)||n.href||""})`;case "li":return u(n,t.listDepth,"ol"===n.parentElement?.tagName?.toLowerCase()?Array.from(n.parentElement.children).filter(e=>"li"===e.tagName?.toLowerCase()).indexOf(n)+1:null);case "p":return t.inListItem?`${c(n,t).trim()}\n`:`${c(n,t)}\n\n`;case "br":return "\n";case "ul":case "ol":return d(n,t.listDepth);case "blockquote":{const e=c(n,t).replace(/\r\n/g,"\n").split("\n");return `\n${e.map(e=>e.trim().length>0?`> ${e}`:">").join("\n")}\n`}default:return n.shadowRoot?Array.from(n.shadowRoot.childNodes).map(e=>h(e,t)).join(""):c(n,t)}}catch(n){return console.error("Error processing node in htmlToMarkdown:",n),e.textContent||""}};return h(e).trim()}function Wi(e,t){const n=[];return n.push(`# ${e.title}`),n.push(""),n.push("---"),n.push(""),n.push(`## ${Oi} ${le("exportMetaTitle")}`),n.push(`- **${le("exportMetaConvTitle")}**: ${e.title}`),n.push(`- **${le("exportMetaTime")}**: ${e.exportTime}`),n.push(`- **${le("exportMetaSource")}**: ${e.source}`),n.push(`- **${le("exportMetaUrl")}**: ${e.url}`),n.push(""),n.push("---"),n.push(""),t.forEach(t=>{if("user"===t.role){const r=e.customUserName||le("exportUserLabel");n.push(`## ${zi} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}else {const r=e.customModelName||e.source;n.push(`## ${Fi} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}}),n.join("\n")}const ji=new TextEncoder;let Gi=null;function Vi(e){const t=function(){if(Gi)return Gi;const e=new Uint32Array(256);for(let t=0;t<256;t+=1){let n=t;for(let e=0;e<8;e+=1)n=1&n?3988292384^n>>>1:n>>>1;e[t]=n>>>0;}return Gi=e,e}();let n=4294967295;for(const r of e)n=t[255&(n^r)]^n>>>8;return (4294967295^n)>>>0}function Qi(e,t,n){return e[t]=255&n,e[t+1]=n>>>8&255,t+2}function Ki(e,t,n){return e[t]=255&n,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255,t+4}function Zi(e){const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length;}),n}async function Yi(e){return "string"==typeof e?ji.encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(await e.arrayBuffer())}function Xi(e,t){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim()||t}function Ji(e,t){const n=e.replace(/\\/g,"/").replace(/^[a-zA-Z]:\//,"").replace(/^\/+/,"").split("/").map(e=>Xi(e,"asset")).filter(e=>"."!==e&&".."!==e);return n.length>0?n.join("/"):t}function ea(e,t){if(!t.has(e))return t.add(e),e;const n=e.lastIndexOf("/"),r=n>=0?`${e.slice(0,n+1)}`:"",o=n>=0?e.slice(n+1):e,i=o.lastIndexOf("."),a=i>0?o.slice(0,i):o,s=i>0?o.slice(i):"";for(let l=2;l<1e4;l+=1){const e=`${r}${a}-${l}${s}`;if(!t.has(e))return t.add(e),e}throw new Error(`Unable to create unique zip path for ${e}`)}function ta(e,t,n="assets/asset"){return ea(function(e,t="assets/asset"){return Ji(e,t)}(e,n),t)}function na(e){return `assets/${Xi(e.name,e.id||"asset")}`}async function ra(e){if(void 0!==e.content)return e.content;if(!e.sourceUrl)throw new Error("Asset has no content or source URL");try{const t=await fetch(e.sourceUrl,{credentials:"include"});if(!t.ok)throw new Error(`Asset fetch failed with HTTP ${t.status}`);return t.blob()}catch(t){if(!/^https?:\/\//i.test(e.sourceUrl))throw t;try{const t=await $i.fetch(e.sourceUrl);if(!t.ok)throw new Error(`Asset proxy fetch failed with HTTP ${t.status}`);return t.blob()}catch(n){throw new Error(`Asset fetch failed: ${oa(t)}; proxy fetch failed: ${oa(n)}`)}}}function oa(e){return e instanceof Error?e.message:String(e)}async function ia(e){const t=[],n=[],{dosDate:r,dosTime:o}=function(e=new Date){const t=Math.max(1980,e.getFullYear());return {dosTime:e.getHours()<<11|e.getMinutes()<<5|Math.floor(e.getSeconds()/2),dosDate:t-1980<<9|e.getMonth()+1<<5|e.getDate()}}();let i=0;for(const d of e){const e=Ji(d.path,"file"),a=ji.encode(e),s=await Yi(d.data),l=Vi(s),c=new Uint8Array(30+a.length);let u=0;u=Ki(c,u,67324752),u=Qi(c,u,20),u=Qi(c,u,2048),u=Qi(c,u,0),u=Qi(c,u,o),u=Qi(c,u,r),u=Ki(c,u,l),u=Ki(c,u,s.length),u=Ki(c,u,s.length),u=Qi(c,u,a.length),u=Qi(c,u,0),c.set(a,u),t.push({path:e,data:s,crc32:l,dosTime:o,dosDate:r,localHeaderOffset:i}),n.push(c,s),i+=c.length+s.length;}const a=i;t.forEach(e=>{const t=ji.encode(e.path),r=new Uint8Array(46+t.length);let o=0;o=Ki(r,o,33639248),o=Qi(r,o,20),o=Qi(r,o,20),o=Qi(r,o,2048),o=Qi(r,o,0),o=Qi(r,o,e.dosTime),o=Qi(r,o,e.dosDate),o=Ki(r,o,e.crc32),o=Ki(r,o,e.data.length),o=Ki(r,o,e.data.length),o=Qi(r,o,t.length),o=Qi(r,o,0),o=Qi(r,o,0),o=Qi(r,o,0),o=Qi(r,o,0),o=Ki(r,o,0),o=Ki(r,o,e.localHeaderOffset),r.set(t,o),n.push(r),i+=r.length;});const s=i-a,l=new Uint8Array(22);let c=0;return c=Ki(l,c,101010256),c=Qi(l,c,0),c=Qi(l,c,0),c=Qi(l,c,t.length),c=Qi(l,c,t.length),c=Ki(l,c,s),c=Ki(l,c,a),Qi(l,c,0),n.push(l),new Blob([Zi(n)],{type:"application/zip"})}async function aa(e,t,n="text/plain;charset=utf-8"){try{const r=new Blob([e],{type:n});return await sa(r,t)}catch(r){return console.error("[Exporter] Download failed:",r),Pi(le("exportFailed")),false}}async function sa(e,t){try{const n=URL.createObjectURL(e),r=document.createElement("a");return r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n),!0}catch(n){return console.error("[Exporter] Download failed:",n),Pi(le("exportFailed")),false}}function la(){return {assets:[],usedPaths:new Set,imagePathsBySource:new Map,filePathsBySource:new Map}}function ca(e,t="file",n=120){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim().substring(0,n)||t}function da(e){return e.replace(/[[\]]/g,"\\$&")}function ua(e,t="asset"){const n=e.filter(e=>Boolean(e)).map(e=>function(e,t="asset"){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}(e,"")).filter(Boolean).join("-");return n||t}function ha(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.host.toLowerCase()}${t.pathname}`}catch{return e.split(/[?#]/)[0]}}function ga(e,t={}){if(!e)return "";try{const n=new URL(e,window.location.href).pathname,r=decodeURIComponent(n.split("/").pop()||"");return t.ignoreGenericDownload&&"download"===r?"":r}catch{return ""}}function pa(e){return e.match(/\.([A-Za-z0-9]{1,10})(?:$|[?#\s])/)?.[1]?.toLowerCase()||""}function ma(e){return pa(ga(e))}function fa(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean);let n="";for(let a=0;a/^[^.\s].*\.[A-Za-z0-9]{1,10}$/.test(e))||"");const r=t.find(e=>/^\.[A-Za-z0-9]{1,10}$/.test(e))||"",o=t.find(e=>/^\d+(?:\.\d+)?\s*(?:B|KB|MB|GB|TB)$/i.test(e))||"",i=n||t.find(e=>e!==o&&!/^\.[A-Za-z0-9]{1,10}$/.test(e))||r;return {name:i,type:pa(i)||(r?r.slice(1):""),sizeLabel:o}}function ba(e,t="document"){const n=e.replace(/\r\n/g,"\n").split("\n").find(e=>/^#\s+/.test(e.trim()));return n?.replace(/^#\s+/,"").trim()||t}function ya(e,t="document"){return `${ca(e,t,80)}.md`}function va(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}function xa(e){if(!e)return false;if(/^(blob:|data:)/i.test(e))return true;if(!/^https?:\/\//i.test(e))return false;try{const t=new URL(e);return (t.hostname!==window.location.hostname||!/^\/?(app|share)(\/|$)/.test(t.pathname))&&!/faviconV2|google_logo_icon|\/32\/type\//i.test(t.href)}catch{return false}}function wa(e){const[t,n=""]=e.split(",",2),r=t.match(/^data:([^;]+)/)?.[1]||"application/octet-stream";if(!/;base64/i.test(t))return new Blob([decodeURIComponent(n)],{type:r});const o=atob(n),i=new Uint8Array(o.length);for(let a=0;aLa(e,t,n)).filter(Boolean)}function Ra(e,t,n){return e.filter(e=>"image"===e.kind&&Boolean(e.source)).map(e=>La({source:e.source||"",alt:n.getAlt?.(e)||e.name,extensionHint:n.getExtensionHint?.(e)||e.name||e.type||""},t,{siteId:n.siteId,role:n.role||"user",category:n.category||"image",fallbackAlt:n.fallbackAlt||"uploaded image",directory:n.directory,prefix:n.prefix})).filter(Boolean)}function Da(e,t,n){const r=n.prefix||ua([n.siteId,n.role||"user",n.category||"file"]),o=n.fallbackName||"attachment";return e.filter(e=>n.includeAttachment?n.includeAttachment(e):"file"===e.kind).map(e=>{const i=da(n.getLabel?.(e)||function(e){const t=e.name||"attachment",n=e.type?.trim()||"",r=[n&&!t.toLowerCase().endsWith(`.${n.toLowerCase()}`)?n:"",e.sizeLabel||""].filter(Boolean);return r.length>0?`${t} (${r.join(", ")})`:t}(e)||o),a=e.source&&t?Ia(t,{source:e.source,name:e.name||o,mimeHint:n.getMimeHint?.(e)||e.type||e.name,directory:n.directory||"assets/files",idPrefix:r}):e.source;return a?`- [${i}](${a})`:`- ${i}`})}function Pa(e,t,n={}){const r=function(e,t,n={}){const r=n.fallbackTitle||"document",o=ya(n.title||ba(t,r),r),i=n.description??(n.title||void 0),a=e.assets.find(e=>"document"===e.kind&&e.content===t&&e.description===i);if(a?.relativePath)return {name:a.name,path:a.relativePath};const s=ta(`${(n.directory||"assets/documents").replace(/\/+$/,"")}/${o}`,e.usedPaths),l=s.split("/").pop()||o;return e.assets.push({id:`${n.idPrefix||"document"}-${e.assets.length+1}`,name:l,relativePath:s,mimeType:"text/markdown;charset=utf-8",kind:"document",content:t,description:i}),{name:l,path:s}}(e,t,n);return `[${da(n.title||r.name)}](${r.path})`}const qa="data-ophel-managed-tab-title",Ba="data-ophel-gemini-native-tab-title",$a="data-ophel-gemini-native-tab-title-path",_a=/\{(?:status|title|model|site)\}/g,Oa="{model}",za={"(":")","[":"]","{":"}","<":">","(":")","【":"】","《":"》","「":"」","『":"』"};function Fa(e){const t=e?.replace(/\s+/g," ").trim();return t||null}function Ua(){"undefined"!=typeof document&&document.documentElement?.removeAttribute(qa);}function Ha(){return "undefined"==typeof document?null:document.documentElement?.getAttribute(qa)||null}function Wa(e,t={}){const n=Fa(e);if(!n)return null;const r=Ha(),o=Fa(t.expectedManagedTitle),i=Fa(t.privacyTitle),a=Fa(t.siteName),s=Boolean(o&&n===o)||Boolean(r&&n===r),l=s||true===t.hasManagedTitleSignal;if(i&&n===i)return null;const c=function(e,t){let n=e,r=t.hasManagedSignal;r&&/^(?:[⏳✅]\s*)+/u.test(n)&&(n=n.replace(/^(?:[⏳✅]\s*)+/u,""));const o=function(e,t){const n=t.titleFormat||"";if(!n.includes("{title}"))return null;const r=function(e,t){const n=[e],r=Ga(e);r!==e&&n.push(r);const o=[];return n.forEach(e=>{const n=function(e,t){const n=/\{(status|title|model|site)\}/g;let r="^\\s*",o=0,i=false,a=0;for(const s of e.matchAll(n)){r+=Za(e.slice(o,s.index));const n=s[1];if("title"===n)r+=i?"[\\s\\S]*?":"(?[\\s\\S]+?)",i=true;else if("status"===n)r+=`(?(?:[⏳✅]\\s*)*)`,a+=1;else if("model"===n)r+=`(?\\[[^\\]]{1,160}\\])?`,a+=1;else if("site"===n){const e=Fa(t);r+=e?`(?${Za(e)})`:`(?[\\s\\S]*?)`,a+=1;}o=s.index+s[0].length;}if(r+=Za(e.slice(o)),r+="\\s*$",!i)return null;try{return new RegExp(r,"u")}catch{return null}}(e,t);n&&o.push(n);}),o}(n,t.siteName);if(0===r.length)return null;let o=e,i=false,a=t.hasManagedSignal;for(let s=0;s<20;s+=1){const e=Ka(o,r);if(!e)break;if(!a&&!e.hasManagedSignal)break;if(!e.title||e.title===o)break;o=e.title,i=true,a=true;}return i?Fa(o):null}(n,{hasManagedSignal:r,siteName:t.siteName,titleFormat:t.titleFormat});o&&o!==n&&(n=o,r=true);return Fa(n)}(n,{hasManagedSignal:l,siteName:t.siteName,titleFormat:t.titleFormat});return c?a&&c===a&&c!==n&&s||i&&c===i?null:c:null}function ja(e,t={}){const n=Wa(e,t);if(!n)return null;const r=Fa(t.siteName);if(r&&n===r)return null;return Fa(r?n.replace(new RegExp(`\\s*[-|]\\s*${Ya(r)}$`,"i"),"").replace(new RegExp(`^${Ya(r)}\\s*[-|]\\s*`,"i"),"").trim():n)}function Ga(e){let t=e;for(;t.includes(Oa);){const e=Va(t);if(e===t)return t.replace(/\{model\}/g,"");t=e;}return t}function Va(e){const t=Array.from(e.matchAll(_a)),n=t.findIndex(e=>e[0]===Oa&&void 0!==e.index);if(n<0)return e;const r=t[n-1],o=t[n+1],i=t[n],a=i.index??0,s=a+i[0].length,l=void 0!==r?.index?r.index+r[0].length:0,c=o?.index??e.length,d=r&&o&&"{status}"!==r[0]&&"{status}"!==o[0]?function(e,t){const n=function(e,t){const n=e.match(/^(.*?)([\[({<(【《「『])\s*$/u),r=t.match(/^\s*([\])}>)】》」』])(.*)$/u);if(!n||!r)return null;const o=n[2],i=r[1];return za[o]!==i?null:`${n[1]}${r[2]}`}(e,t);if(null!==n)return n;const r=Qa(e),o=Qa(t);return r&&!o?t:!r&&o||e.trim()&&e.trim()===t.trim()?e:e.trim()?(t.trim(),e):t}(e.slice(l,a),e.slice(s,c)):"";return `${e.slice(0,l)}${d}${e.slice(c)}`}function Qa(e){return /[\p{L}\p{N}]/u.test(e)}function Ka(e,t){for(const n of t){const t=n.exec(e),r=Fa(t?.groups?.ophelTitle);if(t&&r)return {title:r,hasManagedSignal:false}}return null}function Za(e){return Ya(e).replace(/\s+/g,"\\s+")}function Ya(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Xa={MAX_DEPTH:15,DEFAULT_TIMEOUT:5e3,POLL_INTERVAL:50,CACHE_TTL:3e5},Ja={ELEMENT:1,DOCUMENT:9,FRAGMENT:11},es=["keydown","keypress","keyup"],ts="data-ophel-interaction-layer",ns={[ts]:"true"},rs=[`[${ts}="true"]`,".gh-dialog-overlay",".conversations-dialog-overlay",".conversations-folder-menu",".conversations-tag-filter-menu",".prompt-modal",".prompt-preview-modal",".import-dialog",".settings-modal-overlay",".settings-search-overlay",".quick-menu-popover"].join(", "),os=e=>(e??("undefined"!=typeof document&&document.body?[document.body]:[])).some(e=>Boolean(e.querySelector(rs))),is=e=>e instanceof HTMLElement&&("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||e.isContentEditable||"true"===e.getAttribute("contenteditable")||e.classList.contains("ProseMirror")),as=(e,t={})=>{const{events:n=es,capture:r=true}=t,o=e=>{(e=>{const t=("function"==typeof e.composedPath?e.composedPath():[]).find(e=>e instanceof HTMLElement)||null;return is(t)?t:is(e.target)?e.target:null})(e)&&(e.stopPropagation(),e.stopImmediatePropagation());};return n.forEach(t=>{e.addEventListener(t,o,r);}),()=>{n.forEach(t=>{e.removeEventListener(t,o,r);});}},ss={isValidContext:e=>null!==e&&Object.values(Ja).includes(e.nodeType),isVisible:e=>e&&null!==e.offsetParent,isConnected:e=>e&&e.isConnected,createCleanupManager(){const e=new Set;return {add:t=>(e.add(t),()=>e.delete(t)),execute(){e.forEach(e=>{try{e();}catch(RS){console.error("[DOMToolkit] Cleanup error:",RS);}}),e.clear();},get size(){return e.size}}}};class ls{enabled=true;ttl;store=new WeakMap;timestamps=new WeakMap;constructor(e=Xa.CACHE_TTL){this.ttl=e;}setEnabled(e){this.enabled=e;}get(e,t){if(!this.enabled)return null;const n=this.store.get(e),r=this.timestamps.get(e);if(!n||!r)return null;const o=n.get(t);if(!o)return null;const i=r.get(t);return i&&Date.now()-i>this.ttl?(n.delete(t),r.delete(t),null):ss.isConnected(o)?o:(n.delete(t),r.delete(t),null)}set(e,t,n){if(!this.enabled||!n)return;let r=this.store.get(e),o=this.timestamps.get(e);r||(r=new Map,this.store.set(e,r)),o||(o=new Map,this.timestamps.set(e,o)),r.set(t,n),o.set(t,Date.now());}clear(){this.store=new WeakMap,this.timestamps=new WeakMap;}}class cs{observers=new Map;getSharedObserver(e){if(!this.observers.has(e)){const t=new Set,n=new MutationObserver(e=>{for(const n of e)for(const e of n.addedNodes)e.nodeType===Ja.ELEMENT&&t.forEach(t=>{try{t(e,n);}catch(RS){console.error("[DOMToolkit] Observer callback error:",RS);}});});n.observe(e,{childList:true,subtree:true}),this.observers.set(e,{observer:n,callbacks:t,refCount:0});}const t=this.observers.get(e);return t.refCount++,{addCallback:e=>t.callbacks.add(e),removeCallback:n=>{t.callbacks.delete(n),t.refCount--,0===t.refCount&&(t.observer.disconnect(),this.observers.delete(e));}}}destroy(){this.observers.forEach(({observer:e})=>e.disconnect()),this.observers.clear();}}const ds=new class{cache;observerManager;doc;constructor(){this.doc=document,this.cache=new ls,this.observerManager=new cs;}configCache(e={}){"boolean"==typeof e.enabled&&this.cache.setEnabled(e.enabled);}clearCache(){this.cache.clear();}getComposedParent(e){if(!e)return null;if(e instanceof ShadowRoot)return e.host;if(e instanceof Element&&e.assignedSlot)return e.assignedSlot;if(e.parentNode)return e.parentNode;const t=e.getRootNode?.();return t instanceof ShadowRoot?t.host:null}getComposedParentElement(e){let t=this.getComposedParent(e);for(;t;){if(t instanceof HTMLElement)return t;t=this.getComposedParent(t);}return null}closestComposed(e,t){let n=e;for(;n;){if(n instanceof HTMLElement)try{if(n.matches(t))return n}catch{return null}n=this.getComposedParent(n);}return null}query(e,t={}){const{parent:n=this.doc,all:r=false,shadow:o=true,maxDepth:i=Xa.MAX_DEPTH,useCache:a=true,filter:s=null}=t,l=Array.isArray(e)?e:[e],c=a&&!s;if(!r&&c&&1===l.length){const e=this.cache.get(n,l[0]);if(e)return e}for(const d of l)try{if(r){const e=Array.from(n.querySelectorAll(d)),t=s?e.filter(s):[...e];if(o&&this.collectInShadow(n,d,t,0,i,s),t.length>0)return t}else {const e=n.querySelectorAll(d);for(const t of e)if(!s||s(t))return c&&this.cache.set(n,d,t),t}}catch{}if(o&&!r){const e=this.findInShadow(n,l,0,i,s);return e&&c&&1===l.length&&this.cache.set(n,l[0],e),e}return r?[]:null}findInShadow(e,t,n,r,o){if(n>r)return null;if(e!==this.doc&&e.querySelectorAll)for(const a of t)try{const t=e.querySelectorAll(a);for(const e of t)if(!o||o(e))return e}catch{}const i=e.querySelectorAll?e.querySelectorAll("*"):[];for(const a of i)if(a.shadowRoot){const e=this.findInShadow(a.shadowRoot,t,n+1,r,o);if(e)return e}return null}collectInShadow(e,t,n,r,o,i){if(r>o)return;if(e!==this.doc&&e.querySelectorAll)try{const r=e.querySelectorAll(t);for(const e of r)n.includes(e)||i&&!i(e)||n.push(e);}catch{}const a=e.querySelectorAll?e.querySelectorAll("*"):[];for(const s of a)s.shadowRoot&&this.collectInShadow(s.shadowRoot,t,n,r+1,o,i);}async get(e,t={}){const{parent:n=this.doc,timeout:r=Xa.DEFAULT_TIMEOUT,shadow:o=true,filter:i=null}=t,a=this.query(e,{parent:n,shadow:o,filter:i});return a&&!Array.isArray(a)?a:new Promise(t=>{const a=ss.createCleanupManager(),s=Date.now();let l;r>0&&(l=setTimeout(()=>{a.execute(),t(null);},r),a.add(()=>clearTimeout(l)));const c=()=>{if(r>0&&Date.now()-s>=r)return;const l=this.query(e,{parent:n,shadow:o,filter:i});if(l&&!Array.isArray(l))return a.execute(),void t(l);const d=setTimeout(c,Xa.POLL_INTERVAL);a.add(()=>clearTimeout(d));},d=Array.isArray(e)?e:[e],u=this.observerManager.getSharedObserver(n),h=e=>{for(const n of d)try{if(e.matches?.(n)&&(!i||i(e)))return a.execute(),void t(e);if(e.querySelectorAll){const r=e.querySelectorAll(n);for(const e of r)if(!i||i(e))return a.execute(),void t(e)}}catch{}};u.addCallback(h),a.add(()=>u.removeCallback(h)),c();})}each(e,t,n={}){const{parent:r=this.doc,shadow:o=true}=n;if("function"!=typeof t)return console.error("[DOMToolkit] each: callback must be a function"),()=>{};const i=new WeakSet;let a=true;const s=(e,n)=>{if(a&&!i.has(e)){i.add(e);try{!1===t(e,n)&&d();}catch(RS){console.error("[DOMToolkit] each callback error:",RS),d();}}};this.query(e,{parent:r,all:true,shadow:o}).forEach(e=>s(e,false));const l=this.observerManager.getSharedObserver(r),c=t=>{if(a)try{t.matches?.(e)&&s(t,!0),t.querySelectorAll&&t.querySelectorAll(e).forEach(e=>s(e,!0));}catch{}};l.addCallback(c);const d=()=>{a&&(a=false,l.removeCallback(c));};return d}watch(e,t,n={}){const{debounce:r=0,childList:o=true,attributes:i=true,characterData:a=false,subtree:s=false,attributeFilter:l}=n;if(!ss.isValidContext(e))return console.error("[DOMToolkit] watch: invalid element"),()=>{};let c=null;const d=new MutationObserver((e,n)=>{if(r>0)c&&clearTimeout(c),c=setTimeout(()=>{try{t(e,n);}catch(RS){console.error("[DOMToolkit] watch callback error:",RS);}},r);else try{t(e,n);}catch(RS){console.error("[DOMToolkit] watch callback error:",RS);}});return d.observe(e,{childList:o,attributes:i,characterData:a,subtree:s,attributeFilter:l}),()=>{c&&clearTimeout(c),d.disconnect();}}watchMultiple(e,t={}){const{debounce:n=0,characterData:r=true,childList:o=true,attributes:i=false}=t;if(!ss.isValidContext(e))return console.error("[DOMToolkit] watchMultiple: invalid container"),{add:()=>{},remove:()=>{},stop:()=>{}};const a=new Map;let s=null;const l=new Set,c=()=>{l.forEach(e=>{const t=a.get(e);if(t)try{t(e);}catch(RS){console.error("[DOMToolkit] watchMultiple callback error:",RS);}}),l.clear();},d=new MutationObserver(t=>{for(const n of t){let t=n.target;for(;t&&t!==e;){if(a.has(t)){l.add(t);break}t=t.parentNode;}}0!==l.size&&(n>0?(s&&clearTimeout(s),s=setTimeout(c,n)):c());});return d.observe(e,{characterData:r,childList:o,attributes:i,subtree:true}),{add:(e,t)=>a.set(e,t),remove:e=>a.delete(e),stop:()=>{s&&clearTimeout(s),d.disconnect(),a.clear();}}}on(e,t,n,r={}){const{parent:o=this.doc,capture:i=false}=r,a=e=>{const r=e.composedPath?e.composedPath():[e.target];for(const i of r){if(i===o||i===window)break;try{if(i.matches?.(t))return void n(e,i)}catch{}}try{const r=e.target.closest?.(t);r&&o.contains(r)&&n(e,r);}catch{}};return o.addEventListener(e,a,i),()=>o.removeEventListener(e,a,i)}create(e,t={},n=""){const r=this.doc.createElement(e);for(const[o,i]of Object.entries(t))"className"===o?r.className=i:"style"===o&&"object"==typeof i?Object.assign(r.style,i):"style"===o?r.setAttribute("style",i):"dataset"===o&&"object"==typeof i?Object.assign(r.dataset,i):o.startsWith("on")&&"function"==typeof i?r.addEventListener(o.slice(2).toLowerCase(),i):r.setAttribute(o,i);return n&&(r.textContent=n),r}createFromHTML(e,t={}){const{parent:n=null,mapIds:r=false}=t,o=this.doc.createElement("template");o.innerHTML=e.trim();const i=o.content.firstElementChild;if(!i)return null;if(n instanceof Element&&n.appendChild(i),r){const e={root:i};return i.id&&(e[i.id]=i),i.querySelectorAll("[id]").forEach(t=>{t.id&&(e[t.id]=t);}),e}return i}clear(e){for(;e.firstChild;)e.removeChild(e.firstChild);}css(e,t=null){if(t){const n=this.doc.getElementById(t);if(n)return n.textContent!==e&&(n.textContent=e),n}const n=this.doc.createElement("style");return t&&(n.id=t),n.textContent=e,this.doc.head.appendChild(n),n}cssToShadow(e,t,n=null){if(!e)return null;try{if(n){const r=e.getElementById(n);if(r)return r.textContent!==t&&(r.textContent=t),r}const r=this.doc.createElement("style");return n&&(r.id=n),r.textContent=t,e.appendChild(r),r}catch{return null}}cssToAllShadows(e,t,n={}){const{root:r=this.doc.body,filter:o=null}=n;if(!r)return 0;let i=0;const a=n=>{if(n.shadowRoot){if(o&&!o(n));else try{this.cssToShadow(n.shadowRoot,e,t),i++;}catch{}try{a(n.shadowRoot);}catch{}}const r=n.childNodes;for(let e=0;e{if(n>r)return;if(t.shadowRoot){try{e(t.shadowRoot,t);}catch(RS){console.error("[DOMToolkit] walkShadowRoots callback error:",RS);}try{o(t.shadowRoot,n+1);}catch{}}const i=t.childNodes;for(let e=0;ee.clientHeight)return e}const o=(e,t)=>{if(t>Xa.MAX_DEPTH)return null;const n=e.querySelectorAll?e.querySelectorAll("*"):[];for(const i of n){if(i.scrollHeight>i.clientHeight+r){const e=window.getComputedStyle(i);if("auto"===e.overflowY||"scroll"===e.overflowY||"auto"===e.overflow||"scroll"===e.overflow)return i}if(i.shadowRoot){const e=o(i.shadowRoot,t+1);if(e)return e}}return null},i=o(t,0);return i||(this.doc.documentElement.scrollHeight>this.doc.documentElement.clientHeight?this.doc.documentElement:this.doc.body)}destroy(){this.observerManager.destroy(),this.cache.clear();}},us=[/^flowchart\b/i,/^graph\b/i,/^sequenceDiagram\b/i,/^classDiagram(?:-v2)?\b/i,/^stateDiagram(?:-v2)?\b/i,/^erDiagram\b/i,/^gantt\b/i,/^gitGraph\b/i],hs=[{pattern:/^flow\s*-?\s*chart\b/i,replacement:"flowchart"},{pattern:/^sequence\s*-?\s*diagram\b/i,replacement:"sequenceDiagram"},{pattern:/^class\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"classDiagram-v2"},{pattern:/^class\s*-?\s*diagram\b/i,replacement:"classDiagram"},{pattern:/^state\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"stateDiagram-v2"},{pattern:/^state\s*-?\s*diagram\b/i,replacement:"stateDiagram"},{pattern:/^er\s*-?\s*diagram\b/i,replacement:"erDiagram"},{pattern:/^git\s*-?\s*graph\b/i,replacement:"gitGraph"}];function gs(e){const t="code"===e.nodeName.toLowerCase()?e:e.querySelector("code"),n=[e.getAttribute("data-language"),e.getAttribute("data-test-language"),t?.getAttribute("data-language"),t?.getAttribute("data-test-language"),e.className,t?.className].filter(Boolean).join(" ").toLowerCase();return n.includes("language-mermaid")||n.includes("lang-mermaid")||/\bmermaid\b/.test(n)}function ps(e){const t=ms(e);if(!t)return false;const n=t.split("\n").map(e=>e.trim()).find(e=>e&&!e.startsWith("%%"));return !!n&&us.some(e=>e.test(n))}function ms(e){const t=e.replace(/\r\n/g,"\n").replace(/\n+$/,"").trim();if(!t)return "";const n=t.split("\n"),r=function(e){return e.findIndex(e=>{const t=e.trim();return Boolean(t)&&!t.startsWith("%%")})}(n);if(-1===r)return t;const o=n[r],i=o.trim(),a=o.match(/^\s*/)?.[0]||"";for(const{pattern:s,replacement:l}of hs){const e=i.match(s);if(e)return n[r]=`${a}${l}${i.slice(e[0].length)}`,n.join("\n")}return t}function fs(e){const t="code"===e.nodeName.toLowerCase()?e:e.querySelector("code");return (t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"").trim()||null}function bs(e){const t=e.closest("code-block, ms-code-block, ucs-code-block");if(t)return t;const n=e.closest("pre");if(n)return n;const r=e.closest(".cm-editor, #code-block-viewer");return r||e}function ys(e){const t=ds.query("code-block, ms-code-block, pre, pre code, [data-language], [data-test-language], [data-test-id='code-content'], .cm-content, #code-block-viewer",{parent:e,all:true,shadow:true})||[],n=new Set,r=[];for(const o of t){if(!(o instanceof HTMLElement))continue;if(o.closest(".gh-assistant-mermaid"))continue;const e=bs(o);if(!e||n.has(e))continue;const t=fs(e);t&&((gs(e)||ps(t))&&(n.add(e),r.push({element:e,source:t})));}return r}class vs{textarea=null;_cachedFlutterScrollContainer=null;extractFormulaCopySource(e,t){return null}supportsFormulaCopy(){return true}getSessionId(){const e=window.location.href.split("?")[0].split("/").filter(e=>e);return e.length>0?e[e.length-1]:"default"}supportsNewTab(){return true}getNewTabUrl(){return window.location.origin}supportsTabRename(){return true}getSessionName(){return this.getDocumentConversationTitle()}getDocumentConversationTitle(e=this.getName()){return ja(document.title,{siteName:e})}isNewConversation(){return false}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){const e=this.getSessionId()?.trim();return Boolean(e)&&"default"!==e&&!this.isSharePage()&&!this.isNewConversation()}getCurrentCid(){return null}getConversationList(){return []}getLoadedConversationCount(){return this.getConversationList().length}getCurrentConversationInfo(){const e=this.getSessionId();return !e||"default"===e||this.isNewConversation()?null:{id:e,title:this.getConversationTitle()||this.getSessionName()||"",url:window.location.href,cid:this.getCurrentCid()||void 0}}getSidebarScrollContainer(){return null}getConversationObserverConfig(){return null}navigateToConversation(e,t){return !!t&&(window.location.href=t,true)}async deleteConversationOnSite(e){return {id:e.id,success:false,method:"none",reason:"not_supported"}}async deleteConversationsOnSite(e){const t=[];for(const n of e)t.push(await this.deleteConversationOnSite(n));return t}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!e)return false;let t=this.getLoadedConversationCount(),n=e.scrollHeight,r=0;for(let o=0;o<40;o++){e.scrollTop=e.scrollHeight,e.dispatchEvent(new Event("scroll",{bubbles:true})),await new Promise(e=>setTimeout(e,800));const o=this.getLoadedConversationCount(),i=e.scrollHeight;if(o>t||i>n?(t=Math.max(t,o),n=Math.max(n,i),r=0):r++,r>=4)return true}return false}isGenerating(){return false}requiresDomConfirmationForNetworkGeneration(){return false}getModelName(){return null}getModelLockCheckText(e){return e?.textContent||e?.innerText||""}getNetworkMonitorConfig(){return null}supportsHostThemeSync(){return true}async toggleTheme(e){return false}hasCustomToggleTheme(){return this.toggleTheme!==vs.prototype.toggleTheme}getNativeThemeCss(){return null}getWidthSelectors(){return []}getUserQueryWidthSelectors(){return []}getZenModeConfig(){return null}getCleanModeConfig(){return null}getMarkdownFixerConfig(){return null}getAssistantMermaidSupportMode(){return "native"}getAssistantMermaidBlocks(e){return ys(e)}getSubmitButtonSelectors(){return []}findSubmitButton(e){return null}getSubmitKeyConfig(){return {key:"Enter"}}findTextarea(){for(const e of this.getTextareaSelectors()){const t=document.querySelectorAll(e);for(const e of Array.from(t))if(this.isValidTextarea(e))return this.textarea=e,e}return null}isValidTextarea(e){return !e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&(!Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-"))&&null!==e.offsetParent)}clearTextarea(){this.textarea&&(this.textarea instanceof HTMLInputElement||this.textarea instanceof HTMLTextAreaElement?this.textarea.value="":this.textarea.textContent="",this.textarea.dispatchEvent(new Event("input",{bubbles:true})));}getTextareaElement(){return this.textarea&&this.textarea.isConnected?this.textarea:this.findTextarea()}getScrollContainer(){const e=["infinite-scroller.chat-history",".chat-mode-scroller","main",'[role="main"]',".conversation-container",".chat-container","div.content-container"];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return this._cachedFlutterScrollContainer=null,e}if(this._cachedFlutterScrollContainer&&this._cachedFlutterScrollContainer.isConnected)return this._cachedFlutterScrollContainer;if(this.getSiteId()===ho){const e=document.querySelectorAll('iframe[sandbox*="allow-same-origin"]');for(const n of Array.from(e))try{const e=n.contentDocument||n.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]:not([style*="overflow-x: scroll"])');if(t&&t.scrollHeight>t.clientHeight)return this._cachedFlutterScrollContainer=t,t}}catch(t){console.warn("[Ophel] Failed to access iframe:",t.message);}}return null}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=e.scrollTop,n=this.getChatContentSelectors();if(!n.length)return null;const r=Array.from(e.querySelectorAll(n.join(", ")));if(!r.length)return null;let o=null;for(let i=0;i0&&(o=r[0]),o){const e=t-o.offsetTop,n=o.getAttribute("data-message-id")||o.id;if(n){let t=`[data-message-id="${n}"]`;return o.matches(t)||(t=`#${n}`),{type:"selector",selector:t,offset:e}}{const t=r.indexOf(o);if(-1!==t){return {type:"index",index:t,offset:e,textSignature:(o.textContent||"").trim().substring(0,50)}}}}return null}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}if(n){const r=n.offsetTop+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}return false}getResponseContainerSelector(){return ""}getObserveTarget(){const e=this.getResponseContainerSelector();return e?document.querySelector(e):null}getChatContentSelectors(){return []}getUserQuerySelector(){return null}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()}calculateRangeWordCount(e,t,n){if(!e)return 0;try{const r=document.createRange();if(r.setStartAfter(e),t)r.setEndBefore(t);else {if(!n?.lastChild)return 0;r.setEndAfter(n.lastChild);}return r.toString().trim().length}catch{return 0}}extractUserQueryText(e){return this.extractTextWithLineBreaks(e)}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryText(e)}extractUserQueryExportText(e){return this.extractUserQueryExportContent(e)}replaceUserQueryContent(e,t){return false}extractAssistantResponseText(e){return this.extractTextWithLineBreaks(e)}isInRenderedMarkdownContainer(e){return null!==e.closest(".gh-user-query-markdown")}usesShadowDOM(){return false}extractOutline(e=6,t=false,n=false){return []}getOutlineSources(){return [{id:"conversation",kind:"conversation",label:"对话",available:true}]}supportsDynamicOutlineSources(){return false}getOutlineSourcesSignature(){return this.getOutlineSources().map(e=>`${e.id}:${e.kind}:${e.available}:${e.count??""}`).join("|")}extractOutlineForSource(e,t=6,n=false,r=false){return "conversation"!==e?[]:this.extractOutline(t,n,r)}getInlineBookmarkItems(){return this.extractOutline(6,true,false).filter(e=>e.isUserQuery&&e.element?.isConnected)}findElementByHeading(e,t){const n=document.querySelectorAll(`h${e}`);for(const r of Array.from(n))if(r.textContent?.trim()===t)return r;return null}findUserQueryElement(e,t){const n=this.getUserQuerySelector();if(!n)return null;const r=ds.query(n,{all:true,shadow:true});if(!r||0===r.length)return null;if(r.length>=e){const n=r[e-1],o=this.extractUserQueryText(n);if(o===t||o.startsWith(t)||t.startsWith(o))return n}for(const o of r){const e=this.extractUserQueryText(o);if(e===t||e.startsWith(t)||t.startsWith(e))return o}return null}async resolveOutlineTarget(e,t,n="conversation"){return e.isUserQuery&&0===e.level&&void 0!==t?this.findUserQueryElement(t,e.text):this.findElementByHeading(e.level,e.text)}scrollToOutlineTarget(e){e.scrollIntoView({behavior:"instant",block:"start",__bypassLock:true});}getOutlineScrollContainer(e="conversation"){return this.getScrollContainer()}scrollToOutlineSourceTarget(e,t="conversation"){this.scrollToOutlineTarget(e);}supportsScrollLock(){return false}getExportConfig(){return null}async extractExportMessages(e){return null}async extractExportBundle(e){return null}async createExportBundleFromMessages(e){const t=la(),n=await e(t);return 0===n.length?null:{messages:n,assets:t.assets}}async prepareConversationExport(e){return null}async restoreConversationAfterExport(e,t){}getLatestReplyText(){return null}getLastCodeBlockText(){const e=this.getLatestReplyText(),t=this.extractLastFencedCodeBlockText(e||"");if(t)return t;const n=this.getAssistantResponseElementsForCodeSearch();for(let r=n.length-1;r>=0;r-=1){const e=n[r],t=this.extractLastCodeBlockTextFromDomRoot(e);if(t)return t;const o=this.extractAssistantResponseText(e).trim(),i=this.extractLastFencedCodeBlockText(o);if(i)return i}return 0===n.length?this.extractLastCodeBlockTextFromDomRoot(this.getPrimaryCodeSearchRoot()):null}getNewChatButtonSelectors(){return []}startNewConversation(){const e=this.captureConversationNavigationState(),t=this.findVisibleElementBySelectors(this.getNewChatButtonSelectors());return t?(this.simulateClick(t),window.setTimeout(()=>{this.hasConversationNavigationChanged(e)||this.navigateToNewConversationUrl();},150),true):this.navigateToNewConversationUrl()}getStopButtonSelectors(){return []}stopGeneration(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());return !!e&&(this.simulateClick(e),true)}bindNewChatListeners(e){document.addEventListener("keydown",t=>{t.ctrlKey&&t.shiftKey&&("o"===t.key||"O"===t.key)&&setTimeout(e,500);}),document.addEventListener("click",t=>{const n=this.getNewChatButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)if(o.matches&&o.matches(t))return void setTimeout(e,500)}},true);}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return null}simulateClick(e){e.click();}clickModelSelector(){const e=this.getModelSwitcherConfig("");if(!e||!e.selectorButtonSelectors)return false;const t=this.findElementBySelectors(e.selectorButtonSelectors);return !(!t||null===t.offsetParent)&&(this.simulateClick(t),true)}lockModel(e,t){const n=this.getModelSwitcherConfig(e);if(!n)return;const{targetModelKeyword:r,selectorButtonSelectors:o,menuItemSelector:i,checkInterval:a=1e3,maxAttempts:s=10,menuRenderDelay:l=500,subMenuTriggers:c=[],subMenuSelector:d}=n,u=e=>(e||"").toLowerCase().trim(),h=u(r);let g=0;const p=s,m=setInterval(()=>{g++;const e=this.findElementBySelectors(o);if(e){clearInterval(m);if(u(this.getModelLockCheckText(e)).includes(h))return void(t&&t());this.performMenuSearch(e,h,i,l,c,d,t,s);}else g>=p&&(clearInterval(m),console.warn(`Ophel: Model selector button not found after ${p} attempts.`),this.showModelLockFailure(r,"button_not_found"));},a);}performMenuSearch(e,t,n,r,o,i,a,s=10){this.simulateClick(e);const l=Math.max(3,s);let c=0;const d=()=>{c++;const s=this.getVisibleMenuItems(n,e);if(!(s.length>0))return c>=l?(document.body.click(),console.warn("Ophel: Menu items not found."),void this.showModelLockFailure(t,"menu_empty")):void setTimeout(d,r);this.searchAndSelectModel(s,t,n,r,o,i,a);};setTimeout(d,r);}searchAndSelectModel(e,t,n,r,o,i,a){const s=e=>(e||"").toLowerCase().trim(),l=this.findBestMatchingItem(e,t);if(l)return this.simulateClick(l),void setTimeout(()=>{document.body.click(),a&&a();},100);let c;if(i&&(c=e.find(e=>e.matches(i))),!c&&o.length>0&&(c=e.find(e=>{const t=s(e.textContent||"");return o.some(e=>t.includes(s(e)))})),c)return this.simulateClick(c),void setTimeout(()=>{const e=this.getVisibleMenuItems(n,c),r=this.findBestMatchingItem(e,t);if(r)return this.simulateClick(r),void setTimeout(()=>{document.body.click(),a&&a();},100);document.body.click(),console.warn(`Ophel: Model "${t}" not found in sub-menu.`),this.showModelLockFailure(t,"not_found");},r);document.body.click(),console.warn(`Ophel: Model "${t}" not found in menu.`),this.showModelLockFailure(t,"not_found");}getVisibleMenuItems(e,t){const n=this.getVisibleElementsBySelector(e);if(!t||0===n.length)return n;const r=this.getMenuContainerByAria(t);if(r){const e=n.filter(e=>r.contains(e));if(e.length>0)return e}const o=this.getMenuContainerSelector(),i=new Map;for(const a of n){const e=a.closest(o);if(!e||!this.isElementVisible(e))continue;const t=i.get(e);t?t.push(a):i.set(e,[a]);}if(i.size>0){const e=this.pickBestMenuContainer(t,i);if(e)return i.get(e)||n}return n}getVisibleElementsBySelector(e){return ds.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)})||[]}getMenuContainerByAria(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=`#${this.escapeSelector(t)}`,r=ds.query(n,{shadow:true});return r&&this.isElementVisible(r)?r:null}getMenuContainerSelector(){return ['[role="menu"]','[role="listbox"]',"md-menu-surface",".mdc-menu-surface",".mat-menu-panel",".menu[popover]","[data-radix-popper-content-wrapper]",".cdk-overlay-pane"].join(", ")}pickBestMenuContainer(e,t){const n=e.getBoundingClientRect();let r=null;return t.forEach((e,t)=>{if(0===e.length)return;const o=t.getBoundingClientRect(),i=this.getRectDistance(n,o);(!r||ir.count)&&(r={container:t,distance:i,count:e.length});}),r?r.container:null}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}isElementVisible(e){if(!e)return false;const t=e;if(!t.isConnected)return false;const n=window.getComputedStyle(t);if("none"===n.display||"hidden"===n.visibility||0===parseFloat(n.opacity))return false;const r=t.getBoundingClientRect();return r.width>0&&r.height>0}escapeSelector(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}findBestMatchingItem(e,t){const n=e=>(e||"").toLowerCase().trim();for(const r of e){const e=n(r.textContent||r.innerText||"");if(e.split("\n")[0].trim()===t||e===t)return r}for(const r of e){if(n(r.textContent||r.innerText||"").split("\n")[0].trim().endsWith(t))return r}for(const r of e){if(n(r.textContent||r.innerText||"").includes(t))return r}}async showModelLockFailure(e,t){try{const{showToast:n}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Bi);return {showToast:e}},void 0),{t:r}=await o(async()=>{const{t:e}=await Promise.resolve().then(()=>ue);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=r("modelLockFailedNoButton");break;case "menu_empty":i=r("modelLockFailedMenuEmpty");break;default:i=r("modelLockFailedNotFound").replace("{model}",e);}n(i,3e3);}catch(n){console.error("Ophel: Failed to show toast:",n);}}findElementBySelectors(e){return ds.query(e,{shadow:true})}findAllElementsBySelector(e){return ds.query(e,{all:true,shadow:true})||[]}afterPropertiesSet(e={}){const{modelLockConfig:t}=e;t&&t.enabled&&this.lockModel(t.keyword);}shouldInjectIntoShadow(e){return true}findVisibleElementBySelectors(e){if(0===e.length)return null;const t=ds.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)});for(const n of t||[]){if(!(n instanceof HTMLElement))continue;const e=this.resolveClickableTarget(n);if(e&&this.isElementVisible(e))return e}return null}extractLastFencedCodeBlockText(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDomRoot(e){const t=ds.query("pre code, pre, pre.code-block, .code-block code",{parent:e,all:true,shadow:true,filter:e=>this.shouldIncludeCodeElement(e)})||[];for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"], .gh-copy-btn, [data-testid*="copy"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}getAssistantResponseElementsForCodeSearch(){const e=this.getExportConfig();return e?.assistantResponseSelector&&ds.query(e.assistantResponseSelector,{parent:this.getPrimaryCodeSearchRoot(),all:true,shadow:true,filter:e=>this.shouldIncludeAssistantResponseElement(e)})||[]}getPrimaryCodeSearchRoot(){const e=this.getResponseContainerSelector();if(e){const t=ds.query(e,{shadow:true});if(t)return t}return this.getScrollContainer()||document}resolveClickableTarget(e){return e?e.matches("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")?e:e.closest("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")||e:null}shouldIncludeAssistantResponseElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}shouldIncludeCodeElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}isAssistantMermaidCandidate(e){return gs(e)}extractAssistantMermaidSource(e){return fs(e)}navigateToNewConversationUrl(){const e=this.getNewTabUrl();if(!e)return false;try{const t=new URL(e,window.location.origin).href;return t===window.location.href&&this.isNewConversation()||(window.location.href=t),!0}catch{return window.location.href=e,true}}captureConversationNavigationState(){return {href:window.location.href,sessionId:this.getSessionId(),isNewConversation:this.isNewConversation()}}hasConversationNavigationChanged(e){return window.location.href!==e.href||this.getSessionId()!==e.sessionId||this.isNewConversation()!==e.isNewConversation}}const xs="delete_ui_failed",ws="delete_batch_aborted_after_ui_failure",Ss="delete_api_disabled_unstable",Cs="delete_api_auth_missing",ks="delete_api_key_missing",Ts="delete_api_request_failed",Es="delete_api_not_found_but_visible",As=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","löschen","excluir","hapus","удалить"],Ms=["cancel","取消","キャンセル","취소","annuler","abbrechen","annulla","batal","cancelar","отмена"],Is="/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService",Ls="ms-chat-turn",Ns=".chat-turn-container.model, .model-prompt-container",Rs=".chat-turn-container.model",Ds="ms-thought-chunk",Ps="data-gh-aistudio-export-root",qs="data-gh-aistudio-export-turn",Bs="data-gh-aistudio-export-role",$s="user",_s="assistant",Os=`[${Ps}="1"] [${qs}="1"]`,zs=`[${Ps}="1"] [${Bs}="${$s}"]`,Fs=`[${Ps}="1"] [${Bs}="${_s}"]`,Us="ms-library-table",Hs=['ms-library-table table a[href*="/prompts/"]:not([href*="new_chat"])','ms-library-table .prompt-card a[href*="/prompts/"]:not([href*="new_chat"])'].join(", "),Ws=["ms-library-table .empty-state",'ms-library-table [class*="empty" i]','ms-library-table [class*="no-results" i]','ms-library-table [class*="no-prompts" i]','ms-library-table [data-test-id*="empty" i]','ms-library-table [aria-label*="empty" i]'].join(", ");const js=new Set(["chatglm.cn"]),Gs="share_conversation_id",Vs="SKIN_MODE",Qs={light:"1",dark:"2",system:"3"},Ks=[".userInfoBar-header .me-icon",".userInfoBar-header .me",".userInfoBar-header img.avatar"],Zs=".selecttheme-list",Ys=".conversation-list",Xs=".conversation.question",Js=".question-txt",el=".answer-content-wrap",tl=".answer-content-wrap .markdown-body",nl=[".advance-thinking",".advance-thinking-area",".advanced-thinking",".advanced-thinking-data",".text-advance-thinking-content",".thinking-chain-container",".thinking-block",".thinking-content",".thinking-item","[class*='thinking']","[class*='think']","[class*='reason']","[class*='cot']"].join(", "),rl=[".gh-root",".gh-user-query-markdown",".assistant-name",".interact-container",".code-no-artifacts .top-outer",".code-no-artifacts .copy-button","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),ol=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],il=["#search-input-box textarea",".main-chat-search #search-input-box textarea",".main-chat-search textarea"],al=".enter-icon-container";const sl="ChatGPT",ll=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удалить","excluir"],cl="delete_ui_failed",dl="delete_batch_aborted_after_ui_failure",ul="delete_api_token_missing",hl="delete_api_request_failed",gl="delete_api_not_found_but_visible",pl=new Set(["yaml","yml","json","js","javascript","ts","typescript","py","python","bash","sh","shell","html","css","sql","cpp","c++","c","cs","csharp","java","go","rust","php","rb","ruby","pl","perl","swift","kotlin","scala","xml","md","markdown","diff","dockerfile","ini","toml","powershell","ps1","r","dart","groovy","haskell","lua","objectivec","objc","ocaml","tex","latex","vhdl","verilog","wasm"]),ml=['button[class*="__composer-pill"][aria-haspopup="menu"]'],fl='[data-radix-popper-content-wrapper] [role="menu"][data-radix-menu-content]',bl=`${fl} [data-testid^="model-switcher-"]`,yl="data-gh-chatgpt-export-root",vl="data-gh-chatgpt-export-turn",xl="data-gh-chatgpt-export-role",wl="user",Sl="assistant",Cl=`[${yl}="1"] [${vl}="1"]`,kl=`[${yl}="1"] [${xl}="${wl}"]`,Tl=`[${yl}="1"] [${xl}="${Sl}"]`,El=/^chatgpt-native-user-query::(\d+)::/,Al=/^Prompt\s+\d+$/i;function Ml(e,t=6,n){return Array.from(e.querySelectorAll(function(e=6){const t=Math.min(Math.max(e,1),6);return Array.from({length:t},(e,t)=>`h${t+1}`).join(", ")}(t))).filter(e=>!n?.(e))}function Il(e,t={}){const{maxLevel:n=6,showWordCount:r=false,idPrefix:o,maxTextLength:i,shouldSkipHeading:a,calculateWordCount:s}=t,l=Ml(e,n,a);return l.map((t,n)=>{const a=parseInt(t.tagName.charAt(1),10),c=t.textContent?.trim()||"",d={level:a,text:i&&c.length>i?c.slice(0,i):c,element:t,isTruncated:i?c.length>i:void 0};if(o&&(d.id=`${o}:${a}:${c}:${n}`),r&&s){let r=null;for(let e=n+1;e!r?.(e)).find(e=>e.textContent?.trim()===n)||null}function Nl(e){let t=e?.parentElement||null;for(;t&&t!==document.body;){const e=window.getComputedStyle(t).overflowY;if(t.scrollHeight>t.clientHeight&&("auto"===e||"scroll"===e||"overlay"===e))return t;t=t.parentElement;}return null}function Rl(e,t,n=12){if(!t||t===e)return false;const r=t.getBoundingClientRect(),o=e.getBoundingClientRect();return t.scrollTo({top:t.scrollTop+o.top-r.top-n,behavior:"instant"}),true}const Dl="https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/fonts",Pl=e=>e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),ql=()=>{try{const e=GM_getResourceText("ophelKatexCss");return e?(e=>e.replace(/url\((['"]?)(?!data:|https?:|\/)([^)'"]+)\1\)/g,(e,t,n)=>{const r=String(n).replace(/^\.?\//,"");return `url(${t}${r.startsWith("fonts/")?`${Dl}/${r.slice(6)}`:`${Dl}/${r}`}${t})`}))(e):""}catch(RS){return console.warn("[Ophel] Failed to load KaTeX CSS resource:",RS),""}},Bl=(e,{displayMode:t})=>{const n=e.replace(/\r\n?/g,"\n").trim(),r=(()=>{const e=globalThis.katex;return e&&"function"==typeof e.renderToString?e:null})();if(!r){const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Pl(n)}">${Pl(e)}`}try{const e=r.renderToString(n,{displayMode:t,output:"htmlAndMathml",throwOnError:!1,strict:"ignore",trust:!1}),o=t?"div":"span";return `<${o} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Pl(n)}">${e}`}catch{const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Pl(n)}">${Pl(e)}`}};const $l=(e,t=true,n={})=>function(){const e=globalThis.__OphelMarkdownVendor;if(!e||"function"!=typeof e.renderMarkdown)throw new Error("[Ophel] Markdown vendor runtime is missing");return e}().renderMarkdown(e,t,n),_l=()=>"undefined"==typeof window?"":window.__OPHEL_MARKDOWN_PREVIEW_STYLES__||"",Ol="delete_ui_failed",zl="delete_batch_aborted_after_ui_failure",Fl="delete_api_org_missing",Ul="delete_api_request_failed",Hl="delete_api_not_found_but_visible",Wl=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","elimina","löschen","excluir","hapus","हट","मिट"],jl=["cancel","取消","annuler","abbrechen","annulla","キャンセル","취소","batal","cancelar"],Gl=/^[a-f0-9-]{36}$/i,Vl=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],Ql=[/((^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$))/,/\\\([^\n]+?\\\)/],Kl="document",Zl="#wiggle-file-content",Yl=".standard-markdown, .progressive-markdown",Xl=".artifact-block-cell",Jl='[data-testid="file-thumbnail"]',ec="button[aria-expanded]",tc='span[role="status"][aria-live="polite"]';function nc(){try{const e=localStorage.getItem("LSS-userThemeMode");if(e){const t=JSON.parse(e);if("string"==typeof t.tabId&&t.tabId.trim())return t.tabId}}catch{}return crypto.randomUUID()}function rc(e){const t=e.trim();if(!t)return false;const n=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(t);return /^#{1,6}\s/m.test(t)||/\*\*[^*]+\*\*/.test(t)||new RegExp("(?e.test(n))||Ql.some(e=>e.test(n))}const oc=/\/a\/chat\/s\/([a-z0-9-]+)/i,ic=/\/share\/([a-z0-9-]+)/i,ac="__appKit_@deepseek/chat_themePreference",sc='a[href*="/a/chat/s/"]',lc=".ds-message",cc=`${lc}:has(.ds-markdown)`,dc=".ds-message:not(:has(.ds-markdown))",uc=".ds-think-content",hc=[`${dc} > .gh-inline-bookmark + div`,`${dc} > div:not(.gh-user-query-raw):not(.gh-user-query-markdown):not(.ds-focus-ring)`,`${dc} > div.gh-user-query-markdown`].join(", "),gc="https://chat.deepseek.com/",pc="gh.deepseek.delete.refresh",mc="data-gh-deepseek-export-root",fc="data-gh-deepseek-export-role",bc="user",yc="assistant",vc=`[${mc}="1"] [${fc}="${bc}"]`,xc=`[${mc}="1"] [${fc}="${yc}"]`,wc="M2 4.88",Sc="M8.3125 0.981587C8.66767 1.0545 8.97902 1.20558 9.2627 1.43374C9.48724 1.61438 9.73029 1.85933 9.97949 2.10854L14.707 6.83608L13.293 8.25014L9 3.95717V15.0431H7V3.95717L2.70703 8.25014L1.29297 6.83608L6.02051 2.10854C6.26971 1.85933 6.51277 1.61438 6.7373 1.43374C6.97662 1.24126 7.28445 1.04542 7.6875 0.981587C7.8973 0.94841 8.1031 0.956564 8.3125 0.981587Z",Cc="delete_api_missing_auth_token",kc="delete_api_request_failed",Tc="delete_api_invalid_response",Ec="delete_api_business_failed";const Ac=/^(?:(?:\/code)?\/chat|\/thread)\/([^/?#]+)/,Mc="#flow_chat_sidebar",Ic=`${Mc} [data-history-container="true"]`,Lc=`${Mc} a[id^="conversation_"][href*="/chat/"]`,Nc='[class*="overallTitle-"], [class*="title-"]',Rc=`${Mc} > div:nth-child(2)`,Dc='[class*="v_list_scroller"]',Pc=".v_list_row",qc='[data-target-id="message-box-target-id"]',Bc="[data-message-id].justify-end",$c=".whitespace-pre-wrap.wrap-anywhere:not(.gh-user-query-markdown)",_c=`${Bc} ${$c}`,Oc="[data-message-id]:not(.justify-end)",zc=[".flow-markdown-body",".md-box-root"],Fc=zc.join(", "),Uc=zc.map(e=>`${Oc} ${e}`).join(", "),Hc='[data-plugin-identifier="block_type:2074"]',Wc='[class*="image-wrapper"], [class*="image-box-grid-item"], [class*="image-box-grid"]',jc=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Gc="delete_ui_failed",Vc="delete_batch_aborted_after_ui_failure";const Qc=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createPortal)throw new Error("[Ophel] ReactDOM CDN runtime is missing");return e}(),Kc=Qc.createPortal;Qc.flushSync,Qc.unstable_batchedUpdates,Qc.version;const Zc="ophel-global-tooltip-styles",Yc=8,Xc=10;!function(){if("undefined"==typeof window)return;const e=window;"boolean"!=typeof e.__ophelTooltipSuppressFocusFromWindowRestoration__&&(e.__ophelTooltipSuppressFocusFromWindowRestoration__=false),e.__ophelTooltipWindowFocusListenerRegistered__||(e.__ophelTooltipWindowFocusListenerRegistered__=true,window.addEventListener("focus",()=>{window.__ophelTooltipSuppressFocusFromWindowRestoration__=true,requestAnimationFrame(()=>{window.__ophelTooltipSuppressFocusFromWindowRestoration__=false;});}));}();function Jc(e){if(!e||"undefined"==typeof document)return null;const t=e.getRootNode?.();return t instanceof ShadowRoot?t:document.body}function ed(e){if("undefined"==typeof document||!e||e instanceof ShadowRoot)return;if(document.getElementById(Zc))return;const t=document.createElement("style");t.id=Zc,t.textContent="\n .ophel-tooltip {\n background-color: rgba(30, 30, 35, 0.95);\n color: #ffffff;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n line-height: 1.5;\n z-index: 2147483647;\n pointer-events: none;\n white-space: pre-wrap;\n word-wrap: break-word;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n border: 1px solid rgba(255, 255, 255, 0.1);\n backdrop-filter: blur(4px);\n animation: tooltip-fade-in 0.15s ease-out;\n }\n\n @keyframes tooltip-fade-in {\n from {\n opacity: 0;\n transform: scale(0.95);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n }\n",document.head.appendChild(t);}function td(e,t,n={}){const{preferredPlacement:r="bottom",gap:o=Yc,viewportPadding:i=Xc}=n,a="top"===r?e.top-t.height-o:e.bottom+o,s="top"===r?e.bottom+o:e.top-t.height-o;let l=a;(lwindow.innerHeight-i)&&(l=s),lwindow.innerHeight-i&&(l=Math.max(i,window.innerHeight-t.height-i));let c=e.left+e.width/2-t.width/2;return cwindow.innerWidth-i&&(c=window.innerWidth-t.width-i),{top:l,left:c}}const nd=new class{tooltipEl=null;activeTrigger=null;activeContainer=null;positionOptions={};handleWindowChange=()=>{this.positionTooltip();};handleWindowBlur=()=>{this.hide();};handleVisibilityChange=()=>{document.hidden&&this.hide();};show(e,t,n=260,r={}){if(!t||!e.isConnected)return void this.hide(e);const o=Jc(e);if(!o)return;ed(o),this.activeTrigger&&this.activeTrigger!==e&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=e,this.activeContainer=o,this.positionOptions=r;const i=this.ensureTooltipElement(o);i.textContent=t,i.style.maxWidth="number"==typeof n?`${n}px`:n,i.style.opacity="0",e.setAttribute("aria-describedby",i.id),this.attachGlobalListeners(),this.positionTooltip();}hide(e){e&&this.activeTrigger&&e!==this.activeTrigger||(this.activeTrigger&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=null,this.positionOptions={},this.detachGlobalListeners(),this.tooltipEl?.parentNode&&this.tooltipEl.parentNode.removeChild(this.tooltipEl));}ensureTooltipElement(e){return this.tooltipEl||(this.tooltipEl=document.createElement("div"),this.tooltipEl.className="ophel-tooltip",this.tooltipEl.id=`ophel-tooltip-${Math.random().toString(36).slice(2,9)}`,this.tooltipEl.setAttribute("role","tooltip"),this.tooltipEl.style.position="fixed",this.tooltipEl.style.top="0",this.tooltipEl.style.left="0",this.tooltipEl.style.pointerEvents="none",this.tooltipEl.style.zIndex="2147483647"),this.tooltipEl.parentNode===e&&this.tooltipEl.isConnected||e.appendChild(this.tooltipEl),this.tooltipEl}positionTooltip(){if(!this.tooltipEl||!this.activeTrigger||!this.tooltipEl.isConnected)return;const e=this.activeTrigger.getBoundingClientRect(),t=this.tooltipEl.getBoundingClientRect(),{top:n,left:r}=td(e,t,this.positionOptions);this.tooltipEl.style.top=`${n}px`,this.tooltipEl.style.left=`${r}px`,this.tooltipEl.style.opacity="1";}attachGlobalListeners(){window.addEventListener("scroll",this.handleWindowChange,true),window.addEventListener("resize",this.handleWindowChange),window.addEventListener("blur",this.handleWindowBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange);}detachGlobalListeners(){window.removeEventListener("scroll",this.handleWindowChange,true),window.removeEventListener("resize",this.handleWindowChange),window.removeEventListener("blur",this.handleWindowBlur),document.removeEventListener("visibilitychange",this.handleVisibilityChange);}};function rd(e,t){let n=null;const r=()=>{n&&(clearTimeout(n),n=null);},o=()=>{r(),nd.hide(e);},i=()=>{var o;(r(),"function"==typeof(o=t.disabled)?o():Boolean(o))||(n=setTimeout(()=>{if(!e.isConnected)return;const n=t.getContent();nd.show(e,n,t.maxWidth??260,t);},t.delay??300));};return e.addEventListener("mouseenter",i),e.addEventListener("mouseleave",o),e.addEventListener("focus",i),e.addEventListener("blur",o),e.addEventListener("pointerdown",o),e.addEventListener("click",o),{hide:o,destroy:()=>{e.removeEventListener("mouseenter",i),e.removeEventListener("mouseleave",o),e.removeEventListener("focus",i),e.removeEventListener("blur",o),e.removeEventListener("pointerdown",o),e.removeEventListener("click",o),o();}}}const od=({content:e,children:t,maxWidth:n=260,delay:r=300,className:o="",triggerClassName:i="",triggerStyle:a={},disabled:s=false})=>{const[l,c]=_(false),[d,u]=_({top:0,left:0}),[h,g]=_(false),[p,m]=_(false),[f,b]=_(null),y=$(null),v=$(null),x=$(null),w=$(false),S=E(()=>{w.current=false,x.current&&(clearTimeout(x.current),x.current=null),c(false),g(false),m(false);},[]),C=E(()=>{w.current=true,s||(x.current&&clearTimeout(x.current),m(true),x.current=setTimeout(()=>{x.current=null,m(false),!document.hidden&&w.current&&(c(true),g(true));},r));},[r,s]),k=E(()=>{ true!==window.__ophelTooltipSuppressFocusFromWindowRestoration__&&C();},[C]),T=E(()=>{const e=y.current?.getBoundingClientRect(),t=v.current?.getBoundingClientRect();e&&t&&u(td(e,t,{preferredPlacement:"bottom"}));},[]);return L(()=>{if(y.current){const e=Jc(y.current);b(e),ed(e);}},[]),L(()=>{(l||h)&&y.current&&(T(),h&&g(false));},[e,h,l,T]),L(()=>{if(!l&&!h)return;const e=()=>{T();};return window.addEventListener("scroll",e,true),window.addEventListener("resize",e),()=>{window.removeEventListener("scroll",e,true),window.removeEventListener("resize",e);}},[h,l,T]),L(()=>{if(!p&&!l&&!h)return;const e=()=>{document.hidden&&S();};return window.addEventListener("blur",S),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",S),document.removeEventListener("visibilitychange",e);}},[p,S,h,l]),L(()=>()=>{x.current&&clearTimeout(x.current);},[]),L(()=>{s?S():w.current&&(x.current&&clearTimeout(x.current),m(true),x.current=setTimeout(()=>{x.current=null,m(false),!document.hidden&&w.current&&(c(true),g(true));},r));},[r,s,S]),De("div",{ref:y,className:`ophel-tooltip-trigger ${o} ${i}`,onMouseEnter:C,onMouseLeave:S,onFocus:k,onBlur:S,style:{display:"inline-flex",...a},children:[t,l&&e&&f&&Kc( Re("div",{ref:v,className:"ophel-tooltip",style:{position:"fixed",top:d.top,left:d.left,maxWidth:n,opacity:h?0:1},children:e}),f)]})},id="http://www.w3.org/2000/svg";function ad(e,t={}){const n=document.createElementNS(id,e);for(const[r,o]of Object.entries(t))n.setAttribute(r,o);return n}function sd(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=ad("svg",{xmlns:id,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=ad("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),a=ad("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"});return o.appendChild(i),o.appendChild(a),o}function ld(e,t={}){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=ad("svg",{xmlns:id,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=ad("polyline",{points:"20 6 9 17 4 12"});return o.appendChild(i),o}({...t,color:"#22c55e"})),setTimeout(()=>{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(sd(t));},1500);}function cd(e,t={}){e.querySelectorAll(".gh-code-copy-btn, .gh-table-copy-btn").forEach(e=>{if(!e.querySelector("svg")){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(sd(t));}});}const dd="CHECK_PERMISSION",ud="CHECK_PERMISSIONS",hd="REQUEST_PERMISSIONS",gd="CLEAR_ALL_DATA",pd="RESTORE_DATA";function md(e){return chrome.runtime.sendMessage(e)}const fd="GH_MONITOR_INIT",bd="GH_MONITOR_START",yd="GH_MONITOR_COMPLETE",vd="OPHEL_GEMINI_MYSTUFF_SYNC_REQUEST",xd="OPHEL_GEMINI_MYSTUFF_CACHE_SYNC",wd="OPHEL_EXTENSION_UPDATE_AVAILABLE";let Sd=null,Cd=null,kd=false;function Td(){if("undefined"==typeof window)return null;const e=window.trustedTypes;return e?.createPolicy?e:null}function Ed(e){return `ophel-userscript-${e}-${Math.random().toString(36).slice(2,8)}`}function Ad(e){if(Sd||function(){if(Sd)return true;const e=Td();if(!e)return false;try{return Sd=e.createPolicy(Ed("html"),{createHTML:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types policy:",t),false}}(),Sd)try{return Sd.createHTML(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe HTML:",t);}return e}function Md(e,t){try{const n=Ad(t);return e.innerHTML=n,!0}catch(n){return console.warn("[TrustedTypes] Failed to set innerHTML:",n),false}}function Id(e){if(Cd||function(){if(Cd)return true;const e=Td();if(!e)return false;try{return Cd=e.createPolicy(Ed("script-url"),{createScriptURL:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types script URL policy:",t),false}}(),Cd)try{return Cd.createScriptURL(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe script URL:",t);}return e}function Ld(e,t){let n=null;const r=t=>{if(!Reflect.set(e,"src",t))throw new Error("Trusted Types prevented script src assignment")};try{return r(Id(t)),!0}catch(o){n=o;}if(function(){if(kd)return true;const e=Td();if(!e)return false;try{return e.createPolicy("default",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}),kd=!0,!0}catch(o){const t=o instanceof Error?o.message:String(o);return /default/i.test(t)&&/already exists/i.test(t)?(kd=true,true):(console.warn("[TrustedTypes] Failed to create default Trusted Types policy:",o),false)}}())try{return r(t),!0}catch(o){n=o;}return console.warn("[TrustedTypes] Failed to set script src:",n),false}function Nd(e){return e instanceof Error?e.message||"Unknown watermark processing error":"string"==typeof e&&e.trim()?e.trim():"Unknown watermark processing error"}function Rd(e){return "undefined"!=typeof ImageData&&e instanceof ImageData?e:new ImageData(new Uint8ClampedArray(e.data),e.width,e.height)}function Dd(e){return "googleusercontent.com"===e||e.endsWith(".googleusercontent.com")}function Pd(e){return /=(?:d|d-I)$/i.test(e||"")}function qd(e){if(!e)return null;const t=e.split("/").filter(Boolean)[0]||"";if(!t)return null;if(t.startsWith("rd-")){const e=t.slice(3),n=e.endsWith("-dl");return {family:"rd",variant:n?e.slice(0,-3):e,isPreview:false,isDownload:n}}if("gg"===t)return {family:"gg",variant:"",isPreview:true,isDownload:false};if(!t.startsWith("gg-"))return null;const n=t.slice(3),r="dl"===n||n.endsWith("-dl");return {family:"gg",variant:r?"dl"===n?"":n.slice(0,-3):n,isPreview:!r,isDownload:r}}function Bd(e){if(!e)return null;try{const t=new URL(e);return Dd(t.hostname)?qd(t.pathname):null}catch{return null}}function $d(e){return null!==Bd(e)}function _d(e){if(!e)return false;try{const t=new URL(e);if(!Dd(t.hostname))return !1;const n=qd(t.pathname);return !(!n||"gg"!==n.family)&&(n.isPreview?!Pd(t.pathname):!Pd(t.pathname)&&(n.isDownload&&/-rj$/i.test(t.pathname)))}catch{return false}}function Od(e){if(!$d(e))return e;try{const t=new URL(e),n=t.pathname,r=/=w\d+-h\d+([^/]*)$/i;if(r.test(n))return t.pathname=n.replace(r,"=s0$1"),t.toString();if(Pd(n))return t.pathname=n.replace(/=(?:d|d-I)$/i,e=>`=s0-${e.slice(1)}`),t.toString();const o=/=(?:s|w|h)\d+([^/]*)$/i;return o.test(n)?(t.pathname=n.replace(o,"=s0$1"),t.toString()):(t.pathname=`${n}=s0`,t.toString())}catch{return e}}const zd="ophel-watermark-loading-style",Fd="watermark-not-detected",Ud=["[data-image-attachment-index]","single-image.generated-image","generated-image",".generated-image-container",".image-container.replace-fife-images-at-export"].join(", ");class Hd{static activeInstance=null;processingQueue=new Set;processingMap=new Map;processedDataUrlCache=new Map;skippedSourceCache=new Set;enabled=false;stopObserver=null;mainWorldMessageListener=null;actionButtonListener=null;userscriptOriginalFetch=null;constructor(){this.processingQueue=new Set,this.processingMap=new Map,this.processedDataUrlCache=new Map,this.skippedSourceCache=new Set;}static getActiveInstance(){return Hd.activeInstance}start(){this.enabled||(this.enabled=true,Hd.activeInstance=this,this.enableUserscriptFetchInterception(),this.processExistingImages(),this.startObserver());}stop(){this.enabled&&(this.enabled=false,this.disableUserscriptFetchInterception(),this.teardownActionButtonInterception(),this.processingMap.clear(),this.processingQueue.clear(),this.skippedSourceCache.clear(),this.clearAllProcessingIndicators(),this.removeProcessingIndicatorStyles(),Hd.activeInstance===this&&(Hd.activeInstance=null),this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}isGeminiStandardSite(){return "gemini.google.com"===window.location.hostname}shouldInterceptGeminiImageUrl(e){return $d(e)}isLikelyGeneratedImage(e){const t=e.currentSrc||e.src||"";if(!t)return false;const n=e.naturalWidth||e.width||0,r=e.naturalHeight||e.height||0;return !(n<192||r<192)&&(this.shouldInterceptGeminiImageUrl(t)||t.startsWith("data:image/")||t.startsWith("blob:"))}isSupportedGeminiImageSource(e){return !!e&&(this.shouldInterceptGeminiImageUrl(e)||e.startsWith("data:image/")||e.startsWith("blob:"))}getImageSourceForAction(e){const t=e.getAttribute("data-ophel-wm-source")||"";if(t)return t;return e.currentSrc||e.src||""}normalizePossibleUrl(e){if(!e)return "";if(e.startsWith("data:image/")||e.startsWith("blob:"))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}shouldSkipAutoProcessingSource(e){return !(!e.startsWith("blob:")&&!e.startsWith("data:image/"))&&this.isGeminiStandardSite()}ensureProcessingIndicatorStyles(){if(document.getElementById(zd))return;if(!document.head)return;const e=document.createElement("style");e.id=zd,e.textContent='\n [data-ophel-wm-loading="1"] {\n isolation: isolate;\n }\n\n .ophel-wm-loading-indicator {\n position: absolute;\n bottom: 20px;\n right: 20px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: 999px;\n background: rgba(15, 23, 42, 0.72);\n box-shadow: 0 10px 24px rgba(15, 23, 42, 0.22);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n pointer-events: none;\n z-index: 2;\n }\n\n .ophel-wm-loading-indicator::after {\n content: "";\n width: 12px;\n height: 12px;\n border-radius: 50%;\n border: 2px solid rgba(255, 255, 255, 0.35);\n border-top-color: rgba(255, 255, 255, 1);\n animation: ophel-wm-loading-spin 0.72s linear infinite;\n }\n\n @keyframes ophel-wm-loading-spin {\n from {\n transform: rotate(0deg);\n }\n\n to {\n transform: rotate(360deg);\n }\n }\n ',document.head.appendChild(e);}removeProcessingIndicatorStyles(){document.getElementById(zd)?.remove();}findProcessingIndicatorHost(e){const t=e.closest(Ud);return t instanceof HTMLElement?t:e.parentElement instanceof HTMLElement?e.parentElement:e}restoreProcessingIndicatorHost(e){e.removeAttribute("data-ophel-wm-loading"),e.removeAttribute("data-ophel-wm-loading-count"),e.querySelector(".ophel-wm-loading-indicator")?.remove(),"1"===e.dataset.ophelWmLoadingManagedPosition&&(e.style.position=e.dataset.ophelWmLoadingOriginalPosition||"",delete e.dataset.ophelWmLoadingManagedPosition,delete e.dataset.ophelWmLoadingOriginalPosition);}showImageProcessingIndicator(e){const t=this.findProcessingIndicatorHost(e);if(!t)return null;this.ensureProcessingIndicatorStyles();const n=Number(t.dataset.ophelWmLoadingCount||"0");if(n<=0){"static"===window.getComputedStyle(t).position&&(t.dataset.ophelWmLoadingManagedPosition="1",t.dataset.ophelWmLoadingOriginalPosition=t.style.position||"",t.style.position="relative"),t.setAttribute("data-ophel-wm-loading","1");const e=document.createElement("div");e.className="ophel-wm-loading-indicator",e.setAttribute("aria-hidden","true"),e.title=le("watermarkProcessing"),t.appendChild(e);}return t.dataset.ophelWmLoadingCount=String(Math.max(0,n)+1),t}hideImageProcessingIndicator(e){if(!e)return;const t=Number(e.dataset.ophelWmLoadingCount||"0");t>1?e.dataset.ophelWmLoadingCount=String(t-1):this.restoreProcessingIndicatorHost(e);}clearAllProcessingIndicators(){document.querySelectorAll('[data-ophel-wm-loading="1"]').forEach(e=>{this.restoreProcessingIndicatorHost(e);});}getCurrentImageSource(e){return e.currentSrc||e.src||""}getComparableProcessingSource(e){return e?this.shouldInterceptGeminiImageUrl(e)?this.replaceWithNormalSize(e):e:""}resetProcessedImageStateIfSourceChanged(e,t){if("1"===e.getAttribute("data-ophel-wm-processed")&&t.startsWith("data:image/"))return;const n=this.getComparableProcessingSource(t),r=e.getAttribute("data-ophel-wm-source")||"",o=e.getAttribute("data-ophel-wm-skip-source")||"";r&&r!==n&&(e.removeAttribute("data-ophel-wm-source"),e.removeAttribute("data-ophel-wm-processed"),delete e.dataset.watermarkProcessed),o&&o!==n&&(e.removeAttribute("data-ophel-wm-skip-source"),delete e.dataset.watermarkProcessed);}getRemoteSkippedSourceCacheKey(e,t){return `${t}:${e}`}extractSupportedUrlFromNode(e){const t=[],n=[],r=[],o=e=>{if(!e)return;const o=this.normalizePossibleUrl(e);this.isSupportedGeminiImageSource(o)&&(this.shouldInterceptGeminiImageUrl(o)?t.push(o):o.startsWith("blob:")?n.push(o):o.startsWith("data:image/")&&r.push(o));const i=e.match(/https?:\/\/[^\s"'<>]*googleusercontent\.com[^\s"'<>]*/gi);if(i&&0!==i.length)for(const n of i){const e=this.normalizePossibleUrl(n);this.shouldInterceptGeminiImageUrl(e)&&t.push(e);}};for(const i of Array.from(e.attributes))o(i?.value||"");return e instanceof HTMLAnchorElement&&e.href&&o(e.href),e instanceof HTMLImageElement&&o(e.currentSrc||e.src||""),t[0]||n[0]||r[0]||""}getRequestUrl(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"url"in e){const t=e;if("string"==typeof t.url)return t.url}return ""}toggleMainWorldFetchInterception(e){this.isGeminiStandardSite()&&window.postMessage({type:"OPHEL_WATERMARK_FETCH_TOGGLE",enabled:e},"*");}setupMainWorldBridge(){!this.mainWorldMessageListener&&this.isGeminiStandardSite()&&(this.mainWorldMessageListener=e=>{if(e.source!==window)return;const t=e.data;if(!t||"OPHEL_WATERMARK_PROCESS_REQUEST"!==t.type)return;const n=t.requestId||"",r=t.url||"",o=t.arrayBuffer,i=t.mimeType||"";n&&r&&this.handleMainWorldProcessRequest(n,r,o,i);},window.addEventListener("message",this.mainWorldMessageListener));}teardownMainWorldBridge(){this.mainWorldMessageListener&&(window.removeEventListener("message",this.mainWorldMessageListener),this.mainWorldMessageListener=null);}postMainWorldProcessResponse(e){window.postMessage({type:"OPHEL_WATERMARK_PROCESS_RESPONSE",...e},"*");}async handleMainWorldProcessRequest(e,t,n,r){if(!this.enabled||!this.shouldInterceptGeminiImageUrl(t))return void this.postMainWorldProcessResponse({requestId:e,success:false,error:"Watermark interceptor disabled"});const o=this.replaceWithNormalSize(t);try{const t=n?new Blob([n],{type:r||"image/png"}):void 0,i=t?await this.processFetchBlobToDataUrl(t,o):await this.getProcessedDataUrl(o,{scene:"fetch"});this.postMainWorldProcessResponse({requestId:e,success:!0,dataUrl:i});}catch(RS){this.postMainWorldProcessResponse({requestId:e,success:false,error:RS instanceof Error?RS.message:"Unknown processing error"});}}getUserscriptPageWindow(){return "undefined"!=typeof unsafeWindow&&unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}buildFetchArgsWithSourceUrl(e,t,n){const r=[...e],o=r[0];if("string"==typeof o)return r[0]=t,r;const i=n.Request||("undefined"!=typeof Request?Request:null);if(i&&o&&"object"==typeof o&&"url"in o)try{return r[0]=new i(t,o),r}catch{return r[0]=t,r}return r[0]=t,r}enableUserscriptFetchInterception(){if(this.userscriptOriginalFetch||!this.isGeminiStandardSite())return;const e=this.getUserscriptPageWindow();this.userscriptOriginalFetch=e.fetch.bind(e),e.fetch=async(...t)=>{const n=this.getRequestUrl(t[0]);if(!this.enabled||!n||!this.shouldInterceptGeminiImageUrl(n))return this.userscriptOriginalFetch(...t);const r=this.replaceWithNormalSize(n),o=this.buildFetchArgsWithSourceUrl(t,r,e);let i=null,a=null;try{if(i=await this.userscriptOriginalFetch(...o),!i.ok)return i;a=await i.blob();const e=await this.processFetchBlobToDataUrl(a,r),t=await this.dataUrlToBlob(e);return new Response(t,{status:i.status,statusText:i.statusText,headers:new Headers({"Content-Type":t.type||"image/png"})})}catch{return i&&a?new Response(a,{status:i.status,statusText:i.statusText,headers:i.headers}):this.userscriptOriginalFetch(...t)}};}disableUserscriptFetchInterception(){if(!this.userscriptOriginalFetch)return;this.getUserscriptPageWindow().fetch=this.userscriptOriginalFetch,this.userscriptOriginalFetch=null;}setupActionButtonInterception(){!this.actionButtonListener&&this.isGeminiStandardSite()&&(this.actionButtonListener=e=>{this.handleActionButtonClick(e);},document.addEventListener("click",this.actionButtonListener,true));}teardownActionButtonInterception(){this.actionButtonListener&&(document.removeEventListener("click",this.actionButtonListener,true),this.actionButtonListener=null);}isActionButtonElement(e,t){const n=[e.getAttribute("aria-label")||"",e.getAttribute("data-tooltip")||"",e.getAttribute("mattooltip")||"",e.getAttribute("title")||"",(e.textContent||"").trim()].join(" ").trim().trim().toLowerCase();return "copy"===t?n.includes("copy")||n.includes("copy image")||n.includes("copy full")||n.includes("复制")||n.includes("複製"):n.includes("download")||n.includes("save image")||n.includes("full size")||n.includes("下载")||n.includes("下載")}findImageAction(e){const t=("function"==typeof e.composedPath?e.composedPath():[]).filter(e=>e instanceof Element),n=e.target instanceof Element?e.target:null,r=[];if(n){const e=n.closest("button,[role='button']");e&&r.push(e);}for(const i of t)i instanceof HTMLElement&&(i.matches("button")||"button"===i.getAttribute("role"))&&r.push(i);const o=Array.from(new Set(r));if(0===o.length)return null;for(const i of o){if(this.isActionButtonElement(i,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(i,"download"))return {action:"download",button:i};for(const e of Array.from(i.querySelectorAll("[aria-label],[data-tooltip],[mattooltip]"))){if(this.isActionButtonElement(e,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(e,"download"))return {action:"download",button:i}}}return null}findRelatedGeminiImage(e){let t=e;for(let a=0;a<6&&t;a++){const e=Array.from(t.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}t=t.parentElement;}const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2,i=document.elementFromPoint(r,o)?.closest("generated-image, .generated-image-container");if(i){const e=Array.from(i.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findBestVisibleGeminiImage(){const e=Array.from(document.querySelectorAll("img")).filter(e=>!!this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(this.getImageSourceForAction(e))).filter(e=>{const t=e.getBoundingClientRect();return t.width>120&&t.height>120&&t.bottom>0&&t.right>0});return 0===e.length?null:(e.sort((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return r.width*r.height-n.width*n.height}),e[0]||null)}findRelatedGeminiImageFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];for(const n of t){if(!(n instanceof Element))continue;if(n instanceof HTMLImageElement){const e=this.getImageSourceForAction(n);if(this.isValidGeminiImage(n)&&this.isSupportedGeminiImageSource(e))return n}const e=Array.from(n.querySelectorAll?.("img")||[]);for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findGeminiSourceUrlFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];let n="",r="";for(const o of t){if(!(o instanceof Element))continue;const e=this.extractSupportedUrlFromNode(o);if(e){if(this.shouldInterceptGeminiImageUrl(e))return e;!n&&e.startsWith("blob:")&&(n=e),!r&&e.startsWith("data:image/")&&(r=e);}}return n||r||""}async resolveActionDataUrl(e,t="display"){return e.startsWith("data:image/")?e:e.startsWith("blob:")?this.processImageSourceToDataUrl(e,{scene:t}):this.getProcessedDataUrl(e,{scene:t})}async resolveProcessedImageDataUrl(e,t){const n=this.normalizePossibleUrl(e);if(!n||!this.isSupportedGeminiImageSource(n))return null;try{return n.startsWith("data:image/")||n.startsWith("blob:")?await this.resolveActionDataUrl(n,t?.scene??"export"):await this.getProcessedDataUrl(n,{bypassCache:t?.bypassCache,requireNonPreviewSource:t?.requireNonPreviewSource,scene:t?.scene??"export"})}catch(RS){return RS instanceof Error&&RS.message,null}}async writeImageToClipboard(e){const t=await this.dataUrlToBlob(e);if("undefined"==typeof ClipboardItem||!navigator.clipboard?.write)throw new Error("Clipboard API unavailable");const n=new ClipboardItem({[t.type||"image/png"]:t});await navigator.clipboard.write([n]);}triggerDownloadFromDataUrl(e){const t=document.createElement("a");t.href=e,t.download=`gemini-image-${Date.now()}.png`,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove();}shouldUseNativeGeminiAction(){return null!==this.userscriptOriginalFetch}async resolveProcessedDataUrlForAction(e,t){if(e.startsWith("data:image/"))return e;if(e.startsWith("blob:"))return this.resolveActionDataUrl(e,t);try{return await this.getProcessedDataUrl(e,{bypassCache:!0,requireNonPreviewSource:!0,scene:t})}catch(RS){const r=RS instanceof Error?RS.message:"";if("copy"===t&&"fullsize-source-unavailable"===r)return this.getProcessedDataUrl(e,{bypassCache:true,requireNonPreviewSource:false,scene:t});throw RS}}async handleActionButtonClick(e){if(!this.enabled||!this.isGeminiStandardSite())return;const t=this.findImageAction(e);if(!t)return;if(this.shouldUseNativeGeminiAction())return;const n=this.findRelatedGeminiImageFromEvent(e)||this.findRelatedGeminiImage(t.button)||this.findBestVisibleGeminiImage(),r=this.findGeminiSourceUrlFromEvent(e)||(n?this.getImageSourceForAction(n):"");if(!r)return;if(!this.isSupportedGeminiImageSource(r))return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const o=n?this.showImageProcessingIndicator(n):null;try{const e=await this.resolveProcessedDataUrlForAction(r,t.action);if(!e)return;n&&n.setAttribute("data-ophel-wm-processed","1"),"copy"===t.action?await this.writeImageToClipboard(e):this.triggerDownloadFromDataUrl(e);}catch{return}finally{this.hideImageProcessingIndicator(o);}}loadImageFromSource(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e;})}async dataUrlToBlob(e){const t=e.match(/^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,([\s\S]*)$/i);if(!t)throw new Error("Invalid data URL");const n=t[1]||"application/octet-stream",r=!!t[2],o=t[3]||"";if(!r)return new Blob([decodeURIComponent(o)],{type:n});const i=o.replace(/\s+/g,""),a=atob(i),s=new Uint8Array(a.length);for(let l=0;l{e&&(n.includes(e)||n.push(e));},o=e=>{for(const t of (e=>{const t=Od(e),n=e.search(/[?#]/),r=-1===n?e.length:n,o=e.lastIndexOf("/",r),i=e.lastIndexOf("=",r);if(-1===i||i{const t=e.toLowerCase();return !/^s\d+$/.test(t)&&!/^w\d+$/.test(t)&&!/^h\d+$/.test(t)}),l=s.filter(e=>"d"!==e.toLowerCase()),c=s.filter(e=>"rj"!==e.toLowerCase()),d=l.filter(e=>"rj"!==e.toLowerCase()),u=s.some(e=>"d"===e.toLowerCase()),h=s.some(e=>"rj"===e.toLowerCase()),g=[["s0",...s],u?["s0",...l]:["s0","d",...s],...h?[["s0",...c],u?["s0",...d]:["s0","d",...d]]:[]],p=[];p.includes(t)||p.push(t);for(const m of g){const t=m.join("-"),n=`${e.slice(0,i+1)}${t}${e.slice(r)}`;p.includes(n)||p.push(n);}return p})(e))r(t);},i=e=>{o(((e,t)=>{if(!t)return e;try{const n=new URL(e),r=n.pathname.split("/"),o=r.findIndex(Boolean);return -1===o?e:(r[o]=t,n.pathname=r.join("/"),n.toString())}catch{return e}})(t,e));},a=Bd(t);if(a){const e=(e=>{try{return new URL(e).pathname.split("/").filter(Boolean)[0]||""}catch{return ""}})(t);if("gg"===a.family){const t=a.variant?`gg-${a.variant}`:"gg",r=a.variant?`gg-${a.variant}-dl`:"gg-dl",o=a.variant?`rd-gg-${a.variant}`:"rd-gg",s=`${o}-dl`;return a.isPreview?(i(s),i(o),i(r),i(t),n):(i(e||r),i(s),i(o),i(t),n)}const r=`rd-${a.variant}`,o=`${r}-dl`,l=(s=a.variant)?"gg"===s||s.startsWith("gg-")?s:`gg-${s}`:"gg",c="gg"===l?"gg-dl":`${l}-dl`;return i(e||(a.isDownload?o:r)),i(a.isDownload?r:o),i(c),i(l),n}var s;return t.includes("/gg/")?(o(t.replace("/gg/","/rd-gg-dl/")),o(t.replace("/gg/","/rd-gg/")),o(t),n):t.includes("/rd-gg/")?(o(t),o(t.replace("/rd-gg/","/rd-gg-dl/")),o(t.replace("/rd-gg/","/gg/")),n):t.includes("/rd-gg-dl/")?(o(t),o(t.replace("/rd-gg-dl/","/rd-gg/")),o(t.replace("/rd-gg-dl/","/gg/")),n):(o(t),n)}async fetchOriginalBlobSingle(e){return async function(e){return new Promise((t,n)=>{GM_xmlhttpRequest({method:"GET",url:e,headers:{Referer:"https://gemini.google.com/",Origin:"https://gemini.google.com"},responseType:"blob",onload:e=>{e.status>=200&&e.status<300?t(e.response):n(new Error(`HTTP ${e.status}`));},onerror:e=>n(new Error(e?.message||"GM_xmlhttpRequest failed"))});})}(e)}async fetchOriginalBlob(e,t){const n=this.shouldInterceptGeminiImageUrl(e)?this.buildRemoteFetchCandidates(e):[e];let r=null;for(const o of n)try{const e=await this.fetchOriginalBlobSingle(o);if(t?.requireNonPreviewSource&&_d(o))throw new Error("fullsize-source-unavailable");return e}catch(RS){r=RS;}throw r instanceof Error?r:new Error("Failed to fetch original image")}async processLoadedImageToDataUrl(e,n,r){const o=document.createElement("canvas");o.width=e.width,o.height=e.height;const i=o.getContext("2d");if(!i)throw new Error("Could not get canvas context");i.drawImage(e,0,0);const a=function(e,n={}){try{const r=geminiWatermarkRemover.removeWatermarkFromImageDataSync(e,{adaptiveMode:n.adaptiveMode??"always",maxPasses:n.maxPasses??4}),o=r.meta,i={meta:o,sourceUrl:n.sourceUrl,scene:n.scene};return function(e){return !(!e||!0!==e.applied||e.skipReason||"insufficient"===e.decisionTier)}(o)?{status:"removed",imageData:Rd(r.imageData),decision:i}:{status:"skipped",reason:o.skipReason?"invalid-candidate":"not-banana",decision:i}}catch(RS){return {status:"failed",error:Nd(RS)}}}(i.getImageData(0,0,o.width,o.height),{sourceUrl:n,scene:r?.scene??"display",adaptiveMode:"always",maxPasses:4});if("skipped"===a.status)throw new Error(Fd);if("failed"===a.status)throw new Error(a.error);return i.putImageData(a.imageData,0,0),o.toDataURL("image/png")}async processImageSourceToDataUrl(e,t){const n=await this.loadImageFromSource(e);return this.processLoadedImageToDataUrl(n,e,t)}async processImageBlobToDataUrl(e,t,n){const r=URL.createObjectURL(e);try{const e=await this.loadImageFromSource(r);return await this.processLoadedImageToDataUrl(e,t,n)}finally{URL.revokeObjectURL(r);}}async processFetchBlobToDataUrl(e,t){const n=this.replaceWithNormalSize(t),r=this.getRemoteSkippedSourceCacheKey(n,"fetch");this.throwIfSourceSkipped(r);try{return await this.processImageBlobToDataUrl(e,n,{scene:"fetch"})}catch(RS){throw RS instanceof Error&&RS.message===Fd&&this.rememberSkippedSource(r),RS}}async getProcessedDataUrl(e,t){const n=this.replaceWithNormalSize(e),r=this.getRemoteSkippedSourceCacheKey(n,t?.scene??"download");if(!t?.bypassCache){const e=this.processedDataUrlCache.get(n);if(e)return e}if(this.throwIfSourceSkipped(r),!t?.bypassCache){const e=this.processingMap.get(n);if(e)return e}const o=(async()=>{try{const e=await this.fetchOriginalBlob(n,{requireNonPreviewSource:t?.requireNonPreviewSource}),r=await this.processImageBlobToDataUrl(e,n,{scene:t?.scene??"download"});return t?.bypassCache||(this.processedDataUrlCache.set(n,r),this.trimProcessedDataUrlCache()),r}catch(RS){throw RS instanceof Error&&RS.message===Fd&&this.rememberSkippedSource(r),RS}})();if(!t?.bypassCache){this.processingMap.set(n,o);try{return await o}finally{this.processingMap.delete(n);}}return o}trimProcessedDataUrlCache(){if(this.processedDataUrlCache.size<=100)return;const e=this.processedDataUrlCache.keys().next().value;e&&this.processedDataUrlCache.delete(e);}rememberSkippedSource(e){if(!e)return;if(this.processedDataUrlCache.has(e))return;if(this.skippedSourceCache.add(e),this.skippedSourceCache.size<=120)return;const t=this.skippedSourceCache.keys().next().value;t&&this.skippedSourceCache.delete(t);}throwIfSourceSkipped(e){if(!this.processedDataUrlCache.has(e)&&e&&this.skippedSourceCache.has(e))throw new Error(Fd)}async getProcessedDisplayDataUrl(e){return this.resolveActionDataUrl(e)}isValidGeminiImage(e){return !!e.closest("generated-image,.generated-image-container")||this.isLikelyGeneratedImage(e)}findGeminiImages(){return [...document.querySelectorAll("img")].filter(e=>{const t=this.getCurrentImageSource(e);this.resetProcessedImageStateIfSourceChanged(e,t);const n=this.getComparableProcessingSource(t),r=e.getAttribute("data-ophel-wm-skip-source")||"",o="skipped"===e.dataset.watermarkProcessed&&r===n;return this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(t)&&!this.shouldSkipAutoProcessingSource(t)&&"true"!==e.dataset.watermarkProcessed&&"processing"!==e.dataset.watermarkProcessed&&!o})}async processExistingImages(){const e=this.findGeminiImages();for(const t of e)this.processSingleImage(t);}async processSingleImage(e){const t=this.getCurrentImageSource(e);if(!t||!this.isSupportedGeminiImageSource(t))return;if(this.resetProcessedImageStateIfSourceChanged(e,t),this.shouldSkipAutoProcessingSource(t))return;if(this.processingQueue.has(t))return;this.processingQueue.add(t),e.dataset.watermarkProcessed="processing";const n=this.showImageProcessingIndicator(e),r=t.startsWith("data:image/")||t.startsWith("blob:")?t:this.replaceWithNormalSize(t);try{const t=await this.getProcessedDisplayDataUrl(r);e.dataset.watermarkProcessed="true",e.setAttribute("data-ophel-wm-source",r),e.setAttribute("data-ophel-wm-processed","1"),e.removeAttribute("data-ophel-wm-skip-source"),e.removeAttribute("srcset"),e.src=t;}catch(RS){if((RS instanceof Error?RS.message:"")===Fd)return e.dataset.watermarkProcessed="skipped",e.setAttribute("data-ophel-wm-skip-source",r),e.removeAttribute("data-ophel-wm-source"),void e.removeAttribute("data-ophel-wm-processed");e.dataset.watermarkProcessed="error",e.removeAttribute("data-ophel-wm-processed");}finally{this.hideImageProcessingIndicator(n),this.processingQueue.delete(t);}}replaceWithNormalSize(e){return e?e.startsWith("data:image/")||e.startsWith("blob:")?e:this.shouldInterceptGeminiImageUrl(e)?Od(e):e:e}startObserver(){const e=new MutationObserver(e=>{let t=false;for(const n of e)n.addedNodes.length>0&&(t=true),"attributes"===n.type&&n.target instanceof HTMLImageElement&&(this.resetProcessedImageStateIfSourceChanged(n.target,this.getCurrentImageSource(n.target)),t=true);t&&this.processExistingImages();});e.observe(document.body,{childList:true,subtree:true,attributes:true,attributeFilter:["src","srcset"]}),this.stopObserver=()=>e.disconnect();}}const Wd="delete_ui_failed",jd="delete_ui_exception",Gd="delete_batch_aborted_after_ui_failure",Vd=["delete","remove","删除","删掉","supprimer","eliminar","löschen","삭제","削除","移除","excluir","hapus","удал"],Qd=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"],Kd="data-ophel-export-image-src",Zd=/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/i,Yd=/(google|account|账号|帳號|conta|compte|cuenta|konto|アカウント|계정|учет)/i,Xd=/(unable|cannot|can't|can not|无法|無法|不可).*(view|preview|download|共享|分享|shared|查看|预览|預覽|下载|下載)|shared.*(file|download|preview)|共享对话中的文件|共享對話中的文件/i,Jd=[".attachment-container.generated-images","response-element","generated-image","single-image.generated-image",".image-container.replace-fife-images-at-export","[data-image-attachment-index]"].join(", "),eu=["user-query img[data-test-id='uploaded-img']","user-query .preview-image"].join(", "),tu='[data-test-id="uploaded-file"]',nu="share-landing-page .share-turn-viewer",ru="message-content .markdown",ou='share-landing-page immersive-share-landing-page structured-content-container[data-test-id="deep-research-block"]',iu='share-landing-page structured-content-container[data-test-id="immersive-artifact-content"]',au=ru,su="deep-research-confirmation-widget",lu="immersive-panel deep-research-immersive-panel",cu=[`${lu} #extended-response-markdown-content`,`${lu} message-content .markdown`].join(", "),du=['mat-icon[data-mat-icon-name="travel_explore"]','mat-icon[fonticon="travel_explore"]'].join(", "),uu=['mat-icon[fonticon="code_blocks"]','mat-icon[data-mat-icon-name="code_blocks"]'].join(", "),hu="immersive-panel code-immersive-panel",gu='xap-code-editor[data-test-id="code-editor"]',pu="gh-gemini-deep-research-panel-actions",mu="gh-gemini-deep-research-panel-action",fu="data-ophel-deep-research-panel-actions",bu="document",yu=[".cdk-visually-hidden","model-thoughts","immersive-entry-chip","gem-processing-card",'[data-test-id="gem-processing-card"]','[data-test-id="time-estimation-message"]',".time-estimation-message","source-footnote","sources-carousel-inline","sources-carousel",".gh-inline-bookmark",".gh-table-copy-btn","mat-icon","share-button","copy-button","download-generated-image-button",".generated-image-controls",".loader"].join(", "),vu=["img.katex-svg","img.favicon","img.google-icon",'img[data-test-id="favicon"]','img[data-test-id="file-icon"]','img[data-test-id="luminous-file-icon"]','img[src*="faviconV2"]','img[src*="drive-thirdparty.googleusercontent.com/32/type/"]','img[src*="google_logo_icon"]'].join(", "),xu="ophel-gemini-mystuff-active",wu="ophel-gemini-mystuff-style",Su="ophel-mystuff-open-btn",Cu="data-ophel-mystuff-open",ku="data-ophel-mystuff-open-suppress",Tu=/^https:\/\/lh\d+\.googleusercontent\.com\//i,Eu='expandable-section[data-test-id="chats-expandable-section"]',Au='expandable-section[storagekey="chats"]',Mu=["source-chip","source-card","source-footnote","citation-source","citation-chip","citation-marker","grounding-chip","grounding-source","web-source","[data-source]","[data-source-id]","[data-citation]","[data-citation-id]","[data-ved]","[decode-data-ved]","[cdkoverlayorigin]","[mattooltip]","[data-mdc-tooltip]","mat-icon[fonticon]","mat-icon[data-mat-icon-name]","[fonticon*='link' i]","[data-mat-icon-name*='link' i]","sup a","sup button","sup [role='button']",...["source","sources","citation","citations","reference","references","grounding","footnote","link","fonte","fontes","fuente","fuentes","quelle","quellen","referencia","referencias","referência","referências","riferimento","riferimenti","来源","引用","链接","出典","参照","출처","참조","источник","источники","ссылка","ссылки"].flatMap(e=>[`[aria-label*='${e}' i]`,`[title*='${e}' i]`,`[data-test-id*='${e}' i]`])].join(",");class Iu{constructor(e){this.options=e;}started=false;mediaWatchStop=null;tooltipBindings=new WeakMap;pendingRequests=new Map;recordsByKind={media:new Map,document:new Map};mediaByTimestamp=new Map;mediaByThumbnail=new Map;documentByTimestamp=new Map;documentByTitle=new Map;start(){this.started||(this.started=true,this.injectStyles(),this.mediaWatchStop=ds.each(".library-item-card",e=>this.enhanceMediaCard(e),{shadow:true}),document.addEventListener("click",this.handleDocumentClick,true),window.addEventListener("message",this.handleWindowMessage),window.addEventListener("gh-url-change",this.handleRouteChange),this.refreshForCurrentRoute(false),setTimeout(()=>this.refreshForCurrentRoute(false),600),setTimeout(()=>this.refreshForCurrentRoute(false),1500));}handleRouteChange=()=>{this.refreshForCurrentRoute(false);};handleWindowMessage=e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==xd||t===xd&&this.handleCachePayload(n);};handleDocumentClick=e=>{if(!this.isMyStuffPath()||e.defaultPrevented||0!==e.button)return;const t=e.target instanceof Element?e.target:null;if(!t)return;const n=t.closest(`[${Cu}="1"]`);if(n){const t=n.closest("library-item-card");if(!t)return;return this.preventNativeNavigation(e),this.dismissActionButtonVisualState(n),void this.openHostInNewTab(t,"media",this.preparePendingTab())}if(t.closest("library-item-card"))return;const r=t.closest("library-list-item");r&&(this.preventNativeNavigation(e),this.openHostInNewTab(r,"document",this.preparePendingTab()));};preventNativeNavigation(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();}refreshForCurrentRoute(e){const t=this.isMyStuffPath();document.documentElement.classList.toggle(xu,t),t&&(this.enhanceExistingMediaCards(),this.requestSync(e,this.getKindsForCurrentPath()).catch(()=>{}));}injectStyles(){if(document.getElementById(wu))return;const e=document.createElement("style");e.id=wu,e.textContent=`\n .${xu} library-item-card .library-item-card,\n .${xu} .library-item-card-container {\n position: relative;\n }\n\n .${xu} .${Su} {\n position: absolute;\n top: 4px;\n right: 42px;\n width: 36px;\n height: 36px;\n border: none;\n border-radius: 999px;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n background: rgba(15, 23, 42, 0.45);\n color: #ffffff;\n box-shadow: 0 4px 14px rgba(15, 23, 42, 0.12);\n backdrop-filter: blur(6px);\n cursor: pointer;\n opacity: 0;\n pointer-events: none;\n transform: translateY(-2px);\n transition:\n opacity 0.18s ease,\n transform 0.18s ease,\n background-color 0.18s ease,\n color 0.18s ease;\n z-index: 3;\n }\n\n .${xu} library-item-card:hover .${Su},\n .${xu} library-item-card:focus-within .${Su},\n .${xu} .library-item-card:hover .${Su},\n .${xu} .library-item-card:focus-within .${Su},\n .${xu} .library-item-card-container:hover .${Su},\n .${xu} .library-item-card-container:focus-within .${Su} {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0);\n }\n\n .${xu} .${Su}:hover {\n background: rgba(15, 23, 42, 0.60);\n color: #ffffff;\n }\n\n .${xu} .${Su}[${ku}="1"] {\n opacity: 0 !important;\n pointer-events: none !important;\n transform: translateY(-2px) !important;\n }\n\n .${xu} .${Su} svg {\n width: 16px;\n height: 16px;\n stroke: currentColor;\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n }\n\n body.dark-theme .${Su},\n html[dark-theme] .${Su},\n html.dark .${Su} {\n background: rgba(15, 23, 42, 0.45);\n color: #f9fafb;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.32);\n }\n\n body.dark-theme .${Su}:hover,\n html[dark-theme] .${Su}:hover,\n html.dark .${Su}:hover {\n background: rgba(15, 23, 42, 0.60);\n color: #ffffff;\n }\n\n `,document.head.appendChild(e);}enhanceExistingMediaCards(){document.querySelectorAll(".library-item-card").forEach(e=>this.enhanceMediaCard(e));}enhanceMediaCard(e){if(!this.isMyStuffPath())return;const t=e.closest("library-item-card"),n=e.matches(".library-item-card")?e:e.querySelector(".library-item-card");if(!t||!n)return;if(n.querySelector(`[${Cu}="1"]`))return;const r=document.createElement("button");r.type="button",r.className=`${Su} ophel-tooltip-trigger`,r.setAttribute(Cu,"1"),r.setAttribute("aria-label",this.getOpenInNewTabLabel()),r.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=ad("svg",{xmlns:id,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...r?{class:r}:{}}),i=ad("path",{d:"M14 5h5v5"}),a=ad("path",{d:"M10 14 19 5"}),s=ad("path",{d:"M19 14v4a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h4"});return o.appendChild(i),o.appendChild(a),o.appendChild(s),o}()),n.appendChild(r),this.tooltipBindings.set(r,rd(r,{getContent:()=>this.getOpenInNewTabLabel(),delay:300,maxWidth:260,preferredPlacement:"top"}));}isMyStuffPath(){const e=this.getNormalizedPath();return "/mystuff"===e||"/mystuff/"===e||e.startsWith("/mystuff/")||"/library"===e||"/library/"===e||e.startsWith("/library/")}getKindsForCurrentPath(){const e=this.getNormalizedPath();return e.startsWith("/mystuff/documents")||e.startsWith("/library/documents")?["document"]:["media","document"]}getNormalizedPath(){return window.location.pathname.replace(/^\/u\/\d+/,"")}handleCachePayload(e){if(!e||!Array.isArray(e.items)||!Array.isArray(e.kinds))return;this.replaceRecords(e.kinds,e.items);const t=e.requestId?this.pendingRequests.get(e.requestId):null;t&&e.requestId&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e));}replaceRecords(e,t){for(const n of e)this.recordsByKind[n].clear(),t.filter(e=>e.kind===n).forEach(e=>this.recordsByKind[n].set(this.getRecordKey(e),e));this.rebuildIndexes();}rebuildIndexes(){this.mediaByTimestamp.clear(),this.mediaByThumbnail.clear(),this.documentByTimestamp.clear(),this.documentByTitle.clear(),this.recordsByKind.media.forEach(e=>{this.pushIndex(this.mediaByTimestamp,e.timestamp,e);const t=this.normalizeThumbnailUrl(e.thumbnailUrl);t&&this.pushIndex(this.mediaByThumbnail,t,e);}),this.recordsByKind.document.forEach(e=>{this.pushIndex(this.documentByTimestamp,e.timestamp,e);const t=this.normalizeTitle(e.title);t&&this.pushIndex(this.documentByTitle,t,e);});}pushIndex(e,t,n){if(null==t||""===t||0===t)return;const r=e.get(t)||[];r.push(n),e.set(t,r);}async requestSync(e,t){const n=`ophel-mystuff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={requestId:n,force:e,kinds:t},o=new Promise((e,t)=>{const r=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("mystuff-sync-timeout"));},12e3);this.pendingRequests.set(n,{resolve:e,reject:t,timeoutId:r});});return window.postMessage({type:vd,payload:r},"*"),o}preparePendingTab(){return "userscript"!==$i.type?null:window.open("about:blank","_blank")}async openHostInNewTab(e,t,n){const r=await this.resolveRecord(e,t);if(!r)return n&&!n.closed&&n.close(),console.warn("[GeminiAdapter][MyStuff] record not found for host",{kind:t,locator:this.extractLocator(e,t)}),void Pi(le("geminiMystuffLocateFailed"),2500);const o=this.buildRecordUrl(r);!n||n.closed?$i.openTab(o):n.location.href=o;}async resolveRecord(e,t){const n=this.extractLocator(e,t);let r=this.findRecord(n);if(r)return r;try{await this.requestSync(!0,[t]);}catch(RS){console.warn("[GeminiAdapter][MyStuff] sync failed before open",{kind:t,error:RS});}return r=this.findRecord(n),r}extractLocator(e,t){const n=e.closest("[jslog]")||e.querySelector("[jslog]"),r=n?.getAttribute("jslog")||"",o=this.extractJslogMeta(r);return {kind:t,status:o?.status,timestamp:o?.timestamp,timestampNano:o?.timestampNano,title:"document"===t?this.extractTitle(e):void 0,thumbnailUrl:"media"===t?this.extractThumbnailUrl(e):void 0}}extractJslogMeta(e){if(!e)return null;const t=Array.from(e.matchAll(/\[(\d+),\[(\d+)(?:,(\d+))?\]\]/g)),n=t[t.length-1];return n?{status:Number(n[1]),timestamp:Number(n[2]),timestampNano:n[3]?Number(n[3]):void 0}:null}extractTitle(e){const t=e.querySelector(".title, .gds-title-m, .text-content .title");return t?.textContent?.trim()||""}extractThumbnailUrl(e){const t=e.querySelector("img");return t instanceof HTMLImageElement?this.normalizeThumbnailUrl(t.currentSrc||t.src||""):""}normalizeTitle(e){return (e||"").trim().replace(/\s+/g," ").toLowerCase()}normalizeThumbnailUrl(e){if(!e)return "";let t=e;try{t=new URL(e,window.location.href).toString();}catch{t=e;}return Tu.test(t)?t.replace(/=[^/?#]+$/,""):t}findRecord(e){return "media"===e.kind?this.findMediaRecord(e):this.findDocumentRecord(e)}findMediaRecord(e){const t=new Map,n=this.normalizeThumbnailUrl(e.thumbnailUrl);if(n)for(const r of this.mediaByThumbnail.get(n)||[])t.set(this.getRecordKey(r),r);if(e.timestamp)for(const r of this.mediaByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}findDocumentRecord(e){const t=new Map,n=this.normalizeTitle(e.title);if(e.timestamp)for(const r of this.documentByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);if(n)for(const r of this.documentByTitle.get(n)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}pickBestRecord(e,t){if(0===e.length)return null;const n=this.normalizeThumbnailUrl(t.thumbnailUrl),r=this.normalizeTitle(t.title),o=e.map(e=>{let o=0;return void 0!==t.status&&e.status===t.status&&(o+=20),void 0!==t.timestamp&&e.timestamp===t.timestamp&&(o+=80),n&&this.normalizeThumbnailUrl(e.thumbnailUrl)===n&&(o+=200),r&&this.normalizeTitle(e.title)===r&&(o+=120),void 0!==t.timestampNano&&(o-=Math.min(Math.abs((e.timestampNano||0)-t.timestampNano)/1e6,20)),{record:e,score:o}}).sort((e,t)=>t.score-e.score);return o[0]?.record||null}buildRecordUrl(e){const t=e.conversationId.replace(/^c_/,""),n=e.responseId.replace(/^r_/,""),r=new URL(`${window.location.origin}${this.options.getUserPathPrefix()}/app/${t}`);return r.searchParams.set(Vo,"1"),r.hash=n,r.toString()}getRecordKey(e){return `${e.conversationId}:${e.responseId}`}getOpenInNewTabLabel(){return le("geminiMystuffOpenInNewTab")}dismissActionButtonVisualState(e){this.tooltipBindings.get(e)?.hide(),e.blur(),e.setAttribute(ku,"1");const t=()=>{e.removeAttribute(ku),window.removeEventListener("pointermove",t,true),window.removeEventListener("pointerdown",t,true),window.removeEventListener("keydown",t,true),window.removeEventListener("wheel",t,true),window.removeEventListener("touchstart",t,true),e.removeEventListener("focus",t,true);};window.addEventListener("pointermove",t,true),window.addEventListener("pointerdown",t,true),window.addEventListener("keydown",t,true),window.addEventListener("wheel",t,true),window.addEventListener("touchstart",t,true),e.addEventListener("focus",t,true);}}const Lu="delete_ui_failed",Nu="delete_batch_aborted_after_ui_failure",Ru=["delete","remove","删除","删掉","移除","supprimer","eliminar","löschen","삭제","削除","hapus","удал"],Du=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"];const Pu=["M13 21L12 23L11 21V16H4.5V13.7129L4.65234 13.4697L6.95801 9.78027L6.41797 5.99512C6.11675 3.8866 7.75289 2 9.88281 2H14.1172C16.2471 2 17.8832 3.8866 17.582 5.99512L17.041 9.78027L19.5 13.7129V16H13V21Z"].map(e=>e.replace(/\s+/g,"")),qu="delete_ui_failed",Bu="delete_batch_aborted_after_ui_failure",$u="delete_api_request_failed",_u="delete_api_not_found_but_visible",Ou=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удал","excluir"],zu=["confirm","ok","yes","确定","確認","确认","確定","check"];const Fu="ima.qq.com",Uu=/^\/chat\/([a-z0-9]+)(?:\/|$)/i,Hu="#scrollContainer",Wu=`${Hu} [class*="scrollWrap"]`,ju='div[class*="userBubbleContainer"]',Gu='div[class*="userBubbleWrap"]',Vu=[ju,Gu].join(", "),Qu=`${ju} [class*="userBubble"]`,Ku='[class*="chatMainBubble"]',Zu=[Qu,`${Gu} ${Ku}`].join(", "),Yu=[`${Qu} [class*="content"]`,Ku].join(", "),Xu='div[class*="aiContainer"]',Ju=`${Xu} [class*="bubble"]`,eh='[class*="markdown"]',th=`${Ju} ${eh}`,nh='[class*="thinking"]',rh='.system-copy-exclude, [x-noteelement="excluded"], [x-copyelement="copy-exclude"]',oh=[".gh-root",".gh-user-query-markdown",".gh-inline-bookmark",rh,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),ih=':is([class*="attachmentContainer"], [class*="attachmentWrap"])',ah=[`${ih} img`,'[class*="imgWrap"] img'].join(", "),sh=[`${ih} [class*="itemWrap"]`,`${ih} [class*="file"]`,`${ih} [class*="doc"]`,`${ih} a[href]`,`${ih} [data-file-id]`,`${ih} [data-doc-id]`,`${ih} [data-resource-id]`].join(", "),lh=[`${Ju} [class*="imagesWrapper"] img`,`${Ju} [id^="image-toolkit-"] img`,`${Ju} [class*="bigImg"] img`,`${Ju} ${eh} img`].join(", "),ch=['[class*="imagesWrapper"]','[id^="image-toolkit-"]',".t-image__wrapper","picture","img"].join(", "),dh=["href","src","data-src","data-url","data-card-url","data-download-url","data-file-url","data-resource-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],uh='[class*="sendBtnWrap"]',hh=['div[class*="stopButton"] > div','[class*="stopButton"][role="button"]','button[class*="stopButton"]','[class*="stopButton"]'].join(", "),gh='[class*="currentChoiceWrap"], [class*="modelSelectionWrap"], [class*="modelSelectionText"]',ph='[class*="modelSelectionText"]';const mh=/^\/chat\/([a-z0-9-]+)(?:\/|$)/i,fh=/^\/(?:share|kimiplus)\/([a-z0-9-]+)(?:\/|$)/i,bh=["/docs/","/website/","/table/"],yh="__tea_cache_tokens_",vh="kimi-auth",xh=[vh,"kimi_auth","access_token","accessToken","token","auth","authorization"],wh=["value","token","access_token","accessToken","auth","authorization","id_token","idToken","jwt"],Sh=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ch=/(token|auth|jwt|tea)/i,kh="a.chat-info-item",Th=`${kh}, a.history-link`,Eh=".history-part",Ah="span.chat-name",Mh=".history-chat .title-wrapper .title",Ih=".chat-content-list",Lh=`${Ih}, .share-content-list`,Nh=[Ih,`${Ih}${Ih}`,`${Ih}${Ih}${Ih}`,`.chat-detail-content ${Ih}`,`.chat-detail-content ${Ih}${Ih}`].join(", "),Rh=".chat-content-item",Dh=".chat-content-item-user",Ph=".chat-content-item-assistant",qh=".segment.segment-user",Bh=".segment.segment-assistant",$h=[".segment-user .segment-content",`${Dh} .segment-content`,".segment-container:has(.user-content) > .segment-content"].join(", "),_h=[".segment-user .segment-content-box",`${Dh} .segment-content-box`,".segment-content-box:has(> .user-content)"].join(", "),Oh=[".segment-user .user-content",`${Dh} .user-content`,".segment-content-box > .user-content"].join(", "),zh=[".segment-assistant .segment-content-box > .markdown-container > .markdown",`${Ph} .segment-content-box > .markdown-container > .markdown`].join(", "),Fh=".toolcall-container, .container-block",Uh="button, [role='button'], svg, canvas, [aria-hidden='true'], .segment-avatar, .okc-cards-container",Hh="CUSTOM_THEME",Wh="delete_api_missing_auth_token",jh="delete_api_request_failed",Gh="delete_api_invalid_response",Vh="delete_api_business_failed";const Qh=/\/chat\/([a-f0-9]+)/i,Kh=/\/group\/([a-f0-9]+)/i,Zh="tongyi-theme-preference",Yh="model-select-expanded",Xh='[class*="questionItem"], .chat-question-wrap, [class*="message-select-wrapper-question"]',Jh="[data-chat-question-wrap]",eg='[class*="answerItem"], [data-chat-answers-wrap], .chat-answers-card-wrap',tg='[class*="bubble"]',ng=[`${Jh} .message-card-wrap.question`,`${Jh} .question-text-card`].join(", "),rg=".message-card-wrap.question",og=`${rg}[data-mt*="image"]`,ig=[`${rg}[data-mt*="doc"]`,`${rg}[data-mt*="file"]`,`${rg}[data-mt*="office"]`,`${rg}:has([class*="office-card"])`].join(", "),ag=[".answer-common-card .qk-markdown",".markdown-pc-special-class .qk-markdown","#qk-markdown-react",".answer-common-card"].join(", "),sg=['[data-card-type="ai_generate_image_list"] img',".card_card_ai_generate_image img",'[data-tpl*="card_ai_generate_image"] img','img[data-image-menu-items*="download"]','img[class*="image-"][data-image-resource-id]'].join(", "),lg=['[data-card-type="ai_generate_image_list"]',".card_card_ai_generate_image",'[data-tpl*="card_ai_generate_image"]'].join(", "),cg=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']",".qk-md-table-action",".qk-md-copy-icon","[class*='answerToolsContent']","[class*='functionArea']","[class*='recommend-query']",".q-item",".qs-bottom","style","script"].join(", "),dg=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],ug='[class*="chatInput"]',hg=".message-list-scroll-container, #message-list-scroller",gg="#qwen-message-list-area",pg="aside#new-nav-tab-wrapper",mg='.qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], [class*="thinkingHeader"], [class*="thinkingTitle"]',fg='[class*="stop-"], [class*="stopBtn"], div[class*="stop"]',bg='[role="dialog"], [data-radix-popper-content-wrapper]',yg=['[role="dialog"] [id="tongyi-for-guide-model"]','[role="dialog"] .group.rounded-8','[data-radix-popper-content-wrapper] [id="tongyi-for-guide-model"]',"[data-radix-popper-content-wrapper] .group.rounded-8"].join(", ");const vg=/\/c\/([a-f0-9-]+)/i,xg="theme",wg="#sidebar",Sg=".session-list-wrapper",Cg=".chat-item-drag",kg=".chat-item-drag-link-content-tip-text",Tg="#chat-messages-scroll-container",Eg="#chat-message-container",Ag=".qwen-chat-message-user, .chat-user-message-wrapper",Mg=".qwen-chat-message-assistant",Ig=".user-message-content",Lg=".response-message-content",Ng="button.send-button",Rg=["button.stop-button",'button[class*="stop-button"]',".stop-button"],Dg="pre.qwen-markdown-code",Pg=".artifacts-body-header-switch",qg=".artifacts-body-header-switch-active, .artifacts-body-header-switch-unactive, .header-switch-status-small",Bg="data-ophel-qwenai-mermaid-export-switched",$g=".qwen-chat-thinking-tool-status-card-wraper, .qwen-chat-thinking-status-card",_g=".qwen-chat-thinking-status-card-title-text",Og=[".splitter-container-right-panel .qwen-chat-thinking-and-sources",".share-layout-right-panel .qwen-chat-thinking-and-sources",".qwen-chat-thinking-and-sources-share"].join(", "),zg=".response-message-footer, .copy-response-button, .message-hoc-container",Fg=[".gh-root",".gh-user-query-markdown",$g,zg,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Ug=[".user-image-item",".user-image-list .qwen-image","[class*='file-message-image'] .qwen-image",".qwen-markdown-image:has(img)"].join(", "),Hg=[".chat-response-media-render img",".qwen-chat-response-control-card img",".response-message-content img",".qwen-markdown-image img","img.qwen-image"].join(", "),Wg=[".chat-response-media-render",".qwen-chat-response-control-card",".qwen-markdown-image","picture","img"].join(", "),jg=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Gg='#qwen-chat-header-left .ant-dropdown-trigger:has([class*="model-selector-text"])',Vg='#qwen-chat-header-left [class*="model-selector-text"]',Qg='[class*="model-selector-popup"]',Kg=[`${Qg} [class*="model-list"] > [class*="model-item___"]`,`${Qg} [class*="model-list"] > [class*="model-item-selected___"]`].join(", "),Zg=[`${Qg} .ant-dropdown-trigger:has([class*="view-more-text"])`,`${Qg} .ant-dropdown-trigger:has([class*="view-more-icon"])`].join(", "),Yg=[Kg,Zg,'.ant-dropdown [role="menuitem"]',".ant-dropdown .ant-dropdown-menu-item",".ant-dropdown .ant-dropdown-menu-title-content",'.ant-select-dropdown [role="option"]',".ant-select-dropdown .ant-select-item-option"].join(", "),Xg=".qwen-markdown-latex";const Jg="yuanbao.tencent.com",ep=/^\/chat\/([^/?#]+)(?:\/([^/?#]+))?/,tp="yb_web_theme_mode",np="#yuanbao-send-btn, a.style__send-btn___RwTm5",rp="a.style__send-btn___RwTm5",op=".yb-recent-conv-list__item",ip=".yb-recent-conv-list__item.active",ap=".yb-recent-conv-list__item-name[data-item-name], .yb-recent-conv-list__item-name, [data-item-id][data-item-name]",sp="#chat-content .agent-chat__list__content, .agent-chat__list__content",lp=".agent-chat__list__item--human",cp=".agent-chat__list__item--ai",dp=".agent-chat__list__item--ai .hyc-common-markdown-style, .agent-chat__list__item--ai .hyc-content-md-done",up=".agent-chat__toolbar, .agent-chat__toolbar_new, .agent-chat__question-toolbar, .hyc-common-markdown__code__hd__r",hp=".hyc-card-box-process-list, .hyc-common-markdown__replace-appCard",gp=[".hyc-component-multi-modal__image img",".agent-chat__bubble--human .hyc-content-img img"].join(", "),pp=[".hyc-component-multi-modal__file",".hyc-component-multi-modal__doc",".hyc-component-multi-modal__document",".hyc-content-file",".hyc-content-doc",".hyc-file-card",".hyc-doc-card","[data-file-id]","[data-doc-id]","[data-resource-id]","a[href*='/api/resource/download']",".agent-chat__bubble--human [class*='file']",".agent-chat__bubble--human [class*='doc']"].join(", "),mp=['[data-card-type="image"] img','[data-box-type="loadingImage"] img',".hyc-media-box--loadingImage img",".loading-image-box img"].join(", "),fp=['[data-card-type="image"]','[data-box-type="loadingImage"]',".hyc-media-box--loadingImage",".loading-image-box"].join(", "),bp=["href","src","data-src","data-url","data-card-url","data-download-url","data-file-url","data-resource-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],yp=".ybc-model-select-button .t-button__text",vp=[".hyc-component-reasoner__think-content .hyc-common-markdown-style",".hyc-component-deepsearch-cot__think__content__item .hyc-common-markdown-style",".hyc-common-markdown-style-cot"].join(", "),xp=[".hyc-component-reasoner__think",".hyc-component-deepsearch-cot__think",".hyc-common-markdown-style-cot"].join(", "),wp=[".hyc-component-reasoner__text .hyc-common-markdown-style",".hyc-component-reasoner__text .hyc-content-md-done",".hyc-component-reasoner__text"],Sp=[".t-dropdown__menu",".t-dropdown__submenu",".t-dropdown",".t-popup",".t-popup__content",".t-popup__content__inner",'[role="menu"]','[role="listbox"]'].join(", "),Cp=[".t-dropdown__item",".yb-dropdown__item",'[role="menuitem"]','[role="option"]'].join(", "),kp=['[aria-haspopup="menu"]','[aria-haspopup="listbox"]',".icon-yb-ic_ellipsis",".icon-yb-ic_more_vert",".icon-yb-ic_more_vert_16",".icon-yb-ic_delete",".icon-yb-ic_delete_16",".icon-yb-ic_delete_20",".icon-more",".icon-del",".icon-delete",".icon-menu","button",'[role="button"]'].join(", "),Tp='.t-dialog, [role="dialog"]',Ep="--hunyuan-chat-list-max-width",Ap=/删除|delete/i,Mp=/删除|确认|确定|delete|confirm/i,Ip=/取消|cancel/i,Lp="ui_failed",Np="ui_exception",Rp="batch_aborted_after_ui_failure";const Dp="chat.z.ai",Pp=/\/(?:c|s)\/([a-z0-9-]+)(?:\/|$)/i,qp=/\/s\/([a-z0-9-]+)(?:\/|$)/i,Bp=["#chat-input","textarea#chat-input"],$p="#send-message-button",_p=["#sidebar-new-chat-button","#new-chat-button"],Op=["button.modelSelectorButton",'button[id^="model-selector-"][id$="-button"]',"#model-selector-glm-5-button","button[data-melt-dropdown-menu-trigger][data-menu-trigger].modelSelectorButton"],zp="#chat-container",Fp=[`${zp} .flex.overflow-y-scroll.flex-col.w-full.h-full`,`${zp} .scrollbar-none.flex.flex-col`,`${zp} [data-pane-id] .overflow-y-scroll`,`${zp} [data-pane-id] .scrollbar-none`].join(", "),Up=['[id^="message-"].user-message',".user-message .chat-user.markdown-prose",".user-message .chat-user",`${zp} .chat-user.markdown-prose`,`${zp} .chat-user`,`${zp} [data-message-author-role="user"]`,`${zp} [data-role="user"]`,`${zp} .message-user`,`${zp} .user-message`,`${zp} .chat-message-user`,`${zp} .message.user`].join(", "),Hp=[`${zp} .markdown-prose:not(.chat-user)`,`${zp} [data-message-author-role="assistant"]`,`${zp} [data-role="assistant"]`,`${zp} .message-assistant`,`${zp} .assistant-message`,`${zp} .chat-message-assistant`,`${zp} .markdown`,`${zp} .markdown-body`,`${zp} .prose`,`${zp} article`,`${zp} [data-markdown]`,'[id^="message-"]:not(.user-message) .markdown-prose:not(.chat-user)','[id^="message-"]:not(.user-message) .markdown-body','[id^="message-"]:not(.user-message) [data-markdown]'].join(", "),Wp=['[id^="message-"]:not(.user-message)',Hp].join(", "),jp="data-gh-export-role",Gp=`[${jp}="user"]`,Vp=`[${jp}="assistant"]`,Qp=".thinking-chain-container, .thinking-block",Kp=[".gh-user-query-raw",".rounded-xl.whitespace-pre-wrap",".rounded-xl",".whitespace-pre-wrap","[data-user-content]",".message-content",".chat-message-content",".user-message-content",".content",'div[dir="auto"]',"p"],Zp=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Yp=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Xp=['div[aria-label="停止"] button',"button:has(span.rounded-xs):has(span.size-3)","button:has(span.rounded-xs):has(span.block)"].join(", "),Jp="#sidebar .w-full.mb-1.relative.group",em='div[dir="auto"]',tm="theme",nm={light:"#F4F6F8",dark:"#141618"},rm=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,om=/^message-([a-f0-9-]{36})$/i;const im=[new class extends vs{clearOnInit=false;cloneWithoutSrOnly(e){const t=e.cloneNode(true);return t.querySelectorAll(".sr-only").forEach(e=>e.remove()),t}match(){return window.location.hostname.includes("business.gemini.google")}getSiteId(){return mo}getName(){return "Gemini Enterprise"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNewTabUrl(){return "https://business.gemini.google"}isNewConversation(){return !window.location.pathname.includes("/session/")}isSharePage(){return window.location.pathname.includes("/r/share/")}isUserConversationPage(){return !this.isSharePage()&&/\/session\/[^/?#]+(?:\/|$)/i.test(window.location.pathname)}supportsTabRename(){return true}getCurrentCid(){const e=window.location.pathname.match(/\/home\/cid\/([^/]+)/);return e?e[1]:""}getSessionName(){const e=ds.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(!e)continue;if(e.classList.contains("selected")||e.classList.contains("active")||"true"===e.getAttribute("aria-selected")){const t=e.querySelector(".conversation-title");if(t){const e=t.textContent?.trim();if(e)return e}}}return super.getSessionName()}getConversationTitle(){const e=ds.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(e&&(e.classList.contains("selected")||e.classList.contains("active")))return e.querySelector(".conversation-title")?.textContent?.trim()||null}return null}getConversationList(){const e=ds.query(".conversation",{all:true,shadow:true}),t=this.getCurrentCid();return Array.from(e).map(e=>{const n=e.querySelector("button.list-item")||e.querySelector("button");if(!n)return null;const r=n.querySelector(".conversation-action-menu-button");let o="";if(r&&r.id&&r.id.startsWith("menu-")&&(o=r.id.replace("menu-","")),!o||!/^\d+$/.test(o))return null;const i=n.querySelector(".conversation-title"),a=i&&i.textContent?.trim()||"",s=n.classList.contains("selected")||n.classList.contains("active")||"true"===n.getAttribute("aria-selected");let l=`https://business.gemini.google/session/${o}`;return t&&(l=`https://business.gemini.google/home/cid/${t}/r/session/${o}`),{id:o,cid:t,title:a,url:l,isActive:s}}).filter(e=>null!==e)}getLatestReplyText(){const e=ds.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return null;const t=e.shadowRoot.querySelector(".main");if(!t)return null;const n=t.querySelectorAll(".turn");if(0===n.length)return null;const r=n[n.length-1].querySelector("ucs-summary");if(!r)return null;const o=this.extractSummaryContent(r);if(!o)return this.extractTextWithLineBreaks(r);const i=this.cloneWithoutSrOnly(o),a=Hi(i).trim();return a||this.extractTextWithLineBreaks(i)}getSidebarScrollContainer(){return ds.query(".conversation-list",{shadow:true})||ds.query("mat-sidenav",{shadow:true})}getConversationObserverConfig(){return {selector:".conversation",shadow:true,extractInfo:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");if(!t)return null;const n=t.querySelector(".conversation-action-menu-button");if(!n||!n.id?.startsWith("menu-"))return null;const r=n.id.replace("menu-","");if(!/^\d+$/.test(r))return null;const o=t.querySelector(".conversation-title"),i=o?.textContent?.trim()||"",a=this.getCurrentCid();return {id:r,cid:a,title:i,url:`https://business.gemini.google/home/cid/${a}/r/session/${r}`}},getTitleElement:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");return t?.querySelector(".conversation-title")||e}}}navigateToConversation(e,t){const n=ds.query(".conversation",{all:true,shadow:true});if(n)for(const r of Array.from(n)){if(r.querySelector(`#menu-${e}`)||r.querySelector(`.conversation-action-menu-button[id="menu-${e}"]`)){const e=r.querySelector("button.list-item")||r.querySelector("button");return e?e.click():r.click(),true}}return super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Lu}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);const n=await this.findConversationMenuButton(t);if(!n)return false;const r=await this.openConversationMenu(t,n);if(!r)return false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o),this.removeConversationRowElement(t,e);const i=await this.waitForConversationRemoved(e,5200),a=await this.waitForMenuClosed(1200),s=i||a;return s&&this.syncConversationListAfterDelete(e),s}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){if(n){const e=o.find(e=>e.id===`menu-${n}`);if(e)return e}const e=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"], md-icon'));if(e)return e;const t=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(t)return t}await this.sleep(90);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}revealConversationActions(e){const t=["mouseenter","mouseover","mousemove"];for(const n of t)e.dispatchEvent(new MouseEvent(n,{bubbles:true,cancelable:true,view:window}));}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,Du))return e}return null}getMenuActionCandidates(e,t){const n='md-menu-item, [role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=this.getMenuContainerFromTrigger(e);o&&r.push(...Array.from(o.querySelectorAll(n)));const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(t):t;return ds.query(`#${n}`,{shadow:true})||null}findVisibleMenuContainer(){const e=this.findAllElementsBySelector('md-menu-surface, .menu[popover], .mat-mdc-menu-panel, [role="menu"]').filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForMenuClosed(e=1200){const t=Date.now();for(;Date.now()-te instanceof HTMLElement),r=new Set;for(const o of n)r.has(o)||(r.add(o),o.isConnected&&o.remove());}async waitForConversationRemoved(e,t=5200){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getNewChatButtonSelectors(){return [".chat-button.list-item",'button[aria-label="New chat"]','button[aria-label="新对话"]']}getWidthSelectors(){const e=(e,t,n,r=false)=>({selector:e,globalSelector:`mat-sidenav-content ${e}`,property:"max-width",value:t,extraCss:n,noCenter:r});return [e("mat-sidenav-content","100%",void 0,true),e(".main.chat-mode","100%",void 0,true),e("ucs-summary"),e("ucs-conversation"),e("ucs-search-bar"),e(".summary-container.expanded"),e(".conversation-container"),e(".input-area-container",void 0,"left: 0 !important; right: 0 !important;",true)]}getUserQueryWidthSelectors(){return [{selector:".question-block .question-wrapper",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["ucs-nav-panel"]}}getCleanModeConfig(){return {hide:[".disclaimer"]}}getTextareaSelectors(){return ["div.ProseMirror",".ProseMirror",'[contenteditable="true"]:not([type="search"])','[role="textbox"]','textarea:not([type="search"])']}getSubmitButtonSelectors(){return ['button[aria-label*="Submit"]','button[aria-label*="提交"]','button[aria-label*="发送"]','button[aria-label*="Send"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if("search"===e.type)return false;if(e.classList.contains("main-input"))return false;if(e.getAttribute("aria-label")?.includes("搜索"))return false;if(e.placeholder?.includes("搜索"))return false;if(e.classList.contains("prompt-search-input"))return false;if("prompt-search"===e.id)return false;if(e.closest(".gh-main-panel"))return false;if(e.closest(".gh-queue-panel"))return false;if(Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-")))return false;const t=null!==e.offsetParent,n="true"===e.getAttribute("contenteditable"),r=e.classList.contains("ProseMirror");return t&&(n||r||"TEXTAREA"===e.tagName)}findTextarea(){const e=ds.query(this.getTextareaSelectors(),{shadow:true,filter:e=>this.isValidTextarea(e)});return e?(this.textarea=e,e):super.findTextarea()}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("insertText",false,"​")):this.textarea=null);}clearTextareaNormal(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)):this.textarea=null);}insertPrompt(e){const t=this.textarea||this.findTextarea();if(!t)return console.warn("[GeminiEnterpriseAdapter] Editor not found during insert."),false;if(!t.isConnected)return this.textarea=null,false;this.textarea=t,t.click(),t.focus();const n=()=>(t.textContent?.replace(/[\u200B\u200C\u200D\uFEFF]/g,"")||"").includes(e);try{const r=new DataTransfer;r.setData("text/plain",e);const o=new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:r});if(t.dispatchEvent(o),n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),!0}catch{}try{document.execCommand("selectAll",!1,void 0);if(document.execCommand("insertText",!1,e)&&n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{}try{t.focus();const r=t.ownerDocument.getSelection();r&&(r.selectAllChildren(t),r.collapseToEnd());const o=new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});t.dispatchEvent(o);const i=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});if(t.dispatchEvent(i),n())return !0}catch{}try{let r=t.querySelector("p"),o=!1;if(r||(r=document.createElement("p"),t.appendChild(r),o=!0),r.textContent=e,(o||e)&&(t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))),t.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new Event("change",{bubbles:!0})),n())return !0}catch{}return console.warn("[GeminiEnterpriseAdapter] All insert strategies failed for content insertion."),false}getScrollContainer(){const e=ds.query(".chat-mode-scroller",{shadow:true});return e&&e.scrollHeight>e.clientHeight?e:super.getScrollContainer()}scrollToOutlineTarget(e){const t=this.getScrollContainer();if(t){const n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),o=t.scrollTop+(r.top-n.top);t.scrollTo({top:o,behavior:"instant",__bypassLock:true});}else super.scrollToOutlineTarget(e);}getResponseContainerSelector(){return ".conversation-container"}getChatContentSelectors(){return [".model-response-container",".message-content","[data-message-id]","ucs-conversation-message",".conversation-message"]}getUserQuerySelector(){return ".question-block"}extractUserQueryText(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return this.extractTextWithLineBreaks(e);const n=t.shadowRoot.querySelector(".markdown-document");return n?this.extractTextWithLineBreaks(n):this.extractTextWithLineBreaks(e)}extractAssistantResponseText(e){const t=this.extractSummaryContent(e);if(!t)return this.extractTextWithLineBreaks(e);const n=this.cloneWithoutSrOnly(t),r=Hi(n).trim();return r||this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return e.textContent?.trimEnd()||"";const n=t.shadowRoot.querySelector(".markdown-document");if(!n)return e.textContent?.trimEnd()||"";const r=n.querySelectorAll("p");if(0===r.length)return n.textContent?.trimEnd()||"";return Array.from(r).map(e=>e.textContent||"").join("\n").trimEnd()}replaceUserQueryContent(e,t){const n=e.querySelector("ucs-fast-markdown");if(!n||!n.shadowRoot)return false;const r=n.shadowRoot.querySelector(".markdown-document");if(!r)return false;if(r.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const o=document.createElement("div");return o.className="gh-user-query-markdown gh-markdown-preview",!!Md(o,t)&&(r.style.display="none",r.after(o),true)}usesShadowDOM(){return true}extractSummaryContent(e){const t=(e,n=0)=>{if(n>10||!e)return null;const r=e.shadowRoot||(11===e.nodeType?e:null)||e;if("querySelector"in r){const e=r.querySelector(".markdown-document");if(e)return e}const o="querySelectorAll"in r?r.querySelectorAll("*"):[];for(const i of Array.from(o))if(i.shadowRoot){const e=t(i.shadowRoot,n+1);if(e)return e}return null};return t(e)}findHeadingsInShadowDOM(e,t,n,r,o,i={}){if(!(r>15))if("shadowRoot"in e&&e.shadowRoot)this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);else {if(e!==document&&"querySelectorAll"in e){const r=Array.from({length:n},(e,t)=>`h${t+1}`).join(", ");try{e.querySelectorAll(r).forEach(e=>{if(this.isInRenderedMarkdownContainer(e))return;const n=e.querySelectorAll("span[data-markdown-start-index]");if(n.length>0){const r=parseInt(e.tagName[1],10),a=Array.from(n).map(e=>e.textContent?.trim()).join("");if(a){const n={level:r,text:a,element:e};if(o){const t=`${e.tagName.toLowerCase()}-${a}`,r=i[t]||0;i[t]=r+1,n.id=`${o}::${t}::${r}`;}t.push(n);}}});}catch{}}if("querySelectorAll"in e){const a=e.querySelectorAll("*");for(const e of Array.from(a))e.shadowRoot&&this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);}}}extractOutline(e=6,t=false,n=false){const r=[],o=e=>{const t=this.extractSummaryContent(e);return t?t.textContent?.trim().length||0:e.textContent?.trim().length||0};if(!t)return this.findHeadingsInShadowDOM(document,r,e,0),n&&r.forEach((e,t)=>{if(!e.element)return;const n=e.element.closest(".markdown-document");if(n){let o=null;for(let n=t+1;n{const i=(t.getAttribute("jslog")||"").match(/(\d+_\d+)/),a=i?i[1]:void 0,s=t.querySelector(".question-block"),l=t.querySelector("ucs-summary");if(s){let e=this.extractUserQueryText(s),t=false;e.length>200&&(e=e.substring(0,200),t=true);const i={level:0,text:e,element:s,isUserQuery:true,isTruncated:t,id:a};n&&l&&(i.wordCount=o(l)),r.push(i);}if(l){const t=[];if(this.findHeadingsInShadowDOM(l,t,e,0,a),n){const e=this.extractSummaryContent(l);t.forEach((n,r)=>{if(!n.element)return;let o=null;for(let e=r+1;er.push(e));}}),r}findElementByHeading(e,t){const n=ds.query(`h${e}`,{all:true,shadow:true});for(const r of n)if(r.textContent?.trim()===t)return r;return null}getExportConfig(){return {userQuerySelector:".question-block",assistantResponseSelector:"ucs-summary",turnSelector:".turn",useShadowDOM:true}}getAssistantMermaidSupportMode(){return "fallback"}getAssistantMermaidBlocks(e){const t=e instanceof Element?e.matches("ucs-summary")?e:e.closest("ucs-summary")||ds.query("ucs-summary",{parent:e,shadow:true}):ds.query("ucs-summary",{parent:e,shadow:true})||null;if(!t)return [];const n=this.extractSummaryContent(t);return ys(n||t)}isGenerating(){const e=(t,n=0)=>{if(n>10)return false;const r=t.querySelector('button[aria-label*="Stop"], button[aria-label*="停止"], [data-test-id="stop-button"], .stop-button, md-icon-button[aria-label*="Stop"]');if(r&&null!==r.offsetParent)return true;const o=t.querySelector('mat-spinner, md-spinner, .loading-spinner, [role="progressbar"], .generating-indicator, .response-loading');if(o&&null!==o.offsetParent)return true;const i=t.querySelectorAll("*");for(const a of Array.from(i))if(a.shadowRoot&&e(a.shadowRoot,n+1))return true;return false};return e(document)}getStopButtonSelectors(){return ['button[aria-label*="Stop"]','button[aria-label*="停止"]','[data-test-id="stop-button"]',".stop-button",'md-icon-button[aria-label*="Stop"]']}requiresDomConfirmationForNetworkGeneration(){return true}getModelName(){const e=(t,n=0)=>{if(n>10)return null;const r=["#model-selector-menu-anchor",".action-model-selector",".model-selector",'[data-test-id="model-selector"]',".current-model"];for(const e of r){const n=t.querySelector(e);if(n&&n.textContent){const e=n.textContent.trim(),t=e.match(/(\d+\.?\d*\s*)?(Pro|Flash|Ultra|Nano|Gemini|auto|自动)/i);if(t)return t[0].trim();if(e.length<=20&&e.length>0)return e}}const o=t.querySelectorAll("*");for(const i of Array.from(o))if(i.shadowRoot){const t=e(i.shadowRoot,n+1);if(t)return t}return null};return e(document)}getNetworkMonitorConfig(){return {urlPatterns:["widgetStreamAssist"],silenceThreshold:3e3}}afterPropertiesSet(e={}){this.clearOnInit=e.clearOnInit||false,super.afterPropertiesSet(e),this.clearOnInit&&this.clearTextarea();}lockModel(e,t=null){super.lockModel(e,t??void 0);}shouldInjectIntoShadow(e){return !(e.closest("mat-sidenav")||e.closest("mat-drawer")||e.closest('[class*="bg-sidebar"]'))}async loadAllConversations(){for(let e=0;e<20;e++){const e=(ds.query("button.show-more",{all:true,shadow:true})||[]).filter(e=>{const t=e.querySelector(".show-more-icon");return t&&!t.classList.contains("more-visible")});if(0===e.length)break;for(const t of e)t.click();await new Promise(e=>setTimeout(e,300));}}getDefaultLockSettings(){return {enabled:true,keyword:"3 Pro"}}getModelSwitcherConfig(e){return {targetModelKeyword:e||"3 Pro",selectorButtonSelectors:["#model-selector-menu-anchor",".action-model-selector"],menuItemSelector:"md-menu-item",checkInterval:1500,maxAttempts:20,menuRenderDelay:500}}async toggleTheme(e){let t=false;const n=()=>{if(!t){try{ds.query('.menu[popover], md-menu-surface, .mat-menu-panel, [role="menu"]',{all:!0,shadow:!0}).forEach(e=>{const t=e;"0"!==t.style.opacity&&(t.style.setProperty("opacity","0","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("pointer-events","none","important"));});}catch{}requestAnimationFrame(n);}};n(),document.body.classList.add("gh-stealth-mode");try{let t=ds.query(".settings-button",{shadow:!0});if(!t)return console.error("[GeminiEnterpriseAdapter] Settings button not found (.settings-button)"),!1;"function"==typeof t.click?t.click():t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}));let n=0;const r=()=>{const t="system"===e?"computer":"dark"===e?"dark_mode":"light_mode",n=ds.query("md-primary-tab",{all:!0,shadow:!0});for(const e of n){const n=e.querySelector("md-icon")||ds.query("md-icon",{parent:e,shadow:!0});if(n&&n.textContent?.trim()===t)return e.click(),!0}return !1};return await new Promise(e=>{const o=setInterval(()=>{n++,r()?(clearInterval(o),e(!0)):n>20&&(clearInterval(o),console.error("[GeminiEnterpriseAdapter] Target theme option not found"),e(!1),t&&"function"==typeof t.click&&t.click());},100);})}finally{t=true,setTimeout(()=>{document.body.classList.remove("gh-stealth-mode");},200);}}},new class extends vs{cachedAccountEmail=null;accountEmailLastDetectAt=0;myStuffEnhancer=null;deepResearchPanelWatchStop=null;deepResearchPanelObservers=new WeakMap;deepResearchPanelTooltipBindings=new WeakMap;exportOpenedCanvasPanel=false;getUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);if(!e)return "";return `/u/${e[1]}`}getCurrentCid(){const e=this.getCurrentAccountEmail();if(e)return e;const t=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return t?t[1]:"0"}getCurrentAccountEmail(){const e=Date.now();if(e-this.accountEmailLastDetectAt<2e3)return this.cachedAccountEmail;this.accountEmailLastDetectAt=e;const t=["aria-label","title","data-email","data-identifier"],n=new Set;["[data-email]",'[data-identifier*="@"]','[aria-label*="@"]','[title*="@"]'].forEach(e=>{document.querySelectorAll(e).forEach(e=>n.add(e));});for(const r of n)for(const e of t){const t=r.getAttribute(e),n=this.extractEmailFromAttr(e,t);if(n)return this.cachedAccountEmail=n,n}return this.cachedAccountEmail}startDeepResearchPanelActions(){this.deepResearchPanelWatchStop||(this.injectDeepResearchPanelActionStyles(),this.deepResearchPanelWatchStop=ds.each(lu,e=>this.watchDeepResearchPanel(e),{shadow:true}));}watchDeepResearchPanel(e){if(this.syncDeepResearchPanelActions(e),this.deepResearchPanelObservers.has(e))return;let t=null;t=ds.watch(e,()=>{if(!e.isConnected)return t?.(),void this.deepResearchPanelObservers.delete(e);this.syncDeepResearchPanelActions(e);},{childList:true,subtree:true,attributes:true,attributeFilter:["aria-busy"],debounce:100}),this.deepResearchPanelObservers.set(e,t);}injectDeepResearchPanelActionStyles(){ds.css(`\n .${pu} {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n margin-inline-end: 4px;\n }\n\n .${mu} {\n width: 40px;\n height: 40px;\n border: 0;\n border-radius: 999px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n background: transparent;\n color: var(--bard-color-on-surface-variant, #5f6368);\n cursor: pointer;\n transition:\n background-color 0.16s ease,\n color 0.16s ease,\n opacity 0.16s ease;\n }\n\n .${mu}:hover:not(:disabled),\n .${mu}:focus-visible:not(:disabled) {\n background: rgba(60, 64, 67, 0.08);\n color: var(--bard-color-on-surface, #202124);\n outline: none;\n }\n\n .${mu}:disabled {\n cursor: default;\n opacity: 0.38;\n }\n\n .${mu} svg {\n width: 18px;\n height: 18px;\n stroke: currentColor;\n }\n\n body.dark-theme .${mu},\n html.dark .${mu},\n html[dark-theme] .${mu} {\n color: rgba(232, 234, 237, 0.86);\n }\n\n body.dark-theme .${mu}:hover:not(:disabled),\n body.dark-theme .${mu}:focus-visible:not(:disabled),\n html.dark .${mu}:hover:not(:disabled),\n html.dark .${mu}:focus-visible:not(:disabled),\n html[dark-theme] .${mu}:hover:not(:disabled),\n html[dark-theme] .${mu}:focus-visible:not(:disabled) {\n background: rgba(232, 234, 237, 0.12);\n color: #ffffff;\n }\n `,"gh-gemini-deep-research-panel-actions-style");}syncDeepResearchPanelActions(e){const t=this.getDeepResearchPanelMarkdownElement(e),n=e.querySelector("toolbar .action-buttons");if(!(n instanceof HTMLElement&&t))return void this.removeDeepResearchPanelActions(e);if(e.querySelector(`[${fu}="1"]`))return void this.updateDeepResearchPanelActionDisabledState(e);const r=this.createDeepResearchPanelActions(e),o=n.querySelector('[data-test-id="export-menu-button"]');o?.parentElement===n?n.insertBefore(r,o):n.prepend(r),this.updateDeepResearchPanelActionDisabledState(e);}removeDeepResearchPanelActions(e){e.querySelectorAll(`[${fu}="1"]`).forEach(e=>{e.querySelectorAll(`.${mu}`).forEach(e=>{e instanceof HTMLElement&&this.deepResearchPanelTooltipBindings.get(e)?.destroy();}),e.remove();});}createDeepResearchPanelActions(e){const t=document.createElement("div");t.className=pu,t.setAttribute(fu,"1");const n=this.createDeepResearchPanelActionButton("copy"),r=this.createDeepResearchPanelActionButton("download");return n.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.copyDeepResearchPanelMarkdown(e,n);}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.downloadDeepResearchPanelMarkdown(e);}),t.append(n,r),t}createDeepResearchPanelActionButton(e){const t=document.createElement("button");t.type="button",t.className=mu,t.setAttribute("aria-label",this.getDeepResearchPanelActionLabel(e)),t.title=this.getDeepResearchPanelActionLabel(e),t.appendChild("copy"===e?sd({size:18}):this.createDeepResearchPanelDownloadIcon());const n=rd(t,{getContent:()=>this.getDeepResearchPanelActionLabel(e),preferredPlacement:"bottom"});return this.deepResearchPanelTooltipBindings.set(t,n),t}createDeepResearchPanelDownloadIcon(){const e=ad("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"});return [Ye,Xe,Je].forEach(t=>{e.appendChild(ad("path",{d:t}));}),e}getDeepResearchPanelActionLabel(e){return "copy"===e?le("exportToClipboard"):`${le("webdavDownloadBtn")} ${le("exportToMarkdown")}`}updateDeepResearchPanelActionDisabledState(e){const t=this.hasDeepResearchPanelContent(e);e.querySelectorAll(`.${mu}`).forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}async copyDeepResearchPanelMarkdown(e,t){const n=this.getDeepResearchPanelMarkdown(e);if(!n)return void Pi(le("exportNoContent"));const r=await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){return console.error("[Exporter] Failed to copy:",t),false}}(n);r?(ld(t,{size:18}),Pi(le("copySuccess"))):Pi(le("copyFailed"));}async downloadDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdown(e);if(!t)return void Pi(le("exportNoContent"));const n=await aa(function(e){return e?e.startsWith("\ufeff")?e:`\ufeff${e}`:"\ufeff"}(t),ya(this.getDeepResearchPanelTitle(e)||ba(t,"deep-research-report"),"deep-research-report"),"text/markdown;charset=utf-8");n&&Pi(le("exportSuccess"));}getDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdownElement(e);return t?this.extractAssistantResponseTextWithAssets(t).trim():""}hasDeepResearchPanelContent(e){const t=this.getDeepResearchPanelMarkdownElement(e);return Boolean(t?.textContent?.trim())}getDeepResearchPanelMarkdownElement(e){return Array.from(e.querySelectorAll("#extended-response-markdown-content, message-content .markdown")).find(e=>null===e.closest("thinking-panel"))||null}getDeepResearchPanelTitle(e){const t=this.getNormalizedText(e.querySelector("toolbar h2.title-text"));if(t)return t;return this.getNormalizedText(this.getDeepResearchPanelMarkdownElement(e)?.querySelector("h1"))||null}extractEmailFromAttr(e,t){return t&&("data-email"===e||"data-identifier"===e||Yd.test(t))?this.extractEmail(t):null}extractEmail(e){if(!e)return null;const t=e.match(Zd);return t?t[1].toLowerCase():null}match(){return window.location.hostname.includes("gemini.google")&&!window.location.hostname.includes("business.gemini.google")}getSiteId(){return ho}getName(){return "Gemini"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNativeThemeCss(){return "\n/* =============================================\n * Gemini 站点原生主题适配器 (Gemini Theme Adapter)\n * ============================================= */\n:root body.light-theme, :root body.dark-theme, :root {\n /* 1. 核心页面背景层 */\n --bard-color-lm-surface: var(--gh-bg) !important;\n --bard-color-lm-surface-bright: var(--gh-bg) !important;\n --bard-color-lm-surface-dim: var(--gh-bg-secondary) !important;\n --bard-color-footer-background: var(--gh-bg-secondary) !important;\n --bard-color-inverse-primary-background: var(--gh-bg-tertiary) !important;\n\n /* 2. 侧边栏与浮动层:使用极其微弱的主色调混合背景,避免大面积色块导致“太亮”或“太腻” */\n --bard-color-sidenav-background-desktop: color-mix(in srgb, var(--gh-primary) 5%, var(--gh-bg)) !important;\n\n --bard-color-icon-container-background: color-mix(in srgb, var(--gh-primary) 6%, var(--gh-bg)) !important;\n\n /* 3. 全局核心文字 */\n --bard-color-lm-on-surface: var(--gh-text) !important;\n --bard-color-sentence-prefix-color: var(--gh-text) !important;\n --bard-color-lm-on-surface-variant: var(--gh-text-secondary) !important;\n --bard-color-sentence-words-color: var(--gh-text-secondary) !important;\n --bard-color-image-lightbox-text: var(--gh-text-tertiary) !important;\n --bard-color-code-comment: var(--gh-text-tertiary) !important;\n\n /* 4. 品牌高亮与强调色(绑定我们插件的主题色段) */\n --bard-color-surface-tint: var(--gh-primary) !important;\n --bard-color-form-field-outline-active: var(--gh-primary) !important;\n --bard-color-brand-text-gradient-stop-1: var(--gh-primary) !important;\n --bard-color-chrome-experiment-badge: var(--gh-primary) !important;\n --bard-color-share-link: var(--gh-primary) !important;\n\n /* 5. 分叉对话、状态卡片相关 */\n --bard-color-zero-state-card-selected: var(--gh-active-bg) !important;\n --bard-color-zero-state-prompt-chip-background: var(--gh-hover) !important;\n\n /* 6. 其他元素 */\n --gem-sys-color--primary: var(--gh-primary) !important;\n /* 图标颜色 */\n --mat-icon-color: var(--gh-primary) !important;\n}\n\n/* 仅在 AI 回复容器内覆盖 surface-container-high(用于代码块背景),\n * 不在 :root 全局设置,以免影响用户气泡等其他使用该变量的元素 */\nmodel-response, .model-response-container {\n --gem-sys-color--surface-container-high: var(--gh-bg-tertiary) !important;\n}"}getNewTabUrl(){return `https://gemini.google.com${this.getUserPathPrefix()}/app`}isNewConversation(){const e=window.location.pathname.replace(/^\/u\/\d+/,"");if("/app"===e||"/app/"===e)return true;if("/gems/create"===e||"/gems/create/"===e)return true;if(e.startsWith("/gems/edit/"))return true;if(e.startsWith("/gem/")){return e.split("/").filter(Boolean).length<=2}return false}isUserConversationPage(){const e=window.location.pathname.replace(/^\/u\/\d+(?=\/)/,"");return !this.isSharePage()&&(/^\/app\/[^/?#]+(?:\/|$)/i.test(e)||/^\/gem\/[^/?#]+\/[^/?#]+(?:\/|$)/i.test(e))}getConversationList(){const e=ds.query('gem-nav-list-item[data-test-id="conversation"]',{all:true})||[],t=this.getCurrentCid(),n=this.getUserPathPrefix();return Array.from(e).map(e=>{const r=e.querySelector("a"),o=(r?.getAttribute("jslog")||e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),i=o?o[1]:"",a=e.querySelector(".title-text")?.textContent?.trim()||"",s=!!e.querySelector('mat-icon[fonticon="push_pin"]'),l=r?.classList.contains("mdc-list-item--activated")||false;return {id:i,cid:t,title:a,url:i?`https://gemini.google.com${n}/app/${i}`:"",isActive:l,isPinned:s}}).filter(e=>e.id)}getSidebarScrollContainer(){return ds.query('infinite-scroller[scrollable="true"]')||ds.query("infinite-scroller")||this.getChatsScrollableContainer()}async loadAllConversations(){if(!(await this.ensureChatsExpandableSectionOpen()))return false;const e=this.getSidebarScrollContainer();if(!e)return false;let t=0,n=0,r=0;for(let o=0;o<40;o++){e.scrollTop=e.scrollHeight,await this.sleep(900);const o=(ds.query('gem-nav-list-item[data-test-id="conversation"]',{all:true,shadow:true})||[]).length;if(o===t?n++:(t=o,n=0),this.isConversationHistoryLoading()?r=0:r++,n>=4&&r>=2)return o>0}return false}async ensureChatsExpandableSectionOpen(e=2500){if(this.getConversationList().length>0)return true;const t=this.getChatsExpandableSection();if(!t)return false;t.click();const n=Date.now();for(;Date.now()-n0)return true;await this.sleep(100);}return this.getConversationList().length>0}getChatsExpandableSection(){const e=[Eu,Au];for(const o of e){const e=document.querySelector(o);if(e instanceof HTMLElement)return e}const t=document.querySelector('conversations-list[data-test-id="all-conversations"]'),n=t?.closest("expandable-section");if(n instanceof HTMLElement)return n;const r=document.getElementsByTagName("expandable-section")[0];return r instanceof HTMLElement?r:null}isConversationHistoryLoading(){const e=document.querySelector('[data-test-id="loading-history-spinner"]');return e instanceof HTMLElement&&this.isVisible(e)}getChatsScrollableContainer(){const e=document.querySelector(['conversations-list[data-test-id="all-conversations"]',Eu,Au,'gem-nav-list-item[data-test-id="conversation"]'].join(","));if(!(e instanceof HTMLElement))return null;let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if((/(auto|scroll|overlay)/i.test(e.overflowY)||t.classList.contains("chat-history"))&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}getConversationObserverConfig(){return {selector:'gem-nav-list-item[data-test-id="conversation"]',shadow:false,extractInfo:e=>{const t=e.querySelector("a"),n=(t?.getAttribute("jslog")||e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),r=n?n[1]:"";if(!r)return null;const o=e.querySelector(".title-text")?.textContent?.trim()||"",i=!!e.querySelector('mat-icon[fonticon="push_pin"]');return {id:r,cid:this.getCurrentCid(),title:o,url:`https://gemini.google.com${this.getUserPathPrefix()}/app/${r}`,isPinned:i}},getTitleElement:e=>e.querySelector(".title-text")||e}}navigateToConversation(e,t){const n=document.querySelector(`gem-nav-list-item[data-test-id="conversation"] a[jslog*="${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Wd}}catch(RS){return console.error(`[GeminiAdapter] deleteConversationOnSiteInternal error for "${e.id}":`,RS),{id:e.id,success:false,method:"none",reason:jd}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let n=await this.findConversationMenuButton(t);if(!n)return false;const r=await this.openConversationMenu(t,n);if(!r)return false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o);if(!(await this.waitForDialogOpen(2200)))return false;const i=await this.waitForDeleteConfirmButton(2800);if(!i)return false;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4500),s=await this.waitForDialogClosed(1200),l=a||s;return l&&this.syncConversationListAfterDelete(e),l}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){const t=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"]'));if(t)return t;const r=o.find(t=>this.isLikelyMenuButton(t,e));if(r)return r;const i=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(i)return i;if(n>=8){const e=o[o.length-1];if(e)return e}}await this.sleep(100);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}isLikelyMenuButton(e,t){if(!t.contains(e))return false;if("menu"===e.getAttribute("aria-haspopup"))return true;const n=this.getSignalText(e);return n.includes("more")||n.includes("更多")||n.includes("选项")||n.includes("menu")||n.includes("菜单")}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,Qd))return e}return null}getMenuActionCandidates(e,t){const n='[role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(o){const e=document.getElementById(o);e&&r.push(...Array.from(e.querySelectorAll(n)));}const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=document.getElementById(t);return n instanceof HTMLElement?n:null}findVisibleMenuContainer(){const e=Array.from(document.querySelectorAll('[role="menu"], .mat-mdc-menu-panel, .mat-menu-panel')).filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForDialogOpen(e=2200){const t=Date.now();for(;Date.now()-tthis.isVisible(e));for(const o of n){const e=this.getSignalText(o);if(this.hasKeyword(e,Vd)&&!this.hasKeyword(e,Qd))return o}const r=n.filter(e=>!this.hasKeyword(this.getSignalText(e),Qd)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(r)return r;await this.sleep(80);}return null}async waitForDialogClosed(e=1200){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=4500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}getSessionName(){const e=document.querySelector("a.mdc-list-item--activated .title-text");if(e){const t=e.textContent?.trim();if(t)return t}const t=this.getDeepResearchDocumentShareTitle();if(t)return t;const n=document.querySelector("h1.headline, h1[class*='headline']");if(n){const e=n.textContent?.trim();if(e)return e}const r=this.getDeepResearchArtifactShareTitle();if(r)return r;const o=this.getGeminiNativeDocumentTitle();return o||super.getSessionName()}getGeminiNativeDocumentTitle(){const e=document.documentElement,t=e?.getAttribute(Ba),n=e?.getAttribute($a);return t&&n===window.location.pathname?ja(t,{siteName:this.getName()}):null}getConversationTitle(){const e=document.querySelector("a.mdc-list-item--activated .title-text");if(e){const t=e.textContent?.trim();if(t)return t}return this.getSessionName()}getNewChatButtonSelectors(){return ['gem-nav-list-item[data-test-id="new-chat-button"] a','[aria-label="New chat"]','[aria-label="新对话"]','[aria-label="发起新对话"]','[data-testid="new-chat-button"]','[data-test-id="new-chat-button"]','[data-test-id="expanded-button"]','[data-test-id="temp-chat-button"]','button[aria-label="临时对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll("model-response");if(0===t.length)return null;const n=t[t.length-1];return this.extractAssistantResponseText(n)||null}getWidthSelectors(){return [{selector:".conversation-container",property:"max-width"},{selector:".input-area-container",property:"max-width"},{selector:".table-block.new-table-style",property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important;"},{selector:"user-query",property:"max-width",value:"100%",noCenter:true,extraCss:"display: flex !important; justify-content: flex-end !important;"},{selector:".user-query-container",property:"max-width",value:"100%",noCenter:true,extraCss:"justify-content: flex-end !important;"}]}getUserQueryWidthSelectors(){return [{selector:".user-query-bubble-with-background:not(.edit-mode)",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["bard-sidenav","div.sidenav-with-history-container"]}}getCleanModeConfig(){return {hide:["hallucination-disclaimer","g1-dynamic-upsell-button",".share-viewer_footer_disclaimer",".share-landing-page_footer",'share-landing-page immersive-share-landing-page .page:has(structured-content-container[data-test-id="deep-research-block"]) > .footer']}}getMarkdownFixerConfig(){return {selector:"message-content p",fixSpanContent:false,shouldIgnore:e=>this.shouldIgnoreMarkdownFixElement(e)}}shouldIgnoreMarkdownFixElement(e){return null!==e.querySelector(Mu)}getAssistantMermaidSupportMode(){return "fallback"}getTextareaSelectors(){return ['div[contenteditable="true"].ql-editor','div[contenteditable="true"]','[role="textbox"]','[aria-label*="Enter a prompt"]']}getSubmitButtonSelectors(){return ['button[aria-label*="Send"]','button[aria-label*="发送"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if(null===e.offsetParent)return false;const t="true"===e.getAttribute("contenteditable"),n="textbox"===e.getAttribute("role");return !e.closest(".gh-main-panel")&&(t||n||e.classList.contains("ql-editor"))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}));}return true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),(document.activeElement===this.textarea||this.textarea.contains(document.activeElement))&&(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0))):this.textarea=null);}getScrollContainer(){return this.isSharePage()?document.querySelector("div.content-container"):document.querySelector("infinite-scroller.chat-history")}getResponseContainerSelector(){return this.isSharePage()?"div.content-container":"infinite-scroller.chat-history"}getChatContentSelectors(){return [".model-response-container","model-response",".response-container","[data-message-id]","message-content"]}getUserQuerySelector(){return "user-query"}getOutlineSources(){const e=[{id:"conversation",kind:"conversation",label:"对话",available:true}],t=this.extractDeepResearchDocumentOutline(6,false);return t.length>0&&e.push({id:bu,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=null!==this.getDeepResearchDocumentOutlineRoot();return `conversation:1|${bu}:${e?1:0}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===bu?this.extractDeepResearchDocumentOutline(t,r):this.extractOutline(t,n,r)}sanitizeUserQueryElement(e){const t=e.cloneNode(true);return t.querySelectorAll(".cdk-visually-hidden").forEach(e=>e.remove()),t}extractUserQueryText(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelector(".query-text")||t;return this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelectorAll(".query-text-line");if(0===n.length)return this.extractUserQueryText(t);const r=Array.from(n).map(e=>e.querySelector("br")&&""===e.textContent?.trim()?"":e.textContent?.trimEnd()??""),o=r.filter(e=>""!==e.trim());if(o.length>0){const e=o.reduce((e,t)=>{const n=t.match(/^(\s*)/);return Math.min(e,n?n[1].length:0)},1/0);if(e>0&&isFinite(e))return r.map(t=>""===t?"":t.slice(e)).join("\n")}return r.join("\n")}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}extractUserQueryExportContentWithAssets(e,t){const n=this.sanitizeUserQueryElement(e),r=this.extractUserQueryImageMarkdown(n,t),o=this.extractUserQueryFileMarkdown(n,t),i=this.extractUserQueryMarkdown(n).trim()||this.extractUserQueryText(n).trim();if(0===r.length&&0===o.length)return i;const a=o.length>0?`${le("exportAttachmentsLabel")}:\n${o.join("\n")}`:"";return [r.join("\n\n"),a,i].filter(Boolean).join("\n\n")}async extractUserQueryExportContentWithResolvedAssets(e,t){const n=this.sanitizeUserQueryElement(e),r=this.extractUserQueryImageMarkdown(n,t),o=await this.extractUserQueryFileMarkdownWithResolvedAssets(e,n,t),i=this.extractUserQueryMarkdown(n).trim()||this.extractUserQueryText(n).trim();if(0===r.length&&0===o.length)return i;const a=o.length>0?`${le("exportAttachmentsLabel")}:\n${o.join("\n")}`:"";return [r.join("\n\n"),a,i].filter(Boolean).join("\n\n")}async prepareConversationExport(e){this.exportOpenedCanvasPanel=false,await this.prepareImagesForExport(e);const t={openedDeepResearchPanel:false};return this.isDeepResearchAppPage()&&!this.getDeepResearchAppDocumentElement()&&(t.openedDeepResearchPanel=await this.openDeepResearchAppDocumentPanel()),t}async restoreConversationAfterExport(e,t){this.clearPreparedExportImageMetadata(),this.isGeminiExportLifecycleState(t)&&t.openedDeepResearchPanel&&await this.closeDeepResearchAppDocumentPanel(),this.exportOpenedCanvasPanel&&(await this.closeGeminiCanvasPanel(),this.exportOpenedCanvasPanel=false);}async prepareImagesForExport(e){this.clearPreparedExportImageMetadata();const t=Array.from(document.querySelectorAll(["model-response img",`share-landing-page ${ru} img`,eu].join(", "))).filter(e=>e instanceof HTMLImageElement);for(const n of t)try{const t=await this.resolvePreparedExportImageSrc(n,e);if(!t)continue;n.setAttribute(Kd,t);}catch(RS){console.warn("[GeminiAdapter] Failed to prepare export image source",RS);}}clearPreparedExportImageMetadata(){document.querySelectorAll(`[${Kd}]`).forEach(e=>{e.removeAttribute(Kd);});}extractUserQueryImageMarkdown(e,t){const n=Array.from(e.querySelectorAll("img[data-test-id='uploaded-img'], .preview-image")).filter(e=>e instanceof HTMLImageElement),r=[],o=new Set;for(const i of n){const e=this.getPreparedExportImageSrc(i);if(!e||o.has(e))continue;o.add(e);const n=(i.alt||"uploaded image").replace(/\s+/g," ").trim().replace(/[[\]]/g,"\\$&"),a=t?this.addImageExportAsset(t,e,n||"uploaded image"):e;r.push(`![${n||"uploaded image"}](${a})`);}return r}addImageExportAsset(e,t,n){const r=e.imagePathsBySource.get(t);if(r)return r;const o=e.imagePathsBySource.size+1,i=this.getImageExportExtension(t),a=`gemini-image-${String(o).padStart(3,"0")}.${i}`,s=this.createUniqueGeminiExportPath(`assets/images/${a}`,e),l=s.split("/").pop()||a;return e.imagePathsBySource.set(t,s),e.assets.push({id:`gemini-image-${o}`,name:l,relativePath:s,mimeType:this.getImageExportMimeType(t,i),kind:"image",content:t.startsWith("data:image/")?this.dataUrlToExportBlob(t):void 0,sourceUrl:t.startsWith("data:image/")?void 0:t,description:n}),s}getImageExportExtension(e){if(e.startsWith("data:image/")){const t=e.match(/^data:image\/([a-zA-Z0-9.+-]+)[;,]/);return this.normalizeImageExtension(t?.[1]||"png")}try{const t=new URL(e,window.location.href).pathname,n=t.match(/\.([a-zA-Z0-9]+)$/)?.[1];return this.normalizeImageExtension(n||"png")}catch{return "png"}}normalizeImageExtension(e){const t=e.toLowerCase().replace(/^jpg$/,"jpeg").replace(/^svg\+xml$/,"svg");return ["png","jpeg","webp","gif","avif","svg"].includes(t)?"jpeg"===t?"jpg":t:"png"}getImageExportMimeType(e,t){return e.startsWith("data:image/")?e.slice(5,e.indexOf(";")):"svg"===t?"image/svg+xml":"jpg"===t?"image/jpeg":`image/${t}`}dataUrlToExportBlob(e){const[t,n=""]=e.split(",",2),r=t.match(/^data:([^;]+)/)?.[1]||"application/octet-stream";if(!/;base64/i.test(t))return new Blob([decodeURIComponent(n)],{type:r});const o=atob(n),i=new Uint8Array(o.length);for(let a=0;a"document"===e.kind&&e.name===o&&e.content===t);if(i?.relativePath)return i.relativePath;const a=this.createUniqueGeminiExportPath(`assets/documents/${o}`,e),s=a.split("/").pop()||o;return e.assets.push({id:`gemini-document-${e.assets.length+1}`,name:s,relativePath:a,mimeType:r||this.getExportAssetMimeType("",s,"document"),kind:"document",content:t,description:n||void 0}),a}async extractUserQueryViewerDocument(e,t){const n=this.getUserQueryFilePreviewTrigger(e);if(!n)return null;const r=document.querySelector("immersive-panel .drive-viewer");n.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),this.simulateClick(n);const o=await this.waitForDriveViewer(r)||r;if(!o)return null;try{const e=await this.waitForDriveViewerDocument(o,t);return e||console.warn("[GeminiAdapter] Failed to extract uploaded file viewer document",{name:t,viewerTextContainers:document.querySelectorAll("immersive-panel .drive-viewer-text-content").length,visibleViewers:Array.from(document.querySelectorAll("immersive-panel .drive-viewer")).filter(e=>this.isVisible(e)).length}),e?{name:e.name||t,mimeType:e.mimeType,content:e.content}:null}finally{await this.closeDriveViewer(o);}}getUserQueryFilePreviewTrigger(e){return [e.matches("button, [role='button']")?e:null,e.querySelector("button"),e.querySelector("[role='button']")].find(e=>e instanceof HTMLElement)||null}async waitForDriveViewer(e,t=3e3){const n=Date.now();for(;Date.now()-nt!==e);if(n)return n;if(!e&&t[0])return t[0];await new Promise(e=>setTimeout(e,100));}return null}async waitForDriveViewerDocument(e,t,n=5e3){const r=Date.now();for(;Date.now()-rthis.isVisible(e)))return null;await new Promise(e=>setTimeout(e,100));}return null}findActiveDriveViewerTextContent(e){const t=Array.from(document.querySelectorAll("immersive-panel .drive-viewer")),n=e.replace(/\.[A-Za-z0-9]{1,10}$/,""),r=t.find(t=>{const r=this.extractDriveViewerDocumentName(t);return r===e||r===n||r.startsWith(`${n}.`)||e.startsWith(`${r}.`)})||t[t.length-1],o=Array.from((r||document).querySelectorAll(".drive-viewer-text-content pre, .drive-viewer-text-content"));return o.find(e=>this.isVisible(e))||o.find(e=>this.decodeDriveViewerText(e.textContent||""))||null}decodeDriveViewerText(e){return e.replace(/\r\n/g,"\n").trim()}extractDriveViewerDocumentName(e){const t=this.parseDriveActiveItemInfo(e),n=this.getNormalizedText(e.querySelector(".drive-viewer-toolstrip-name"));return t?.title||n||""}extractDriveViewerDocumentMimeType(e){return this.parseDriveActiveItemInfo(e)?.mimeType}parseDriveActiveItemInfo(e){const t=Array.from(e.querySelectorAll('[id="drive-active-item-info"], div[style*="display:none"]')).map(e=>e.textContent?.trim()||"").find(e=>e.startsWith("{")&&e.includes('"title"'));if(!t)return null;try{const e=JSON.parse(t);return e&&"object"==typeof e?e:null}catch{return null}}async closeDriveViewer(e){const t=e.querySelector(".drive-viewer-close-button");t instanceof HTMLElement&&(this.simulateClick(t),await new Promise(e=>setTimeout(e,150)));}addFileExportAsset(e,t,n,r,o="file"){const i=e.filePathsBySource.get(t);if(i)return i;const a=this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(n||"gemini-file"),t,r),s=this.createUniqueGeminiExportPath(`assets/files/${a}`,e),l=s.split("/").pop()||a,c=this.getExportAssetMimeType(t,r||l,o);return e.filePathsBySource.set(t,s),e.assets.push({id:`gemini-${o||"file"}-${e.filePathsBySource.size}`,name:l,relativePath:s,mimeType:c,kind:o,content:t.startsWith("data:")?this.dataUrlToExportBlob(t):void 0,sourceUrl:t.startsWith("data:")?void 0:t,description:n||void 0}),s}sanitizeGeminiExportFilename(e){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim().substring(0,120)}ensureExportFilenameExtension(e,t,n){const r=e||"gemini-file";if(/\.[A-Za-z0-9]{1,10}$/.test(r))return r;const o=this.getExportAssetExtension(t)||this.getExtensionFromMimeType(n||"");return o?`${r}.${o}`:r}getExportAssetExtension(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;,]+)/)?.[1]||"";return this.getExtensionFromMimeType(t)}try{const t=new URL(e,window.location.href).pathname;return t.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toLowerCase()||""}catch{return ""}}getExportAssetMimeType(e,t,n){if(e.startsWith("data:"))return e.match(/^data:([^;,]+)/)?.[1]||void 0;const r=t.toLowerCase(),o=r.match(/\.([a-z0-9]{1,10})$/)?.[1]||r,i=o?this.getMimeTypeFromExtension(o):"";return i||("audio"===n?"audio/mpeg":"video"===n?"video/mp4":void 0)}getMimeTypeFromExtension(e){return {avif:"image/avif",csv:"text/csv",gif:"image/gif",htm:"text/html",html:"text/html",jpeg:"image/jpeg",jpg:"image/jpeg",json:"application/json",m4a:"audio/mp4",md:"text/markdown;charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",ogg:"audio/ogg",pdf:"application/pdf",png:"image/png",txt:"text/plain;charset=utf-8",wav:"audio/wav",webm:"video/webm",webp:"image/webp"}[e.toLowerCase()]||""}getExtensionFromMimeType(e){return {"application/json":"json","application/pdf":"pdf","audio/mpeg":"mp3","audio/mp4":"m4a","audio/ogg":"ogg","audio/wav":"wav","image/avif":"avif","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/svg+xml":"svg","image/webp":"webp","text/csv":"csv","text/html":"html","text/markdown":"md","text/plain":"txt","video/mp4":"mp4","video/webm":"webm"}[e.toLowerCase().split(";")[0].trim()]||""}extractUserQueryFileName(e){const t=this.extractUserQueryFileAriaName(e);if(t)return t;return [this.getNormalizedText(e.querySelector('[data-test-id="filename-label"]')),this.getNormalizedText(e.querySelector(".filename-label")),this.getNormalizedText(e.querySelector(".new-file-name"))].find(Boolean)||""}extractUserQueryFileAriaName(e){return Array.from(e.querySelectorAll("a[aria-label], button[aria-label]")).map(e=>e.getAttribute("aria-label")||"").map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).find(e=>!Xd.test(e))||""}extractUserQueryFileType(e){const t=this.getNormalizedText(e.querySelector(".new-file-type"));if(t)return t;const n=e.querySelector('[data-test-id="luminous-file-icon"]')?.getAttribute("alt");return (n||"").replace(/icon|图标|圖標|アイコン|아이콘|símbolo|ícone|symbol|значок/gi,"").replace(/\s+/g," ").trim()}fileNameEndsWithType(e,t){const n=e.toLowerCase(),r=t.replace(/^\./,"").toLowerCase();return !!r&&n.endsWith(`.${r}`)}extractUserQueryFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=this.normalizeExportAssetUrl(n.href||n.getAttribute("href")||"");if(this.isDownloadableExportAssetUrl(e))return e}return ""}escapeMarkdownLinkText(e){return e.replace(/[[\]]/g,"\\$&")}getPreparedExportImageSrc(e){const t=this.getDisplayedProcessedImageDataUrl(e);if(t)return t;const n=[e.getAttribute(Kd)||"",e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const r of n){const e=this.normalizeExportImageUrl(r);if(this.isStablePreparedExportImageUrl(e))return e}return ""}async resolvePreparedExportImageSrc(e,t){const n=await this.resolveWatermarkRemovedExportImageSrc(e);if(n)return n;const r=[this.getPreparedExportImageSrc(e)],o=[e.getAttribute(Kd)||"",e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const a of r){const n=this.normalizeExportImageUrl(a);if(n){if(this.shouldInlineUserQueryImageForExport(e,t))return this.resolveExportImageDataUrl(n,e);if(this.isStablePreparedExportImageUrl(n))return n}}const i=o.map(e=>this.normalizeExportImageUrl(e)).find(e=>e.startsWith("blob:"));return i?this.convertBlobUrlToDataUrl(i,e):""}shouldTryWatermarkRemovalForExport(e){return !e.closest("user-query")&&(e.closest("model-response")?null!==e.closest(Jd):null!==e.closest(`share-landing-page ${ru}`))}getDisplayedProcessedImageDataUrl(e){if("1"!==e.getAttribute("data-ophel-wm-processed"))return "";return [e.currentSrc||"",e.src||"",e.getAttribute("src")||""].map(e=>this.normalizeExportImageUrl(e)).find(e=>e.startsWith("data:image/"))||""}async resolveWatermarkRemovedExportImageSrc(e){if(!this.shouldTryWatermarkRemovalForExport(e))return "";const t=this.getDisplayedProcessedImageDataUrl(e);if(t)return t;const n=Hd.getActiveInstance();if(!n)return "";const r=[e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute(Kd)||""],o=new Set;for(const i of r){const e=this.normalizeExportImageUrl(i);if(!e||o.has(e))continue;if(o.add(e),e.startsWith("data:image/"))continue;const t=await n.resolveProcessedImageDataUrl(e,{scene:"export"});if(t?.startsWith("data:image/"))return t}return ""}shouldInlineUserQueryImageForExport(e,t){return "markdown"===t.format&&"markdown"===t.packaging&&null!==e.closest("user-query")}async resolveExportImageDataUrl(e,t){if(e.startsWith("data:image/"))return e;if(e.startsWith("blob:"))return this.convertBlobUrlToDataUrl(e,t);if(!/^https?:\/\//i.test(e))return "";try{const t=await $i.fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.blob();return this.convertBlobToDataUrl(n)}catch(RS){return console.warn("[GeminiAdapter] Failed to inline user query image for Markdown export",RS),e}}normalizeExportImageUrl(e){if(!e)return "";if(e.startsWith("blob:")||e.startsWith("data:image/"))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}normalizeExportAssetUrl(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}isDownloadableExportAssetUrl(e){if(!e)return false;if(/^(blob:|data:)/i.test(e))return true;if(!/^https?:\/\//i.test(e))return false;try{const t=new URL(e);return (t.hostname!==window.location.hostname||!/^\/?(app|share)(\/|$)/.test(t.pathname))&&!/faviconV2|google_logo_icon|\/32\/type\//i.test(t.href)}catch{return false}}isStablePreparedExportImageUrl(e){return !!e&&(!!e.startsWith("data:image/")||(!!Tu.test(e)||/^https?:\/\//i.test(e)))}async convertImageElementToDataUrl(e){(!e.complete||e.naturalWidth<=0||e.naturalHeight<=0)&&await e.decode();const t=e.naturalWidth||e.width||e.clientWidth,n=e.naturalHeight||e.height||e.clientHeight;if(t<=0||n<=0)throw new Error("Image has no exportable size");const r=document.createElement("canvas");r.width=t,r.height=n;const o=r.getContext("2d");if(!o)throw new Error("2D canvas context unavailable");return o.drawImage(e,0,0,t,n),r.toDataURL("image/png")}async convertBlobUrlToDataUrl(e,t){if(t)try{return await this.convertImageElementToDataUrl(t)}catch{}const n=await fetch(e),r=await n.blob();return this.convertBlobToDataUrl(r)}async convertBlobToDataUrl(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{"string"!=typeof r.result?n(new Error("Failed to convert blob image to data URL")):t(r.result);},r.onerror=()=>n(r.error||new Error("Failed to read blob image")),r.readAsDataURL(e);})}sanitizeAssistantExportElement(e){const t=e.cloneNode(true);return t.querySelectorAll(yu).forEach(e=>e.remove()),this.normalizeDeepResearchConfirmationWidgetsForExport(t),this.normalizeAssistantGeneratedImagesForExport(t),t}normalizeDeepResearchConfirmationWidgetsForExport(e){e.querySelectorAll(su).forEach(e=>{const t=document.createElement("div");t.className="ophel-gemini-deep-research-plan";const n=this.getNormalizedText(e.querySelector('[data-test-id="title"]'));if(n){const e=document.createElement("h3");e.textContent=n,t.appendChild(e);}Array.from(e.querySelectorAll('[data-test-id="research-steps"] .research-step')).forEach((e,n)=>{const r=this.extractDeepResearchStepTitle(e);if(r){const e=document.createElement("h4");e.textContent=`${n+1}. ${r}`,t.appendChild(e);}const o=this.normalizeExportMultilineText(e.querySelector(".research-step-description")?.textContent||"");if(o){const e=document.createElement("p");e.textContent=o,t.appendChild(e);}}),t.childNodes.length>0&&e.replaceWith(t);});}extractDeepResearchStepTitle(e){const t=e.querySelector(".research-step-title"),n=Array.from(t?.children||[]).find(e=>"mat-icon"!==e.tagName.toLowerCase());return this.getNormalizedText(n||t)}getNormalizedText(e){return (e?.textContent||"").replace(/\s+/g," ").trim()}normalizeExportMultilineText(e){return e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).join("\n").replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}normalizeAssistantGeneratedImagesForExport(e){e.querySelectorAll(vu).forEach(e=>e.remove()),e.querySelectorAll(`img[${Kd}]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=e.getAttribute(Kd)||"";t&&(e.setAttribute("src",t),e.removeAttribute("srcset"),e.removeAttribute(Kd));}),e.querySelectorAll(`${Jd} button.image-button`).forEach(e=>{if(!(e instanceof HTMLButtonElement&&e.parentNode))return;const t=e.querySelector("img");if(!(t instanceof HTMLImageElement))return;const n=t.cloneNode(true),r=n.getAttribute(Kd)||"";r&&(n.setAttribute("src",r),n.removeAttribute("srcset"),n.removeAttribute(Kd)),e.replaceWith(n);}),e.querySelectorAll("share-button, copy-button, download-generated-image-button, .generated-image-controls, .loader").forEach(e=>e.remove());}shouldSkipOutlineHeading(e){return !!this.isInRenderedMarkdownContainer(e)||!!e.classList.contains("cdk-visually-hidden")}getDeepResearchDocumentOutlineRoot(){const e=this.getDeepResearchAppDocumentElement();return e||(this.isDeepResearchDocumentSharePage()?document.querySelector(`${ou} ${au}`):this.isDeepResearchConversationSharePage()?document.querySelector(`${iu} ${au}`):null)}extractDeepResearchDocumentOutline(e=6,t=false){const n=this.getDeepResearchDocumentOutlineRoot();return n?Il(n,{maxLevel:e,showWordCount:t,idPrefix:"gemini-document",shouldSkipHeading:e=>this.shouldSkipOutlineHeading(e),calculateWordCount:(e,t,n)=>this.calculateRangeWordCount(e,t,n)}):[]}findDeepResearchDocumentHeading(e,t){const n=this.getDeepResearchDocumentOutlineRoot();return n?Ll(n,e,t,e=>this.shouldSkipOutlineHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===bu){return Nl(this.getDeepResearchDocumentOutlineRoot())||null}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===bu?this.findDeepResearchDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===bu){if(Rl(e,Nl(e)||this.getOutlineScrollContainer(t)))return}this.scrollToOutlineTarget(e);}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantResponseTextWithAssets(e,t){const n=this.sanitizeAssistantExportElement(e);return t&&(this.replaceAssistantImageSourcesWithExportAssets(n,t),this.replaceAssistantMediaSourcesWithExportAssets(n,t),this.replaceAssistantDownloadLinksWithExportAssets(n,t)),this.extractMarkdownExportContent(n)}async extractExportMessages(e){return this.isDeepResearchDocumentSharePage()?this.extractDeepResearchDocumentShareMessages():this.isDeepResearchConversationSharePage()?this.extractDeepResearchConversationShareMessages():this.isGeminiConversationSharePage()?this.extractGeminiConversationShareMessages():this.isDeepResearchAppPage()?this.extractDeepResearchAppMessages():this.hasGeminiCanvasAppArtifacts()?this.extractGeminiConversationMessages():null}async extractExportBundle(e){const t={assets:[],imagePathsBySource:new Map,filePathsBySource:new Map,usedPaths:new Set},n=await this.extractExportMessagesWithAssets(e,t);return n?{messages:n,assets:t.assets}:null}async extractExportMessagesWithAssets(e,t){return this.isDeepResearchDocumentSharePage()?this.extractDeepResearchDocumentShareMessages(t):this.isDeepResearchConversationSharePage()?this.extractDeepResearchConversationShareMessages(t):this.isGeminiConversationSharePage()?this.extractGeminiConversationShareMessages(t):this.isDeepResearchAppPage()?this.extractDeepResearchAppMessages(t):this.extractGeminiConversationMessages(t)}async extractGeminiConversationMessages(e){const t=document.querySelector(this.getResponseContainerSelector())||this.getScrollContainer();if(!t)return null;const n=Array.from(t.querySelectorAll("user-query, model-response")).sort((e,t)=>this.compareDomOrder(e,t));if(0===n.length)return null;const r=[];for(const i of n){if(i.closest("immersive-panel"))continue;const t="user-query"===i.tagName.toLowerCase()?"user":"assistant",n="user"===t?(e?await this.extractUserQueryExportContentWithResolvedAssets(i,e):this.extractUserQueryExportContentWithAssets(i)).trim():this.joinExportSections(this.extractAssistantResponseTextWithAssets(i,e),await this.extractGeminiCanvasAppArtifactsFromResponse(i));n&&r.push({role:t,content:n});}const o=this.dedupeAdjacentExportMessages(r);return o.length>0?o:null}replaceAssistantImageSourcesWithExportAssets(e,t){Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement).forEach(e=>{if(this.isDecorativeExportImage(e))return;const n=this.getPreparedExportImageSrc(e);if(!n)return;const r=(e.alt||"image").replace(/\s+/g," ").trim(),o=this.addImageExportAsset(t,n,r);e.setAttribute("src",o),e.removeAttribute("srcset");});}replaceAssistantMediaSourcesWithExportAssets(e,t){Array.from(e.querySelectorAll("audio, video")).filter(e=>e instanceof HTMLMediaElement).forEach(e=>{const n=this.extractAssistantMediaSource(e);if(!n)return;const r="video"===e.tagName.toLowerCase()?"video":"audio",o=this.buildAssistantMediaAssetName(e,r,n.source),i=this.addFileExportAsset(t,n.source,o,n.mimeType,r);e.replaceWith(this.createExportAssetLinkElement(o,i));});}replaceAssistantDownloadLinksWithExportAssets(e,t){Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement).forEach(e=>{if(!this.isAssistantExportDownloadLink(e))return;const n=this.normalizeExportAssetUrl(e.getAttribute("href")||e.href||"");if(!this.isDownloadableExportAssetUrl(n))return;const r=this.buildAssistantDownloadAssetName(e,n),o=this.inferExportAssetKind(n,r),i=this.addFileExportAsset(t,n,r,void 0,o);e.setAttribute("href",i),e.setAttribute(Ui,i),e.removeAttribute("target"),e.removeAttribute("rel");});}extractAssistantMediaSource(e){const t=[e.currentSrc||"",e.getAttribute("src")||"","src"in e?String(e.src||""):""],n=Array.from(e.querySelectorAll("source[src]")).filter(e=>e instanceof HTMLSourceElement),r=[...t.map(t=>({source:t,mimeType:e.getAttribute("type")||""})),...n.map(e=>({source:e.getAttribute("src")||e.src||"",mimeType:e.type||""}))];for(const o of r){const e=this.normalizeExportAssetUrl(o.source);if(this.isDownloadableExportAssetUrl(e))return {source:e,mimeType:o.mimeType||void 0}}return null}buildAssistantMediaAssetName(e,t,n){const r=e.getAttribute("aria-label")||e.getAttribute("title")||("video"===t?"gemini-video":"gemini-audio");return this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(r),n)}buildAssistantDownloadAssetName(e,t){const n=e.getAttribute("download")||e.getAttribute("aria-label")||e.getAttribute("title")||e.textContent||"gemini-file";return this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(n),t)}createExportAssetLinkElement(e,t){const n=document.createElement("p"),r=document.createElement("a");return r.setAttribute("href",t),r.setAttribute(Ui,t),r.textContent=e,n.appendChild(r),n}isAssistantExportDownloadLink(e){if(e.getAttribute("href")?.startsWith("assets/"))return false;if(e.hasAttribute("download"))return true;const t=[e.getAttribute("data-test-id")||"",e.getAttribute("data-testid")||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.className||""].join(" ").toLowerCase();if(!/(download|attachment|file|document|audio|video|下载|下載)/i.test(t))return false;const n=this.normalizeExportAssetUrl(e.getAttribute("href")||e.href||"");return this.isDownloadableExportAssetUrl(n)}inferExportAssetKind(e,t){const n=(this.getExportAssetExtension(e)||t.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"").toLowerCase();return ["mp3","m4a","ogg","wav"].includes(n)?"audio":["mp4","webm"].includes(n)?"video":["md","pdf","txt","csv","json","html","htm"].includes(n)?"document":"file"}isDecorativeExportImage(e){if(e.matches(vu))return true;const t=this.getPreparedExportImageSrc(e);if(!t)return true;const n=e.className||"",r=e.getAttribute("data-test-id")||"";if("presentation"===(e.getAttribute("role")||"")&&/(^|\s)(favicon|icon|google-icon)(\s|$)/.test(String(n))&&/favicon|icon|file/i.test(r))return true;return !("image/svg+xml"!==(t.startsWith("data:image/")?t.slice(5,t.indexOf(";")).toLowerCase():"")||!e.classList.contains("katex-svg"))}hasGeminiCanvasAppArtifacts(){if(this.isSharePage())return false;const e=document.querySelector(this.getResponseContainerSelector())||this.getScrollContainer();return !!e&&this.getGeminiCanvasCardsFromResponse(e).length>0}getGeminiCanvasCardsFromResponse(e){return Array.from(e.querySelectorAll('[data-test-id="gem-processing-card"]')).filter(e=>e instanceof HTMLElement&&null!==e.querySelector(uu))}getGeminiCanvasShareArtifactElements(e){const t=new Set;return e instanceof Element&&e.classList.contains("immersive-artifact-container")&&t.add(e),e.querySelectorAll("share-landing-page .immersive-artifact-container, .immersive-artifact-container").forEach(e=>t.add(e)),Array.from(t).filter(e=>e instanceof HTMLElement&&null!==e.querySelector(uu))}async extractGeminiCanvasAppArtifactsFromResponse(e){const t=this.getGeminiCanvasCardsFromResponse(e);if(0===t.length)return "";const n=[];for(const r of t){const e=this.extractGeminiCanvasTitle(r);try{const t=await this.openGeminiCanvasCardForExport(r);if(!t)continue;await this.selectGeminiCanvasCodeTab(t);const o=await this.extractGeminiCanvasCodeArtifact(t,e);o&&n.push(o);}catch(RS){console.warn("[GeminiAdapter] Failed to export Gemini Canvas artifact",RS);}}return n.length>0?this.formatGeminiCanvasCodeArtifacts(n):this.formatGeminiCanvasFallbackTitles(t.map(e=>this.extractGeminiCanvasTitle(e)))}async extractGeminiCanvasShareArtifactsFromTurn(e){const t=this.getGeminiCanvasShareArtifactElements(e);if(0===t.length)return "";const n=[];for(const r of t)try{await this.selectGeminiCanvasCodeTab(r);const e=await this.extractGeminiCanvasCodeArtifact(r,this.extractGeminiCanvasTitle(r));e&&n.push(e);}catch(RS){console.warn("[GeminiAdapter] Failed to export Gemini Canvas share artifact",RS);}return n.length>0?this.formatGeminiCanvasCodeArtifacts(n):this.formatGeminiCanvasFallbackTitles(t.map(e=>this.extractGeminiCanvasTitle(e)))}getGeminiCanvasPanelElement(){const e=document.querySelector(hu);return e instanceof HTMLElement?e:null}async openGeminiCanvasCardForExport(e){const t=null!==this.getGeminiCanvasPanelElement(),n=this.extractGeminiCanvasTitle(e),r=this.getGeminiCanvasPanelElement();if(r&&this.isGeminiCanvasPanelForTitle(r,n))return r;e.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await this.sleep(60);for(const o of this.getGeminiCanvasCardClickTargets(e)){this.simulateClick(o);const e=await this.waitForGeminiCanvasPanel(n);if(e)return t||(this.exportOpenedCanvasPanel=true),e}return null}getGeminiCanvasCardClickTargets(e){const t=e.closest("immersive-entry-chip"),n=[e,t].filter(e=>e instanceof HTMLElement),r=new Set;return n.filter(e=>!r.has(e)&&(r.add(e),true))}async waitForGeminiCanvasPanel(e,t=3e3){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement);if(e.length>=2)return e[0]}return null}isGeminiCanvasCodeTabSelected(e){if(e.classList.contains("mat-button-toggle-checked"))return true;const t=e.querySelector("button[role='radio']");return "true"===t?.getAttribute("aria-checked")}hasGeminiCanvasCodeSurface(e){return null!==this.findGeminiCanvasCodeBlock(e)||null!==this.findGeminiCanvasCodeEditor(e)}async extractGeminiCanvasCodeArtifact(e,t){const n=this.findGeminiCanvasCodeBlock(e);if(n)return this.extractGeminiCanvasCodeBlockArtifact(n,t);const r=this.findGeminiCanvasCodeEditor(e);return r?this.extractGeminiCanvasCodeEditorArtifact(r,t):null}findGeminiCanvasCodeBlock(e){if(e instanceof HTMLElement&&e.matches("code-block"))return e;const t=e.querySelector("code-block");return t instanceof HTMLElement?t:null}findGeminiCanvasCodeEditor(e){if(e instanceof HTMLElement&&e.matches(gu))return e.classList.contains("hidden")?null:e;const t=e.querySelector(gu);return t instanceof HTMLElement&&!t.classList.contains("hidden")?t:null}extractGeminiCanvasCodeBlockArtifact(e,t){const n=e.querySelector('[data-test-id="code-content"], pre code, code'),r=this.normalizeGeminiCanvasCode(this.extractTextWithLineBreaks(n||e));return r?{title:this.extractGeminiCanvasTitle(e,t),language:this.extractGeminiCanvasCodeLanguage(e)||"text",code:r}:null}async extractGeminiCanvasCodeEditorArtifact(e,t){const n=await this.extractGeminiCanvasMainWorldMonacoCode(e)||this.extractGeminiCanvasMonacoModelCode(e)||await this.extractGeminiCanvasRenderedMonacoCode(e);return n?{title:this.extractGeminiCanvasTitle(e,t),language:this.extractGeminiCanvasCodeLanguage(e)||"text",code:n}:null}async extractGeminiCanvasMainWorldMonacoCode(e){if(!document.documentElement.hasAttribute("data-ophel-gemini-canvas-main"))return "";const t=e.querySelector(".monaco-editor")?.getAttribute("data-uri")||"";if(!t)return "";const n=`ophel-gemini-canvas-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(e=>{let r=false,o=0;const i=t=>{r||(r=true,window.clearTimeout(o),window.removeEventListener("message",a),e(this.normalizeGeminiCanvasCode(t)));},a=e=>{if(e.origin&&e.origin!==window.location.origin)return;const t=e.data;t?.type===Q&&t.requestId===n&&i("string"==typeof t.code?t.code:"");};o=window.setTimeout(()=>i(""),900),window.addEventListener("message",a),window.postMessage({type:V,requestId:n,editorUri:t},"*");})}extractGeminiCanvasMonacoModelCode(e){const t=window,n=t.monaco?.editor?.getModels?.();if(!n?.length)return "";const r=e.querySelector(".monaco-editor")?.getAttribute("data-uri")||"",o=n.find(e=>{const t=e;return r&&t.uri?.toString?.()===r})||(1===n.length?n[0]:null),i=o?.getValue;return "function"!=typeof i?"":this.normalizeGeminiCanvasCode(i.call(o))}async extractGeminiCanvasRenderedMonacoCode(e){const t=e.querySelector("textarea.inputarea");if(t instanceof HTMLTextAreaElement&&t.value.trim())return this.normalizeGeminiCanvasCode(t.value);const n=e.querySelector(".monaco-scrollable-element");if(!(n instanceof HTMLElement))return this.normalizeGeminiCanvasCode(this.extractGeminiCanvasVisibleMonacoLines(e).join("\n"));const r=n.scrollTop,o=Math.max(n.clientHeight,1),i=this.getGeminiCanvasMonacoContentHeight(e),a=Math.max(i-o,n.scrollHeight,0),s=Math.max(Math.floor(.8*o),120),l=[];for(let c=0;c<=a;c+=s){n.scrollTop=c,n.dispatchEvent(new Event("scroll",{bubbles:true})),await this.sleep(40);const t=this.extractGeminiCanvasVisibleMonacoLines(e);t.length>0&&l.push(t.join("\n"));}return n.scrollTop=r,n.dispatchEvent(new Event("scroll",{bubbles:true})),this.normalizeGeminiCanvasCode(this.mergeGeminiCanvasRenderedCodeChunks(l))}extractGeminiCanvasVisibleMonacoLines(e){return Array.from(e.querySelectorAll(".view-lines .view-line")).filter(e=>e instanceof HTMLElement).sort((e,t)=>this.getElementTop(e)-this.getElementTop(t)).map(e=>this.normalizeGeminiCanvasCodeLine(e.textContent||""))}getGeminiCanvasMonacoContentHeight(e){const t=Array.from(e.querySelectorAll(".view-lines, .margin, .lines-content")).flatMap(e=>e instanceof HTMLElement?[e.scrollHeight,e.offsetHeight,this.parseCssPixelValue(e.style.height)]:[]);return Math.max(...t,0)}mergeGeminiCanvasRenderedCodeChunks(e){const t=[];for(const n of e){const e=n.split("\n");let r=0;for(let n=Math.min(t.length,e.length);n>0;n-=1){if(t.slice(t.length-n).join("\n")===e.slice(0,n).join("\n")){r=n;break}}t.push(...e.slice(r));}return t.join("\n")}getElementTop(e){return this.parseCssPixelValue(e.style.top)}parseCssPixelValue(e){const t=e.match(/-?\d+(?:\.\d+)?/);return t?Number(t[0]):0}extractGeminiCanvasTitle(e,t="Gemini Canvas"){return (e.querySelector(".title-text, .card-title")?.textContent?.trim()||e.closest(".immersive-artifact-container")?.querySelector(".title-text")?.textContent?.trim()||e.closest(hu)?.querySelector(".title-text")?.textContent?.trim()||t).replace(/\s+/g," ").trim()||t}extractGeminiCanvasCodeLanguage(e){const t=e.querySelector(".code-block-decoration span")?.textContent||e.closest("[data-mode-id]")?.getAttribute("data-mode-id")||e.querySelector("[data-mode-id]")?.getAttribute("data-mode-id")||"";return (t.split(/\r?\n/)[0]?.trim().toLowerCase()||"").replace(/[^a-z0-9_#+.-]/g,"")}formatGeminiCanvasCodeArtifacts(e){const t=[],n=new Set;for(const r of e){const e=`${r.title}\n${r.language}\n${r.code}`;n.has(e)||(n.add(e),t.push(r));}return t.map(e=>`${e.title?`### Gemini Canvas: ${e.title}`:"### Gemini Canvas"}\n\n${this.formatGeminiCanvasCodeFence(e.code,e.language)}`).join("\n\n")}formatGeminiCanvasFallbackTitles(e){return e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t).map(e=>`### Gemini Canvas: ${e}`).join("\n\n")}formatGeminiCanvasCodeFence(e,t){let n="```";for(;e.includes(n);)n+="`";return `${n}${t||""}\n${e}\n${n}`}normalizeGeminiCanvasCode(e){return e.replace(/\r\n?/g,"\n").replace(/\u00a0/g," ").replace(/^\n+/g,"").replace(/\n+$/g,"")}normalizeGeminiCanvasCodeLine(e){return e.replace(/\u00a0/g," ").replace(/\s+$/g,"")}joinExportSections(...e){return e.map(e=>e.trim()).filter(Boolean).join("\n\n")}isDeepResearchAppPage(){return !this.isSharePage()&&(null!==this.getDeepResearchAppDocumentElement()||null!==this.getDeepResearchAppDocumentTrigger()||null!==document.querySelector(`model-response ${su}`))}getDeepResearchAppDocumentElement(){return document.querySelector(cu)}hasDeepResearchAppDocumentTrigger(){return null!==this.getDeepResearchAppDocumentTrigger()}getDeepResearchAppDocumentTrigger(){return Array.from(document.querySelectorAll('model-response [data-test-id="gem-processing-card"], model-response immersive-entry-chip')).filter(e=>e instanceof HTMLElement).find(e=>{const t=e.matches('[data-test-id="gem-processing-card"]')?e:e.querySelector('[data-test-id="gem-processing-card"]');return !!t?.querySelector(du)&&null!==e.closest("model-response")})||null}async openDeepResearchAppDocumentPanel(){const e=this.getDeepResearchAppDocumentTrigger();if(!e)return false;if(e.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),e.click(),await this.waitForDeepResearchAppDocumentElement())return true;const t=e.matches('[data-test-id="gem-processing-card"]')?e:e.querySelector('[data-test-id="gem-processing-card"]');return t instanceof HTMLElement&&t!==e&&(t.click(),this.waitForDeepResearchAppDocumentElement())}async closeDeepResearchAppDocumentPanel(){const e=document.querySelector(`${lu} [data-test-id="close-button"], immersive-panel [data-test-id="close-button"]`);e instanceof HTMLElement&&(e.click(),await new Promise(e=>setTimeout(e,150)));}async waitForDeepResearchAppDocumentElement(e=3e3){const t=Date.now();for(;Date.now()-tsetTimeout(e,100));}return null!==this.getDeepResearchAppDocumentElement()}isGeminiExportLifecycleState(e){return "object"==typeof e&&null!==e&&"openedDeepResearchPanel"in e&&"boolean"==typeof e.openedDeepResearchPanel}isDeepResearchDocumentSharePage(){return this.isSharePage()&&null!==document.querySelector(ou)}isDeepResearchConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(iu)}isGeminiConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(nu)}extractDeepResearchDocumentShareMessages(e){const t=document.querySelector(`${ou} ${au}`),n=t?this.extractAssistantResponseTextWithAssets(t,e):"",r=n&&e?this.appendDeepResearchReportAssetLink(e,n,this.getDeepResearchDocumentShareTitle()):n;return r?[{role:"assistant",content:r}]:[]}async extractDeepResearchAppMessages(e){const t=this.getDeepResearchAppDocumentElement();if(this.hasDeepResearchAppDocumentTrigger()&&!t)return console.warn("[GeminiAdapter] Deep Research report panel is not available for export"),[];const n=[],r=new Set,o=this.getScrollContainer()||document,i=Array.from(o.querySelectorAll("user-query, model-response")).sort((e,t)=>this.compareDomOrder(e,t));for(const a of i){if(a.closest("immersive-panel"))continue;const t="user-query"===a.tagName.toLowerCase()?"user":"assistant",o="user"===t?(e?await this.extractUserQueryExportContentWithResolvedAssets(a,e):this.extractUserQueryExportContentWithAssets(a)).trim():this.extractDeepResearchAppAssistantResponseContent(a,e).trim();o&&(r.add(a),n.push({role:t,content:o}));}if(t&&!r.has(t)){const r=this.extractAssistantResponseTextWithAssets(t,e).trim();r&&n.push({role:"assistant",content:e?this.appendDeepResearchReportAssetLink(e,r):r});}return this.dedupeAdjacentExportMessages(n)}extractDeepResearchAppAssistantResponseContent(e,t){const n=e.querySelector(au);return this.extractAssistantResponseTextWithAssets(n||e,t)}async extractDeepResearchConversationShareMessages(e){const{messages:t,collectedElements:n}=await this.collectGeminiShareTurnMessages(e);return this.collectDetachedDeepResearchArtifactMessages(n,e).forEach(e=>{t.push(e);}),this.dedupeAdjacentExportMessages(t)}async extractGeminiConversationShareMessages(e){return (await this.collectGeminiShareTurnMessages(e)).messages}async collectGeminiShareTurnMessages(e){const t=[],n=new Set,r=Array.from(document.querySelectorAll(nu));for(const o of r){let r=false;const i=[...Array.from(o.querySelectorAll("user-query")).map(e=>({role:"user",element:e})),...Array.from(o.querySelectorAll(ru)).map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element));for(const{role:a,element:s}of i){const i="user"===a?(e?await this.extractUserQueryExportContentWithResolvedAssets(s,e):this.extractUserQueryExportContentWithAssets(s)).trim():this.joinExportSections(this.extractAssistantResponseTextWithAssets(s,e),r?"":await this.extractGeminiCanvasShareArtifactsFromTurn(o));i&&("assistant"===a&&(r=true),n.add(s),t.push({role:a,content:i}));}if(!r){const e=await this.extractGeminiCanvasShareArtifactsFromTurn(o);e&&t.push({role:"assistant",content:e});}}return {messages:this.dedupeAdjacentExportMessages(t),collectedElements:n}}collectDetachedDeepResearchArtifactMessages(e,t){return Array.from(document.querySelectorAll(`${iu} ${au}`)).flatMap(n=>{if(e.has(n))return [];const r=this.extractAssistantResponseTextWithAssets(n,t).trim(),o=r&&t?this.appendDeepResearchReportAssetLink(t,r,this.getDeepResearchArtifactShareTitle()):r;return o?[{role:"assistant",content:o}]:[]})}appendDeepResearchReportAssetLink(e,t,n){return Pa(e,t,{title:n,fallbackTitle:"deep-research-report",directory:"assets/documents",idPrefix:"gemini-deep-research-report"})}createUniqueGeminiExportPath(e,t){return ta(e,t.usedPaths)}extractMarkdownExportContent(e){return (Hi(e)||this.extractTextWithLineBreaks(e)).trim()}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}dedupeAdjacentExportMessages(e){const t=[];return e.forEach(e=>{const n=t[t.length-1];n?.role===e.role&&n.content===e.content||t.push(e);}),t}getDeepResearchDocumentShareTitle(){const e=document.querySelector(`${ou} h1`);return e?.textContent?.trim()||null}getDeepResearchArtifactShareTitle(){const e=document.querySelector(`${iu} h1`);return e?.textContent?.trim()||null}replaceUserQueryContent(e,t){const n=e.querySelector(".query-text");if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const r=document.createElement("div");return r.className="gh-user-query-markdown gh-user-query-markdown-gemini gh-markdown-preview",!!Md(r,t)&&(r.querySelectorAll("pre").forEach(e=>{const t=e;t.style.setProperty("background","var(--gh-user-query-code-bg)","important"),t.style.setProperty("background-color","var(--gh-user-query-code-bg)","important"),t.style.setProperty("color","var(--gh-user-query-code-fg)","important"),t.querySelectorAll("code").forEach(e=>{const t=e;t.style.setProperty("background","transparent","important"),t.style.setProperty("background-color","transparent","important"),t.style.setProperty("color","var(--gh-user-query-code-fg)","important");});}),n.style.display="none",n.after(r),true)}getExportConfig(){return {userQuerySelector:"user-query",assistantResponseSelector:"model-response, .model-response-container .markdown",turnSelector:".conversation-turn",useShadowDOM:false}}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest("message-content");if(t&&t.id){const e=t.id.match(/(r_[a-f0-9]+)/);if(e)return e[1]}return null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector(),c=(e,t,n)=>{if(!e)return 0;try{if(n){let t=e.nextElementSibling,n=0;for(;t;){const e=t.tagName.toLowerCase();if("user-query"===e)break;if("model-response"===e){const e=t.querySelector(".model-response-text, message-content");if(e){const r=t.querySelector("model-thoughts"),o=r?.textContent?.trim().length||0,i=e.textContent?.trim().length||0;n+=Math.max(0,i-o);}}t=t.nextElementSibling;}return n}const r=e.closest("message-content");return this.calculateRangeWordCount(e,t,r||o)}catch{return 0}};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,o)=>{if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(t.tagName.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=o+1;e{const a=t.tagName.toLowerCase();if("user-query"===a){let e=this.extractUserQueryText(t),o=false;e.length>200&&(e=e.substring(0,200),o=true);const i={level:0,text:e,element:t,isUserQuery:true,isTruncated:o},a=(e=>{const t=e.querySelector('button[jslog*="BardVeMetadataKey"]');if(t){const e=(t.getAttribute("jslog")||"").match(/BardVeMetadataKey.*?["'](r_[a-f0-9]+)["']/);if(e)return e[1]}return null})(t);a&&(i.id=a),n&&(i.wordCount=c(t,null,true)),r.push(i);}else if(/^h[1-6]$/.test(a)){if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(a.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},a=i(t);if(a){const n=t.tagName.toLowerCase();e.id=s(a,n,e.text);}if(n){let n=null;for(let t=o+1;t0&&e.length<=20)return e}}return null}getNetworkMonitorConfig(){return {urlPatterns:["BardFrontendService","StreamGenerate"],silenceThreshold:3e3}}afterPropertiesSet(e={}){super.afterPropertiesSet(e),this.myStuffEnhancer||(this.myStuffEnhancer=new Iu({getUserPathPrefix:()=>this.getUserPathPrefix()}),this.myStuffEnhancer.start()),this.startDeepResearchPanelActions();}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".input-area-switch-label",".model-selector",'[data-test-id="model-selector"]','[aria-label*="model"]','button[aria-haspopup="menu"]'],menuItemSelector:'.mode-title, [role="menuitem"], [role="option"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:300}}async toggleTheme(e){try{const t="dark"===e?"Bard-Dark-Theme":"Bard-Light-Theme";return localStorage.setItem("Bard-Color-Theme",t),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:t,storageArea:localStorage})),!0}catch(RS){return console.error("[GeminiAdapter] toggleTheme error:",RS),false}}},new class extends vs{sessionAccessToken=null;sessionAccessTokenExpiresAt=0;lastModelLockAttemptAt=0;lastModelLockAttemptKeyword="";cachedModelDisplayNamesBySlug=new Map;lastKnownModelSlug=null;lastKnownModelSlugContextKey="";lastKnownModelSlugObservedAt=0;outlineCacheSessionKey="";outlineItemCache=new Map;outlineTurnFirstSeenIndex=new Map;outlineTurnFirstSeenCounter=0;outlineCacheTransitionEndAt=0;nativeTocTextCache=[];nativeTocButtonElementSignatureCache="";nativeTocRevealAttemptedSignature="";nativeTocRefreshScheduled=false;nativeTocButtonElementIds=new WeakMap;nativeTocButtonElementIdCounter=0;exportSnapshotRoot=null;exportSnapshotActive=false;exportIncludeThoughtsOverride=null;exportBundle=null;match(){return window.location.hostname.includes("chatgpt.com")}getSiteId(){return go}getName(){return "ChatGPT"}getThemeColors(){return {primary:"#10a37f",secondary:"#1a7f64"}}getNativeThemeCss(){return "\n/* =============================================\n * ChatGPT 站点原生主题适配器 (ChatGPT Theme Adapter)\n * ============================================= */\n:root, .dark, .light {\n /* 1. 侧边栏容器 */\n --sidebar-surface-primary: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n\n /* 悬浮层、气泡和弹窗 */\n --bg-elevated-primary: var(--gh-bg-secondary) !important;\n --bg-elevated-secondary: var(--gh-bg-tertiary) !important;\n\n /* 底层遮罩 */\n --bg-scrim: var(--gh-overlay-bg) !important;\n\n /* 2. 文本与图标层级 */\n --icon-primary: var(--gh-text) !important;\n --icon-secondary: var(--gh-text-secondary) !important;\n --icon-tertiary: var(--gh-text-tertiary) !important;\n\n /* 3. 边框 (使用极其微弱的透明度保持原生通透感) */\n --border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n --border-heavy: color-mix(in srgb, var(--gh-primary) 25%, transparent) !important;\n --border-light: color-mix(in srgb, var(--gh-primary) 8%, transparent) !important;\n\n /* 4. 品牌高亮/突出显示(绑定 Ophel 主题色) */\n --bg-accent-static: var(--gh-primary) !important;\n --text-accent: var(--gh-primary) !important;\n --icon-accent: var(--gh-primary) !important;\n --interactive-label-accent-default: var(--gh-primary) !important;\n --interactive-label-accent-hover: var(--gh-primary) !important;\n --interactive-label-accent-press: var(--gh-primary) !important;\n --interactive-label-accent-inactive: var(--gh-primary) !important;\n --interactive-label-accent-selected: var(--gh-primary) !important;\n --interactive-icon-accent-default: var(--gh-primary) !important;\n\n /* 5. 交互状态 (按钮 Hover 等) */\n /* - 次级交互(普通按钮/Icon Hover) */\n --interactive-bg-secondary-hover: var(--gh-hover) !important;\n --interactive-bg-secondary-press: var(--gh-active-bg) !important;\n --interactive-bg-secondary-selected: var(--gh-active-bg) !important;\n\n /* - 第三级交互(如模型选择器等) */\n --interactive-bg-tertiary-default: var(--gh-bg-secondary) !important;\n --interactive-bg-tertiary-hover: var(--gh-hover) !important;\n --interactive-bg-tertiary-press: var(--gh-active-bg) !important;\n\n /* 6. 其他小细节 */\n --utility-scrollbar: var(--gh-border) !important;\n /* 行内代码块背景 */\n --gray-100: var(--gh-bg-tertiary) !important;\n}\n\n/* 按钮颜色 */\n.composer-btn {\n color: var(--gh-primary) !important;\n}\n\n/* 链接颜色 */\na.decorated-link:where(:not(.not-markdown *)) {\n color: var(--gh-primary) !important;\n}\n"}getNewTabUrl(){return "https://chatgpt.com"}getSessionId(){const e=window.location.pathname.match(/\/c\/([a-z0-9-]+)(?:\/|$)/i);return e?.[1]?e[1]:super.getSessionId()}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/c\/[a-z0-9-]+(?:\/|$)/i.test(window.location.pathname)}getCurrentCid(){try{const e=localStorage.getItem("_account");if(e)return JSON.parse(e)}catch{}return null}getConversationList(){const e=document.querySelectorAll('#history a[data-sidebar-item="true"]')||[],t=this.getCurrentCid()||void 0;return Array.from(e).map(e=>{const n=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span"),i=o?.textContent?.trim()||"",a=e.hasAttribute("data-active"),s=e.querySelector(".trailing-pair"),l=(s?.querySelectorAll(".trailing svg")||[]).length>1;return {id:r,cid:t,title:i,url:r?`https://chatgpt.com/c/${r}`:"",isActive:a,isPinned:l}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("#history");if(e){const t=e.closest("nav");if(t)return t}return null}getConversationObserverConfig(){return {selector:'#history a[data-sidebar-item="true"]',shadow:false,extractInfo:e=>{const t=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),n=t?t[1]:"";if(!n)return null;const r=e.querySelector("span"),o=r?.textContent?.trim()||"",i=e.hasAttribute("data-active"),a=this.getCurrentCid()||void 0,s=e.querySelector(".trailing-pair");return {id:n,cid:a,title:o,url:`https://chatgpt.com/c/${n}`,isActive:i,isPinned:(s?.querySelectorAll(".trailing svg")||[]).length>1}},getTitleElement:e=>e.querySelector("span")||e}}navigateToConversation(e,t){const n=document.querySelector(`#history a[href="/c/${e}"], a[data-sidebar-item][href="/c/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t)}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.sessionAccessToken;try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include"});if(!e.ok)return this.clearSessionAccessToken(),null;const n=await e.json(),r=[n?.accessToken,n?.access_token,n?.token,n?.user?.accessToken].find(e=>"string"==typeof e&&e.length>0)||null;return "string"==typeof r&&r.length>0?(this.sessionAccessToken=r,this.sessionAccessTokenExpiresAt=t+3e5,r):(this.clearSessionAccessToken(),null)}catch{return this.clearSessionAccessToken(),null}}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}getChatgptAccountId(){try{const e=localStorage.getItem("_account");if(!e)return null;const t=JSON.parse(e);return "string"==typeof t&&t&&"personal"!==t?t:null}catch{return null}}buildNativeDeleteHeaders(e,t){const n={accept:"*/*",authorization:`Bearer ${e}`};"PATCH"===t&&(n["content-type"]="application/json");const r=this.getChatgptAccountId();r&&(n["chatgpt-account-id"]=r);const o=this.getCookieValue("oai-did");o&&(n["oai-device-id"]=o);const i=document.documentElement.lang||navigator.language;return i&&(n["oai-language"]=i),n}async performNativeDeleteRequest(e,t,n="PATCH"){const r=this.buildNativeDeleteHeaders(t,n);return fetch(e,{method:n,headers:r,body:"PATCH"===n?JSON.stringify({is_visible:false}):void 0,credentials:"include"})}async isConversationAlreadyGone(e){return !(await this.findConversationRowWithRetry(e))}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}async tryDeleteViaNativeApi(e){let t=await this.getSessionAccessToken();if(!t)return {id:e,success:false,method:"none",reason:ul};const n=async(e,n="PATCH")=>{let r=await this.performNativeDeleteRequest(e,t,n);if(401===r.status||403===r.status){if(t=await this.getSessionAccessToken(true),!t)return this.clearSessionAccessToken(),r;r=await this.performNativeDeleteRequest(e,t,n);}return r},r=encodeURIComponent(e),o=[`/backend-api/conversation/${r}`,`/backend-api/conversations/${r}`];try{let t=null;for(const r of o){let o=await n(r,"PATCH");if(t=o.status,o.ok)return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(405===o.status&&(o=await n(r,"DELETE"),t=o.status,o.ok))return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status)return 401!==o.status&&403!==o.status||this.clearSessionAccessToken(),{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}return 404===t&&await this.isConversationAlreadyGone(e)?(this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:404===t?gl:this.toDeleteApiHttpReason(t??0)}}catch(RS){return RS instanceof Error&&"AbortError"===RS.name?{id:e,success:false,method:"api",reason:"delete_api_timeout"}:{id:e,success:false,method:"api",reason:hl}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;const n=await this.findConversationMenuButton(t,e);if(!n)return false;document.body.click(),await this.sleep(50),this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,4e3)}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#history a[data-sidebar-item="true"][href="/c/${e}"]`)}async findConversationMenuButton(e,t){const n=['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[data-testid*="menu"]',".trailing button"].join(", "),r=this.findConversationItemContainer(e,t),o=[r,e.closest("li"),e.parentElement,e].filter((e,t,n)=>!!e&&n.indexOf(e)===t);for(let i=0;i<8;i++){o.forEach(e=>{e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));});for(const e of o){const o=this.findFirstInScope(e,n,n=>this.isMenuButtonForConversation(n,t,r||e));if(o)return o}await this.sleep(100);}return null}findConversationItemContainer(e,t){const n=`/c/${t}`;let r=e,o=null;for(let i=0;i<8&&r;i++){const e=Array.from(r.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(e.some(e=>e.getAttribute("href")===n)){o||1!==e.length||(o=r);const t=!!r.querySelector('button[aria-haspopup="menu"], .trailing button');if(1===e.length&&t)return r}if("history"===r.id)break;r=r.parentElement;}return o||e.closest("li")||e.parentElement||e}findFirstInScope(e,t,n){const r=Array.from(e.querySelectorAll(t));for(const o of r)if(this.isVisible(o)&&(!n||n(o)))return o;return null}isMenuButtonForConversation(e,t,n){if(!n.contains(e))return false;const r=`/c/${t}`,o=e.closest("li");if(o){const e=Array.from(o.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(1===e.length&&e[0].getAttribute("href")===r&&o.contains(n.querySelector(`a[data-sidebar-item="true"][href="${r}"]`)))return true}const i=Array.from(n.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));return 1===i.length&&i[0].getAttribute("href")===r}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"]'));let r=null,o=Number.POSITIVE_INFINITY;const i=e.getBoundingClientRect(),a=i.left+i.width/2,s=i.top+i.height/2;for(const l of n){if(!this.isVisible(l))continue;const e=l.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,i=Math.hypot(t-a,n-s);i0?n:r;for(const e of o){if(!this.isVisible(e))continue;const t=(e.textContent||"").trim().toLowerCase();if(ll.some(e=>t.includes(e.toLowerCase())))return e}await this.sleep(80);}return null}async waitForDeleteConfirmButton(e=2500){const t=Date.now();for(;Date.now()-te.includes(t.toLowerCase())))return t}await this.sleep(80);}return null}async waitForConversationRemoved(e,t=3e3){const n=Date.now();for(;Date.now()-n0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getSessionName(){const e=this.getDocumentConversationTitle(sl);return e&&e!==sl?e.replace(` | ${sl}`,"").replace(` - ${sl}`,"").trim():super.getSessionName()}getConversationTitle(){const e=document.querySelector("#history a[data-active] span"),t=e?.textContent?.trim();return t||this.getSessionName()}getNewChatButtonSelectors(){return ['[data-testid="create-new-chat-button"]','a[href="/"]','button[aria-label="New chat"]','button[aria-label="新对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll('[data-message-author-role="assistant"]');if(0===t.length)return null;const n=t[t.length-1],r=(n.querySelector(".markdown, .prose, [class*='prose']")||n).cloneNode(true);r.querySelectorAll('.sr-only, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=Hi(r).trim();return o||this.extractTextWithLineBreaks(r)}getWidthSelectors(){return [{selector:'[class*="thread-content-max-width"]',property:"max-width"},{selector:'[style*="--thread-content-max-width"]',property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:":root",property:"--user-chat-width",noCenter:true}]}getZenModeConfig(){return {hide:["#stage-slideover-sidebar","div.select-none:has(> .pointer-events-auto)"]}}getCleanModeConfig(){return {hide:["div.select-none:has(> .pointer-events-auto)",'div.border-token-border-default.border-t.py-4.text-sm:has(button[aria-label="Ad options"]):has([role="link"][tabindex="0"])']}}getMarkdownFixerConfig(){return {selector:'[data-message-author-role="assistant"] p',fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest('[data-message-author-role="assistant"]');if(!t)return false;const n=document.querySelectorAll(this.getChatContentSelectors().find(e=>e.includes("assistant"))||'[data-message-author-role="assistant"]');return t===n[n.length-1]}}}getTextareaSelectors(){return ["#prompt-textarea",'textarea[data-id="root"]','[contenteditable="true"]']}getSubmitButtonSelectors(){return ['[data-testid="send-button"]','button[aria-label="Send prompt"]','button[aria-label="发送"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&("prompt-textarea"===e.id||"true"===e.getAttribute("contenteditable")))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{"TEXTAREA"===t.tagName?t.value=e:t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"TEXTAREA"===this.textarea.tagName?this.textarea.value="":(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)),this.textarea.dispatchEvent(new Event("input",{bubbles:true}))):this.textarea=null);}getScrollContainer(){const e=document.querySelector('[class*="scrollbar-gutter"], [class*="@container/main"] > div');if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelectorAll("div");let n=null,r=0;for(const o of Array.from(t)){const e=getComputedStyle(o);("auto"===e.overflowY||"scroll"===e.overflowY)&&o.scrollHeight>o.clientHeight&&o.scrollHeight>r&&(o.closest("nav")||(r=o.scrollHeight,n=o));}return n}getResponseContainerSelector(){return "#thread, main#main"}getChatContentSelectors(){return ['[data-message-author-role="assistant"]','[data-message-author-role="user"]',".markdown"]}getUserQuerySelector(){return '[data-message-author-role="user"]'}extractUserQueryText(e){const t=e.matches(".whitespace-pre-wrap")?e:e.querySelector(".whitespace-pre-wrap");return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=e.querySelector(".whitespace-pre-wrap");if(!t)return this.extractUserQueryText(e).trim();const n=t.cloneNode(true);n.querySelectorAll(".sr-only").forEach(e=>e.remove()),n.querySelectorAll("pre code").forEach(e=>{if(e.className.includes("language-"))return;const t=(e.textContent||"").split("\n");if(t.length>1){const n=t[0].trim().toLowerCase(),r=t[1].trim().toLowerCase();pl.has(n)&&!pl.has(r)&&(e.className=`language-${n}`,e.textContent=t.slice(1).join("\n"));}});const r=Hi(n).trim();return r||this.extractUserQueryText(t).trim()}extractUserQueryExportContent(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";return this.extractUserQueryMarkdown(e).trim()||this.extractUserQueryText(e)}extractAssistantResponseText(e){return this.isExportSnapshotElement(e)?e.textContent?.trim()||"":super.extractAssistantResponseText(e)}isExportSnapshotElement(e){return e.hasAttribute(xl)}shouldSkipElement(e){return e.classList.contains("sr-only")}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if(this.shouldSkipElement(o))return;if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()}replaceUserQueryContent(e,t){const n=e.querySelector(".whitespace-pre-wrap");if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;n.style.display="none";const r=document.createElement("div");return r.className="gh-user-query-markdown gh-markdown-preview",r.innerHTML=t,n.after(r),true}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:kl,assistantResponseSelector:Tl,turnSelector:Cl,useShadowDOM:false}:{userQuerySelector:'[data-message-author-role="user"]',assistantResponseSelector:'[data-message-author-role="assistant"]',turnSelector:'[data-testid^="conversation-turn"]',useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportSnapshot(),this.exportBundle=null;const t="markdown"===e.format&&"zip"===e.packaging?la():null,n=document.querySelector(this.getResponseContainerSelector())||document.body,r=this.getScrollContainer()||n;let o=r instanceof HTMLElement?await this.collectExportMessageSnapshots(r,t):this.readVisibleExportMessageSnapshots(n,t);return 0===o.length&&r!==n&&(o=this.readVisibleExportMessageSnapshots(n,t)),0===o.length&&n!==document.body&&(o=this.readVisibleExportMessageSnapshots(document,t)),0===o.length?null:(this.mountExportSnapshot(o),this.exportBundle={messages:o.map(({role:e,content:t})=>({role:e,content:t})),assets:t?.assets},{count:o.length})}async extractExportBundle(e){return this.exportBundle}async extractExportMessages(e){return this.exportBundle?.messages??null}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundle=null;}async collectExportMessageSnapshots(e,t){const n=e.scrollTop,r=new Map,o=new Map;let i=0;const a=e=>{for(const t of e){o.has(t.turnKey)||o.set(t.turnKey,i++);const e=r.get(t.turnKey);if(!e){r.set(t.turnKey,t);continue}const n=Math.min(e.order,t.order);t.content.length>e.content.length?r.set(t.turnKey,{...t,order:n}):n!==e.order&&r.set(t.turnKey,{...e,order:n});}};try{const n=this.getAllTurnShellsSorted();if(0===n.length)a(this.readVisibleExportMessageSnapshots(e,t));else {for(const r of n)this.turnHasMountedMessage(r)||(this.scrollTurnIntoView(r),e.dispatchEvent(new Event("scroll",{bubbles:!0})),await this.waitForTurnMessageMounted(r,900)),this.turnHasMountedMessage(r)&&(a(this.extractTurnExportSnapshots(r,null,t)),this.absorbTurnIntoOutlineCache(r));const o=this.extractCollectedTurnIds(r),i=n.filter(e=>{const t=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return t.length>0&&!o.has(t)});if(i.length>0){await this.sleep(200);for(const n of i)this.scrollTurnIntoView(n),e.dispatchEvent(new Event("scroll",{bubbles:!0})),await this.waitForTurnMessageMounted(n,1800),this.turnHasMountedMessage(n)&&(a(this.extractTurnExportSnapshots(n,null,t)),this.absorbTurnIntoOutlineCache(n));}}}finally{try{this.extractOutline(6,!0,!1);}catch{}e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return Array.from(r.values()).sort((e,t)=>{if(e.order!==t.order)return e.order-t.order;return (o.get(e.turnKey)??Number.MAX_SAFE_INTEGER)-(o.get(t.turnKey)??Number.MAX_SAFE_INTEGER)})}getAllTurnShellsSorted(){const e=document.querySelector(this.getResponseContainerSelector())||document,t=Array.from(e.querySelectorAll('section[data-turn], [data-testid^="conversation-turn"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${yl}]`)&&!e.closest(".gh-root, .gh-main-panel")));return t.filter(e=>!t.some(t=>t!==e&&e.contains(t))).sort((e,t)=>this.getExportTurnSortIndex(e)-this.getExportTurnSortIndex(t))}turnHasMountedMessage(e){const t=e.querySelector("[data-message-author-role]");if(t instanceof HTMLElement){if(t.textContent&&t.textContent.trim())return true;if(this.hasExportableChatGPTImage(t))return true}return !!this.hasExportableChatGPTImage(e)||null!==this.getDeepResearchIframe(e)}async waitForTurnMessageMounted(e,t){const n=Date.now()+t;for(;Date.now()e instanceof HTMLElement);for(const i of r){const e=i.getAttribute("data-message-id")||i.closest("[data-message-id]")?.getAttribute("data-message-id")||"";if(!e)continue;const r=this.extractUserQueryText(i).trim();if(!r)continue;let o=r,a=false;o.length>200&&(o=o.substring(0,200),a=true),this.outlineItemCache.set(e,{id:e,level:0,text:o,turnId:t,firstSeenTurnIndex:n,orderInTurn:0,isUserQuery:true,isTruncated:a});}const o=Array.from(e.querySelectorAll('[data-message-author-role="assistant"]')).filter(e=>e instanceof HTMLElement);for(const i of o){const e=i.getAttribute("data-message-id")||i.closest("[data-message-id]")?.getAttribute("data-message-id")||"";if(!e)continue;const r=Array.from(i.querySelectorAll("h1,h2,h3,h4,h5,h6")),o={};let a=0;for(const i of r){if(this.shouldSkipElement(i))continue;if(this.isInRenderedMarkdownContainer(i))continue;const r=i.tagName.toLowerCase(),s=(i.textContent||"").trim();if(!s)continue;const l=`${r}-${s}`,c=o[l]||0;o[l]=c+1;const d=`${e}::${l}::${c}`;this.outlineItemCache.set(d,{id:d,level:parseInt(r.charAt(1),10),text:s,turnId:t,firstSeenTurnIndex:n,orderInTurn:a++,isUserQuery:false});}}}readVisibleExportMessageSnapshots(e,t){const n=e instanceof HTMLElement?e:document.querySelector(this.getResponseContainerSelector()),r=this.findExportTurnContainers(e);if(0===r.length)return Array.from(e.querySelectorAll('[data-message-author-role="user"], [data-message-author-role="assistant"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${yl}]`)&&!e.closest(".gh-root, .gh-main-panel"))).map(e=>this.extractExportMessageSnapshot(e,n,t)).filter(e=>null!==e);const o=[];for(const i of r){const e=this.extractTurnExportSnapshots(i,n,t);o.push(...e);}return o}findExportTurnContainers(e){const t=Array.from(e.querySelectorAll('section[data-turn], [data-testid^="conversation-turn"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${yl}]`)&&!e.closest(".gh-root, .gh-main-panel")));return t.filter(e=>!t.some(t=>t!==e&&e.contains(t)))}extractTurnExportSnapshots(e,t,n){const r=this.collectOwnAuthorMessagesForTurn(e);if(0===r.length){const t=this.extractChatGPTImageMarkdown(e,n,{fallbackAlt:"generated image"}).map(e=>this.normalizeExportMessageContent(e)).filter(e=>e.length>0);if(t.length>0){const n=t.join("\n\n"),r=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return [{role:Sl,turnKey:r?`assistant:turn:${r}`:`assistant:images:${n.replace(/\s+/g," ").slice(0,120)}`,order:this.getExportTurnSortIndex(e),content:n}]}return this.extractDeepResearchTurnExportSnapshot(e)}const o=r[0].getAttribute("data-message-author-role"),i="user"===e.getAttribute("data-turn")||"user"===o?wl:Sl,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"",s=this.getExportTurnSortIndex(e);if(i===wl){const e=r.map(e=>this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAssets(e,n)||this.extractUserQueryText(e))).filter(e=>e.length>0);if(0===e.length)return [];const t=e.join("\n\n");return [{role:wl,turnKey:a?`user:turn:${a}`:`user:content:${t.replace(/\s+/g," ").slice(0,120)}`,order:s,content:t}]}const l=r.map(e=>this.normalizeExportMessageContent(this.extractAssistantResponseTextFromLiveDom(e))).filter(e=>e.length>0);if(l.push(...this.extractChatGPTImageMarkdown(e,n,{fallbackAlt:"generated image",onlyOutsideAuthorMessages:true}).map(e=>this.normalizeExportMessageContent(e)).filter(e=>e.length>0)),0===l.length)return [];const c=l.join("\n\n"),d=a?`assistant:turn:${a}`:`assistant:content:${c.replace(/\s+/g," ").slice(0,120)}`;return [{role:Sl,turnKey:d,order:s,content:c}]}collectOwnAuthorMessagesForTurn(e){return Array.from(e.querySelectorAll('[data-message-author-role="user"], [data-message-author-role="assistant"]')).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(`[${yl}]`))return false;if(t.closest(".gh-root, .gh-main-panel"))return false;return t.closest('section[data-turn], [data-testid^="conversation-turn"]')===e})}extractExportMessageSnapshot(e,t,n){const r="assistant"===e.getAttribute("data-message-author-role")?Sl:wl,o=this.normalizeExportMessageContent(r===Sl?this.extractAssistantResponseTextFromLiveDom(e):this.extractUserQueryExportContentWithAssets(e,n)||this.extractUserQueryText(e));if(!o)return null;const i=e.getAttribute("data-message-id")||e.closest("[data-message-id]")?.getAttribute("data-message-id")||"",a=i?`${r}:${i}`:`${r}:content:${o.replace(/\s+/g," ").slice(0,120)}`,s=e.closest('section[data-turn], [data-testid^="conversation-turn"]');return {role:r,turnKey:a,order:s?this.getExportTurnSortIndex(s):Number.MAX_SAFE_INTEGER,content:o}}extractAssistantResponseTextFromLiveDom(e){const t=(e.querySelector(".markdown, .prose, [class*='prose']")||e).cloneNode(true);t.querySelectorAll('.sr-only, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t)}extractUserQueryExportContentWithAssets(e,t){const n=[...this.extractUserQueryImageMarkdown(e,t),...this.extractUserQueryFileMarkdown(e,t)],r=this.extractUserQueryMarkdown(e).trim();return r&&n.push(r),n.join("\n\n").trim()}extractUserQueryImageMarkdown(e,t){return this.extractChatGPTImageMarkdown(e,t,{fallbackAlt:"uploaded image",role:"user",category:"image"})}extractChatGPTImageMarkdown(e,t,n={fallbackAlt:"image"}){const r=this.getChatGPTExportImages(e).filter(e=>e instanceof HTMLImageElement&&(!!this.isExportableChatGPTImage(e)&&(!n.onlyOutsideAuthorMessages||!e.closest("[data-message-author-role]")))),o=new Set,i=[];for(const a of r){const e=this.getChatGPTImageExportSource(a);if(!e||o.has(e))continue;o.add(e);const r=La({source:e,alt:(a.alt||a.getAttribute("aria-label")||n.fallbackAlt).replace(/\s+/g," ").trim()},t||void 0,{siteId:this.getSiteId(),role:n.role||"assistant",category:n.category||"generated-image",fallbackAlt:n.fallbackAlt});r&&i.push(r);}return i}getChatGPTExportImages(e){const t=Array.from(e.querySelectorAll('[class*="imagegen-image"], [data-testid*="image-gen"]')).map(e=>{const t=Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement);return t.find(e=>{const t=e.className||"";return !t.includes("absolute")&&!t.includes("blur")})||t.find(e=>e.width>0&&e.height>0)||t[0]||null}).filter(e=>e instanceof HTMLImageElement);return t.length>0?t:Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement)}extractUserQueryFileMarkdown(e,t){const n=Array.from(e.querySelectorAll('[role="group"][aria-label], [class*="file-tile"]')).filter(e=>e instanceof HTMLElement),r=new Set,o=[];for(const i of n){const e=this.extractChatGPTFileName(i);if(!e)continue;const n=this.extractChatGPTFileHref(i),a=Da([{kind:"file",name:e,source:n,type:e}],t||void 0,{siteId:this.getSiteId(),getLabel:()=>e,getMimeHint:()=>e})[0];r.has(a)||(r.add(a),o.push(a));}return o.length>0?["**Attachments:**\n\n"+o.join("\n")]:[]}extractDeepResearchTurnExportSnapshot(e){const t=this.getDeepResearchIframe(e);if(!t)return [];const n=t.getAttribute("src")||t.src||"",r=t.getAttribute("title")||"",o=r&&!r.startsWith("internal://")?r:"ChatGPT Deep Research",i=n?`[${da(o)}](${n})`:o,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return [{role:Sl,turnKey:a?`assistant:turn:${a}`:`assistant:deep-research:${n}`,order:this.getExportTurnSortIndex(e),content:i}]}getDeepResearchIframe(e){const t=e.querySelector('iframe[title="internal://deep-research"], iframe[src*="connector_openai_deep_research"]');return t instanceof HTMLIFrameElement?t:null}isExportableChatGPTImage(e){const t=this.getChatGPTImageExportSource(e);return !!t&&(!t.includes("/cdn/assets/")&&(!t.startsWith("data:image/svg+xml")&&(xa(t)||t.startsWith("data:image/"))))}hasExportableChatGPTImage(e){return this.getChatGPTExportImages(e).some(e=>this.isExportableChatGPTImage(e))}getChatGPTImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=va(n);if(e)return e}return ""}extractChatGPTFileName(e){const t=[e.getAttribute("aria-label")||"",e.querySelector("[aria-label]")?.getAttribute("aria-label")||"",e.querySelector(".truncate.font-semibold")?.textContent||"",e.textContent||""].map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).find(e=>/\.[A-Za-z0-9]{1,10}(\s|$)/.test(e));return t?.match(/[^/\\]+?\.[A-Za-z0-9]{1,10}/)?.[0]||""}extractChatGPTFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=va(n.getAttribute("href")||n.href||"");if(xa(e))return e}return ""}getExportTurnSortIndex(e){const t=e.getAttribute("data-testid")||"",n=/^conversation-turn-(\d+)/.exec(t);return n?parseInt(n[1],10):Number.MAX_SAFE_INTEGER}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(yl,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(vl,"1");const r=document.createElement("div");r.setAttribute(xl,e.role),r.textContent=e.content,n.appendChild(r),t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${yl}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}normalizeNativeTocText(e){return e.replace(/\s+/g," ").trim()}isCompatibleNativeTocText(e,t){const n=this.normalizeNativeTocText(e),r=this.normalizeNativeTocText(t);if(!n||!r)return false;if(n===r)return true;return !(Math.min(n.length,r.length)<200)&&(n.startsWith(r)||r.startsWith(n))}isNativeTocOutlineId(e){return Boolean(e?.startsWith("chatgpt-native-user-query::"))}getNativeTocOutlineIndex(e){const t=(e||"").match(El);if(!t?.[1])return null;const n=Number.parseInt(t[1],10);return Number.isNaN(n)?null:n}getNativeTocButtonIndex(e,t){const n=/^Prompt\s+(\d+)$/i.exec((e.getAttribute("aria-label")||"").trim());if(!n?.[1])return t;const r=Number.parseInt(n[1],10);return Number.isNaN(r)?t:Math.max(0,r-1)}isNativeTocButton(e){if(!(e instanceof HTMLElement))return false;if("button"!==e.tagName.toLowerCase())return false;if(!this.normalizeNativeTocText(e.getAttribute("aria-label")||""))return false;const t=String(e.className||"");return t.includes("h-0.5")&&t.includes("w-4.5")}getNativeTocButtons(){return (Array.from(document.querySelectorAll(".no-scrollbar")).map(e=>Array.from(e.querySelectorAll("button[aria-label]")).filter(e=>this.isNativeTocButton(e))).filter(e=>e.length>0).sort((e,t)=>t.length-e.length)[0]||[]).map((e,t)=>({button:e,index:this.getNativeTocButtonIndex(e,t)})).sort((e,t)=>e.index-t.index).map(({button:e})=>e)}getNativeTocHoverTargets(e){const t=e[0];if(!t)return [];const n=t.closest(".no-scrollbar");return [n,n?.parentElement,t.closest(".relative.flex.items-start"),t.closest(".fixed"),t].filter((e,t,n)=>e instanceof HTMLElement&&n.indexOf(e)===t)}getNativeTocButtonElementSignature(e){return e.map(e=>{let t=this.nativeTocButtonElementIds.get(e);return void 0===t&&(t=this.nativeTocButtonElementIdCounter,this.nativeTocButtonElementIdCounter+=1,this.nativeTocButtonElementIds.set(e,t)),t}).join("|")}cacheNativeTocTexts(e,t){this.nativeTocTextCache=t,this.nativeTocButtonElementSignatureCache=this.getNativeTocButtonElementSignature(e);}hasUsableNativeTocTextCache(e){if(this.nativeTocTextCache.length!==e.length)return false;const t=this.getNativeTocButtonElementSignature(e);return t.length>0&&t===this.nativeTocButtonElementSignatureCache}getElementWindow(e){return e.ownerDocument.defaultView||window}revealNativeTocTextLayer(e){this.getNativeTocHoverTargets(e).forEach(e=>{const t=e.getBoundingClientRect(),n=this.getElementWindow(e),r={bubbles:true,cancelable:true,composed:true,view:n,clientX:Math.round(t.left+t.width/2),clientY:Math.round(t.top+t.height/2)},o=n.PointerEvent;o&&(e.dispatchEvent(new o("pointerover",{...r,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new o("pointerenter",{...r,pointerId:1,pointerType:"mouse",isPrimary:true})));const i=n.MouseEvent;e.dispatchEvent(new i("mouseover",r)),e.dispatchEvent(new i("mouseenter",r)),e.dispatchEvent(new i("mousemove",r));});}concealNativeTocTextLayer(e){this.getNativeTocHoverTargets(e).forEach(e=>{const t=e.getBoundingClientRect(),n=this.getElementWindow(e),r={bubbles:true,cancelable:true,composed:true,view:n,clientX:Math.max(0,Math.round(t.left-8)),clientY:Math.max(0,Math.round(t.top-8))},o=n.PointerEvent;o&&(e.dispatchEvent(new o("pointerout",{...r,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new o("pointerleave",{...r,pointerId:1,pointerType:"mouse",isPrimary:true})));const i=n.MouseEvent;e.dispatchEvent(new i("mouseout",r)),e.dispatchEvent(new i("mouseleave",r));});}readNativeTocButtonLabels(e){const t=e.map(e=>this.normalizeNativeTocText(e.getAttribute("aria-label")||"")).filter(e=>e&&!Al.test(e));return t.length===e.length?t:[]}scheduleNativeTocRefresh(e){if(this.nativeTocRefreshScheduled)return;const t=this.outlineCacheSessionKey,n=this.getNativeTocButtonElementSignature(e);this.nativeTocRefreshScheduled=true,window.setTimeout(()=>{try{if(t!==this.outlineCacheSessionKey||t!==this.getOutlineCacheSessionKey())return;const e=this.getNativeTocButtons();if(this.getNativeTocButtonElementSignature(e)!==n)return;const r=this.readNativeTocButtonLabels(e);r.length===e.length&&r.length>0&&(this.cacheNativeTocTexts(e,r),window.dispatchEvent(new CustomEvent("ophel:refreshOutline")));}finally{this.concealNativeTocTextLayer(e.filter(e=>e.isConnected)),this.nativeTocRefreshScheduled=false;}},250);}getNativeTocTexts(e){const t=this.readNativeTocButtonLabels(e);if(t.length===e.length)return this.cacheNativeTocTexts(e,t),t;const n=this.getNativeTocButtonElementSignature(e);if(!this.hasUsableNativeTocTextCache(e)&&this.nativeTocRevealAttemptedSignature!==n){this.nativeTocRevealAttemptedSignature=n,this.revealNativeTocTextLayer(e);const t=this.readNativeTocButtonLabels(e);if(t.length===e.length)return this.cacheNativeTocTexts(e,t),this.concealNativeTocTextLayer(e),t;this.scheduleNativeTocRefresh(e);}const r=e[0],o=r?.closest(".no-scrollbar")?.parentElement||r?.closest(".relative.flex.items-start")||r?.closest(".fixed"),i=o?Array.from(o.querySelectorAll(["button[data-fill] [title]",'button[class*="__menu-item"] [title]',"ul button [title]","[role='menu'] [title]",".absolute [title]"].join(", "))):[],a=new Set,s=i.filter(e=>!a.has(e)&&(a.add(e),e instanceof HTMLElement)).map(e=>this.normalizeNativeTocText(e.getAttribute("title")||e.textContent||"")).filter(e=>e.length>0);return s.length===e.length?(this.cacheNativeTocTexts(e,s),s):this.hasUsableNativeTocTextCache(e)?this.nativeTocTextCache:s}getNativeTocEntries(){const e=this.getNativeTocButtons();if(0===e.length)return [];const t=this.getNativeTocTexts(e);if(t.length!==e.length)return [];const n=new Map;t.forEach(e=>{const t=this.normalizeNativeTocText(e);n.set(t,(n.get(t)||0)+1);});const r=e=>{const n=this.normalizeNativeTocText(e);return !n||t.some(e=>{const t=this.normalizeNativeTocText(e);return !(!t||t===n)&&(n.startsWith(t)||t.startsWith(n))})},o=new Map;Array.from(document.querySelectorAll(this.getUserQuerySelector())).forEach(e=>{const t=this.normalizeNativeTocText(this.extractUserQueryText(e));if(!t)return;const n=o.get(t)||[];n.push(e),o.set(t,n);});const i=[];return e.forEach((e,a)=>{const s=t[a];if(!s)return;const l=this.normalizeNativeTocText(s),c=o.get(l)||[],d=1===n.get(l)&&!r(s)&&1===c.length;i.push({index:this.getNativeTocButtonIndex(e,a),text:s,button:e,element:d?c[0]:null,isActive:e.hasAttribute("data-toc-active")});}),i}getNativeTocButtonEntryForIndex(e){const t=this.getNativeTocButtons().find((t,n)=>this.getNativeTocButtonIndex(t,n)===e);return t?{index:e,text:"",button:t,element:null,isActive:t.hasAttribute("data-toc-active")}:null}getActiveNativeTocIndex(){const e=this.getNativeTocButtons(),t=e.find(e=>e.hasAttribute("data-toc-active"));if(!t)return null;const n=e.indexOf(t);return this.getNativeTocButtonIndex(t,n)}createNativeTocUserQueryOutlineItem(e,t){let n=e.element?this.extractUserQueryText(e.element):e.text,r=false;n.length>200&&(n=n.substring(0,200),r=true);const o=`chatgpt-native-user-query::${e.index}::${this.normalizeNativeTocText(e.text)}`,i=this.getChatGPTMessageId(e.element);return {level:0,text:n,element:e.element,isUserQuery:true,isTruncated:r,id:i||o,navigationId:o,wordCount:t}}resolveNativeTocEntryForOutlineItem(e){const t=this.getNativeTocOutlineIndex(e.navigationId||e.id);return null!==t?this.getNativeTocButtonEntryForIndex(t):null}async waitForNativeTocUserQuery(e,t,n=1600){const r=Date.now()+n;for(;Date.now()this.isVisible(e)&&this.isElementInViewport(e,n));if(0===r.length)return null;const o=r.filter(t=>this.isCompatibleNativeTocText(this.extractUserQueryText(t),e));return 0===o.length?null:t?this.getClosestVisibleElementToViewportCenter(o,n):1===o.length?o[0]:null}isElementInViewport(e,t){const n=e.getBoundingClientRect(),r=t instanceof HTMLElement?t.getBoundingClientRect().top:0,o=t instanceof HTMLElement?t.getBoundingClientRect().bottom:window.innerHeight;return n.bottom>r&&n.top{const t=e.getBoundingClientRect();return {element:e,distance:Math.abs(t.top+t.height/2-r)}}).sort((e,t)=>e.distance-t.distance)[0]?.element||null}getElementRenderOrder(e,t){const n=(this.getChatGPTTurnId(e)&&e.closest("[data-turn-id], [data-turn-id-container]")||e).getBoundingClientRect();if(t instanceof HTMLElement){const e=t.getBoundingClientRect();return t.scrollTop+(n.top-e.top)}return window.scrollY+n.top}getOutlineCacheSessionKey(){return `${this.getCurrentCid()||"default"}:${this.getSessionId()||"default"}:${window.location.pathname}`}ensureOutlineCacheSession(){const e=this.getOutlineCacheSessionKey();if(e===this.outlineCacheSessionKey)return;const t=""===this.outlineCacheSessionKey;this.outlineCacheSessionKey=e,this.outlineItemCache.clear(),this.outlineTurnFirstSeenIndex.clear(),this.outlineTurnFirstSeenCounter=0,this.nativeTocTextCache=[],this.nativeTocButtonElementSignatureCache="",this.nativeTocRevealAttemptedSignature="",this.nativeTocRefreshScheduled=false,this.nativeTocButtonElementIds=new WeakMap,this.nativeTocButtonElementIdCounter=0,this.outlineCacheTransitionEndAt=t?0:Date.now()+2e3;}isInOutlineCacheTransition(){return Date.now(){const r=e.getAttribute("data-turn-id-container")||e.getAttribute("data-turn-id");r&&!t.has(r)&&(t.set(r,{element:e,index:n}),n+=1);}),t}recordTurnDocumentOrders(e){if(0===e.size)return;const t=[];if(e.forEach((e,n)=>{this.outlineTurnFirstSeenIndex.has(n)||t.push(n);}),0!==t.length)for(const n of t)this.outlineTurnFirstSeenIndex.set(n,this.outlineTurnFirstSeenCounter++);}getTurnSortIndex(e,t){if(!e)return Number.MAX_SAFE_INTEGER;const n=t.get(e);if(n)return n.index;const r=this.outlineTurnFirstSeenIndex.get(e);return "number"==typeof r?r+1e6:Number.MAX_SAFE_INTEGER}updateChatGPTOutlineCache(e,t){const n=new Map;for(const r of e){if(!r.id)continue;if(this.isNativeTocOutlineId(r.id))continue;const e=this.getChatGPTTurnId(r.element),o=e||r.id,i=n.get(o)||0;n.set(o,i+1);const a=e&&this.outlineTurnFirstSeenIndex.has(e)?this.outlineTurnFirstSeenIndex.get(e):t.get(e||"")?.index??Number.MAX_SAFE_INTEGER,s=this.outlineItemCache.get(r.id);this.outlineItemCache.set(r.id,{id:r.id,level:r.level,text:r.text,turnId:e,firstSeenTurnIndex:a,orderInTurn:i,isUserQuery:r.isUserQuery,isTruncated:r.isTruncated,wordCount:r.wordCount??s?.wordCount});}}mergeCachedChatGPTOutlineItems(e,t,n,r,o,i=false){if(0===this.outlineItemCache.size)return e;const a=new Set(e.map(e=>e.id).filter(e=>!!e)),s=i||e.some(e=>this.isNativeTocOutlineId(e.id));let l=0;const c=[...e];for(const d of this.outlineItemCache.values())this.isNativeTocOutlineId(d.id)||a.has(d.id)||(!d.isUserQuery||r&&!s)&&(!d.isUserQuery&&d.level>n||d.text&&d.text.trim()&&(c.push({level:d.level,text:d.text,element:null,isUserQuery:d.isUserQuery,isTruncated:d.isTruncated,id:d.id,wordCount:o?d.wordCount:void 0}),l+=1));return 0===l?e:c.map((e,n)=>{const r=e.id?this.outlineItemCache.get(e.id):void 0,o=r?.turnId||this.getChatGPTTurnId(e.element),i=this.getNativeTocOutlineIndex(e.navigationId||e.id),a=null!==i?2*i:this.getTurnSortIndex(o,t);return {item:e,originalIndex:n,orderInTurn:null!==i?0:r?.orderInTurn??n,turnIndex:a}}).sort((e,t)=>e.turnIndex!==t.turnIndex?e.turnIndex-t.turnIndex:e.orderInTurn!==t.orderInTurn?e.orderInTurn-t.orderInTurn:e.originalIndex-t.originalIndex).map(({item:e})=>e)}resolveCachedChatGPTOutlineTarget(e){if(!e)return null;this.ensureOutlineCacheSession();const t=this.outlineItemCache.get(e);if(!t)return null;const n=document.querySelector(this.getResponseContainerSelector());if(!n)return null;const r=this.extractMessageIdFromCachedId(t);if(r){const e=this.escapeAttributeValue(r),o=n.querySelector(`[data-message-id="${e}"]`);if(o){if(t.isUserQuery)return o;const e=this.findHeadingInsideMessage(o,t);return e||o}}if(t.turnId){const e=this.getOrderedChatGPTTurnAnchors(n).get(t.turnId)?.element;if(e)return e}return null}extractMessageIdFromCachedId(e){if(!e.id)return null;if(e.isUserQuery)return e.id;const t=e.id.indexOf("::");return t>0?e.id.slice(0,t):null}escapeAttributeValue(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}findHeadingInsideMessage(e,t){const n=t.id.indexOf("::"),r=t.id.lastIndexOf("::");if(n<=0||r<=n)return null;const o=t.id.slice(n+2,r),i=t.id.slice(r+2),a=o.indexOf("-");if(a<=0)return null;const s=o.slice(0,a).toLowerCase(),l=o.slice(a+1);if(!/^h[1-6]$/.test(s))return null;const c=Number.parseInt(i,10)||0,d=Array.from(e.querySelectorAll(s));let u=0;for(const h of d)if((h.textContent||"").trim()===l){if(u===c)return h;u+=1;}return null}async resolveOutlineTarget(e,t){if(e.isUserQuery&&0===e.level){const t=this.resolveNativeTocEntryForOutlineItem(e);if(t){if(t.element)return t.element;t.button.scrollIntoView({block:"nearest",inline:"nearest"}),t.button.click();const n=await this.waitForNativeTocUserQuery(t,e.text);if(n)return n}}const n=this.resolveCachedChatGPTOutlineTarget(e.id);if(n){if(n instanceof HTMLElement&&n.hasAttribute("data-turn-id-container")){this.scrollIntoViewForRevive(n);const t=await this.waitForCachedChatGPTOutlineTargetRemount(e.id);if(t)return t}return n}return super.resolveOutlineTarget(e,t)}scrollIntoViewForRevive(e){try{e.scrollIntoView({block:"center",behavior:"instant"});}catch{e.scrollIntoView({block:"center"});}}async waitForCachedChatGPTOutlineTargetRemount(e,t=1500){if(!e)return null;const n=Date.now()+t;for(;Date.now(){if(!e)return 0;try{if(n){const n=o.querySelectorAll('[data-message-author-role="assistant"]');let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.querySelector(".markdown, .prose, [class*='prose']");if(i)r+=i.textContent||"";else {const e=o.cloneNode(!0);e.querySelectorAll(".sr-only, [class*='sr-only']").forEach(e=>e.remove()),r+=e.textContent||"";}}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(s);let i=!1,a=null;for(const t of Array.from(r)){if(i){a=t;break}(t===e||t.contains(e)||e.contains(t))&&(i=!0);}if(a)return this.calculateRangeWordCount(e,a,o);const l=o.querySelectorAll('[data-message-author-role="assistant"]');if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}},s=this.getUserQuerySelector(),l=[];for(let g=1;g<=e;g++)l.push(`h${g}`);const c=`${s}, ${l.join(", ")}`,d=Array.from(o.querySelectorAll(c)),u=t?this.getNativeTocEntries():[];if(d.forEach((o,l)=>{const c=o.tagName.toLowerCase(),u=o.matches(s),h=/^h[1-6]$/.test(c);let g=false;if(t&&u&&(g=true),h&&!this.shouldSkipElement(o)&&!this.isInRenderedMarkdownContainer(o)){const t=(o.textContent||"").trim(),n=parseInt(c.charAt(1),10);t&&n<=e&&(g=true);}if(g){let e;if(u){let t=this.extractUserQueryText(o),n=false;t.length>200&&(t=t.substring(0,200),n=true),e={level:0,text:t,element:o,isUserQuery:true,isTruncated:n};}else {e={level:parseInt(c.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}const t=this.getChatGPTMessageId(o);if(t&&(e.id=u?t:((e,t,n)=>{i[e]||(i[e]={});const r=`${t}-${n}`,o=i[e][r]||0;return i[e][r]=o+1,`${e}::${r}::${o}`})(t,c,e.text)),n){let t=null;for(let n=l+1;n0){const e=[],t=u.reduce((e,t)=>Math.max(e,t.index),-1),i=e=>{if(!n||!e.element)return;const r=u.find(t=>t.index>e.index);return r?.element?a(e.element,r.element,true):r||e.index!==t?void 0:a(e.element,null,true)},s=u.filter(e=>Boolean(e.element)).map(e=>({index:e.index,renderOrder:this.getElementRenderOrder(e.element,o)})).sort((e,t)=>e.renderOrder-t.renderOrder),l=u.find(e=>e.isActive),c=e=>{const t=this.getElementRenderOrder(e,o);let n,r;for(const o of s){if(!(o.renderOrder<=t)){r=o;break}n=o;}return n?n.index:r?Math.max(0,r.index-1):l?.index??0};u.forEach(t=>{e.push({item:this.createNativeTocUserQueryOutlineItem(t,i(t)),order:1e5*t.index});}),r.filter(e=>!e.isUserQuery).forEach((t,n)=>{const r=t.element?c(t.element):0;e.push({item:t,order:1e5*r+5e4+n});}),r=e.sort((e,t)=>e.order-t.order).map(({item:e})=>e);}const h=this.getOrderedChatGPTTurnAnchors(o);return this.isInOutlineCacheTransition()?r:(this.recordTurnDocumentOrders(h),this.updateChatGPTOutlineCache(r,h),this.mergeCachedChatGPTOutlineItems(r,h,e,t,n,u.length>0))}isGenerating(){return null!==this.findVisibleElementBySelectors(this.getStopButtonSelectors())}getStopButtonSelectors(){return ['[data-testid="stop-button"]','form[data-type="unified-composer"] #composer-submit-button[aria-label*="Stop"]','form[data-type="unified-composer"] #composer-submit-button[aria-label*="停止"]','form[data-type="unified-composer"] button.composer-submit-btn[aria-label*="Stop"]','form[data-type="unified-composer"] button.composer-submit-btn[aria-label*="停止"]']}findModelSelectorButton(){return this.findElementBySelectors([...ml])}getModelStateContextKey(){return `${this.getCurrentCid()||"default"}::${this.getSessionId()||window.location.pathname||"root"}`}getLatestMessageModelSlug(){const e=document.querySelectorAll("[data-message-model-slug]"),t=e[e.length-1];return t?.getAttribute("data-message-model-slug")?.trim()||null}readModelStateFromOpenMenu(){const e=document.querySelector(fl);if(!this.isVisible(e))return null;const t=Array.from(document.querySelectorAll(bl));if(0===t.length)return null;let n=null,r=null;for(const o of t){const e=o.getAttribute("data-testid")||"",t=e.startsWith("model-switcher-")?e.replace(/^model-switcher-/,"").trim():"",i=o.querySelector(".min-w-0"),a=i?Array.from(i.childNodes).filter(e=>e.nodeType===Node.TEXT_NODE).map(e=>e.textContent?.trim()).find(Boolean)||i.textContent?.replace(/\s+/g," ").trim()||"":o.textContent?.replace(/\s+/g," ").trim()||"";t&&a&&this.cachedModelDisplayNamesBySlug.set(t,a);(Boolean(o.querySelector(".trailing svg, .trailing use"))||"checked"===o.getAttribute("data-state")||"true"===o.getAttribute("aria-checked")||"true"===o.getAttribute("aria-selected"))&&(n=a||null,r=t||null);}return r&&(this.lastKnownModelSlug=r,this.lastKnownModelSlugContextKey=this.getModelStateContextKey(),this.lastKnownModelSlugObservedAt=Date.now()),{name:n,slug:r}}extractModelNameFromSelectorButton(e){return e.querySelector("span.truncate, span[class*='truncate']")?.textContent?.trim()||null}getReliableCurrentModelSignals(){const e=this.readModelStateFromOpenMenu(),t=this.findModelSelectorButton();return [e?.name,e?.slug,t?this.extractModelNameFromSelectorButton(t):null].filter(e=>Boolean(e&&e.trim()))}getCurrentModelSignalsForLockCheck(){const e=this.readModelStateFromOpenMenu(),t=this.findModelSelectorButton();return [e?.name,e?.slug,this.lastKnownModelSlug&&(this.isNewConversation()?Date.now()-this.lastKnownModelSlugObservedAt<6e4:this.lastKnownModelSlugContextKey===this.getModelStateContextKey())?this.lastKnownModelSlug:null,this.getLatestMessageModelSlug(),t?this.extractModelNameFromSelectorButton(t):null].filter(e=>Boolean(e&&e.trim()))}getModelName(){const e=this.readModelStateFromOpenMenu();if(e?.name)return e.name;const t=this.getLatestMessageModelSlug();if(t)return this.cachedModelDisplayNamesBySlug.get(t)||t;const n=this.findModelSelectorButton();if(n){const e=this.extractModelNameFromSelectorButton(n);if(e)return e}return null}getNetworkMonitorConfig(){return {urlPatterns:["backend-api/f/conversation"],urlPathEndsWith:["backend-api/f/conversation"],silenceThreshold:3e3,requestBodyRules:[{type:"json-field-exists",field:"thinking_effort",metadata:{domCompletionRequired:true}}]}}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelLockCheckText(e){return this.getCurrentModelSignalsForLockCheck().join(" ")}findElementBySelectors(e){for(const t of e){const e=Array.from(document.querySelectorAll(t));for(const t of e)if(this.isVisible(t))return t}return super.findElementBySelectors(e)}lockModel(e,t){const n=e.trim();if(!n)return;const r=n.toLowerCase();if(this.getReliableCurrentModelSignals().join(" ").toLowerCase().trim().includes(r))return void t?.();const o=this.findModelSelectorButton(),i="true"===o?.getAttribute("aria-expanded")||Boolean(this.readModelStateFromOpenMenu()),a=this.lastModelLockAttemptKeyword===n&&Date.now()-this.lastModelLockAttemptAt<1200;i||a||(this.lastModelLockAttemptKeyword=n,this.lastModelLockAttemptAt=Date.now(),super.lockModel(n,()=>{this.lastModelLockAttemptAt=0,t?.();}));}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[...ml],menuItemSelector:'[data-radix-collection-item][data-testid^="model-switcher-"], [role="menuitemradio"][data-testid^="model-switcher-"], [role="menuitem"][data-testid^="model-switcher-"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:500}}simulateClick(e){if(e.matches('button[class*="__composer-pill"][aria-haspopup="menu"]')){const t=e.getAttribute("aria-expanded");e.click();const n=e.getAttribute("aria-expanded");if("true"===n||n!==t)return;const r=this.getElementWindow(e),o=r.PointerEvent;return void(o?e.dispatchEvent(new o("pointerdown",{bubbles:true,cancelable:true,view:r,pointerId:1,button:0,buttons:1,pointerType:"mouse",isPrimary:true})):e.dispatchEvent(new r.MouseEvent("mousedown",{bubbles:true,cancelable:true,view:r,button:0,buttons:1})))}e.click();}async toggleTheme(e){try{return localStorage.setItem("theme",e),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:e,storageArea:localStorage})),!0}catch(RS){return console.error("[ChatGPTAdapter] toggleTheme error:",RS),false}}},new class extends vs{match(){const e=window.location.hostname;return "grok.com"===e||e.endsWith(".grok.com")}getSiteId(){return fo}getName(){return "Grok"}getThemeColors(){return {primary:"#f39c12",secondary:"#1e1f22"}}getNativeThemeCss(){return '\n\n/* 全局背景 */\n// .bg-surface, .bg-surface-base {\n// background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important\n// }\n\n/* 链接颜色 */\n.[&_a:not(.not-prose)]:text-current a:not(.not-prose) {\n color: var(--gh-primary) !important;\n}\n\n/* 侧边栏背景 */\n[data-sidebar="sidebar"] {\n background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n}\n\n'}getNewTabUrl(){return "https://grok.com/"}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/c\/[^/?#]+(?:\/|$)/i.test(window.location.pathname)}cachedDialogConversations=null;exportUserAttachmentsByResponseId=null;reloadScheduled=false;async loadAllConversations(){const e=document.querySelector('[data-sidebar="content"]');if(!e)return;const t=e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold");if(t){const{showToast:e}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Bi);return {showToast:e}},void 0),{t:n}=await o(async()=>{const{t:e}=await Promise.resolve().then(()=>ue);return {t:e}},void 0);e(n("grokSyncingConversations")),t.click();let r=null;for(let t=0;t<30&&(await new Promise(e=>setTimeout(e,100)),r=document.querySelector('[cmdk-list-sizer=""], [cmdk-list]'),!r);t++);if(r){let e=0,t=0;const n=15;for(let o=0;osetTimeout(e,400));const n=r.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}return this.cacheDialogConversations(),this.dispatchEscapeKey(),void setTimeout(()=>{this.cachedDialogConversations=null;},5e3)}}cacheDialogConversations(){const e=new Map;document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations=e;}getConversationList(){const e=new Map,t=document.querySelector('[data-sidebar="content"]');if(t){t.querySelectorAll('[data-sidebar="group"]').forEach(t=>{const n=t.querySelectorAll('a[href^="/c/"]');0!==n.length&&n.forEach(t=>{const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;const o=t.querySelector("span.flex-1, span.truncate, span"),i=o?.textContent?.trim()||t.textContent?.trim()||"New Chat",a=t.classList.contains("bg-button-ghost-hover"),s=this.isPinnedSidebarConversation(t);e.set(r,{id:r,title:i,url:n,isPinned:s,isActive:a});});});}return document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations&&this.cachedDialogConversations.forEach((t,n)=>{e.has(n)||e.set(n,t);}),Array.from(e.values())}getSidebarScrollContainer(){return document.querySelector('[data-sidebar="content"]')}getZenModeConfig(){return {hide:[".text-sidebar-foreground",'[data-sidebar="sidebar"]']}}getConversationObserverConfig(){return {selector:'[data-sidebar="content"] a[href^="/c/"], [cmdk-item][data-value^="conversation:"] a[href^="/c/"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href");if(!t)return null;const n=this.extractConversationIdFromHref(t);if(!n)return null;const r=!!e.closest('[data-sidebar="content"]'),o=!!e.closest("[cmdk-item]");let i="",a=false;if(r){const t=e.querySelector("span.flex-1, span.truncate, span");i=t?.textContent?.trim()||e.textContent?.trim()||"",a=this.isPinnedSidebarConversation(e);}else if(o){const t=e.closest("[cmdk-item]"),n=t?.querySelector("span.truncate");i=n?.textContent?.trim()||"",a=false;}return {id:n,title:i,url:t,isPinned:a}},getTitleElement:e=>{const t=e.closest("[cmdk-item]");return t?t.querySelector("span.truncate")||e:e.querySelector("span.flex-1, span.truncate, span")||e}}}navigateToConversation(e,t){return t?(window.location.href=t,true):(window.location.href=`/c/${e}`,true)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.tryDeleteViaNativeApi(e.id);if(t.success)return t;return await this.deleteConversationViaUi(e.id)?{id:e.id,success:true,method:"ui"}:{id:e.id,success:false,method:"none",reason:t.reason||qu}}async tryDeleteViaNativeApi(e){const t=`/rest/app-chat/conversations/soft/${encodeURIComponent(e)}`;try{const n=await fetch(t,{method:"DELETE",headers:this.buildNativeDeleteHeaders(),credentials:"include"});return n.ok?(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):404===n.status?this.isConversationVisible(e)?{id:e,success:!1,method:"api",reason:_u}:(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)}}catch{return {id:e,success:false,method:"api",reason:$u}}}buildNativeDeleteHeaders(){const e={accept:"*/*","x-xai-request-id":this.generateRequestId()},t=this.getStatsigId();return t&&(e["x-statsig-id"]=t),e}getStatsigId(){const e=["x-statsig-id","statsig.stableID","statsig.stable_id","statsigStableId"];for(const t of e){const e=localStorage.getItem(t);if("string"==typeof e&&e.length>0)return e}try{for(let e=0;e0)return t}catch{}if(n.length>0)return n}}}catch{}return null}generateRequestId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}syncConversationListAfterDelete(e){this.cachedDialogConversations?.delete(e);const t=this.findConversationAnchors(e);for(const n of t){this.getConversationItemContainer(n).remove();}}scheduleFullReloadAfterDelete(e){if(this.reloadScheduled||0===e.length)return;const t=this.extractConversationIdFromHref(window.location.pathname);if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/");}catch{}this.reloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120);}async deleteConversationViaUi(e){let t=false;try{let n=await this.findConversationAnchorWithRetry(e,400);if(n||(t=await this.openConversationDialogIfNeeded(),this.getCmdkListElement()&&await this.scrollCmdkListToLoadAll(),n=await this.findConversationAnchorWithRetry(e,1200)),!n)return !1;const r=this.getConversationItemContainer(n);this.revealConversationActions(r,n);const o=await this.waitForDeleteButton(r,2e3);if(!o)return !1;this.simulateClick(o);const i=await this.waitForConfirmButton(r,2200);if(!i)return !1;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4e3);return a&&this.syncConversationListAfterDelete(e),a}finally{t&&this.closeConversationDialog();}}async openConversationDialogIfNeeded(){if(this.getCmdkListElement())return false;const e=this.getViewAllButton();if(!e)return false;this.simulateClick(e);const t=Date.now();for(;Date.now()-t<2500;){if(this.getCmdkListElement())return true;await this.sleep(80);}return false}getViewAllButton(){const e=document.querySelector('[data-sidebar="content"]');return e?e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold"):null}getCmdkListElement(){return document.querySelector('[cmdk-list-sizer=""], [cmdk-list]')}closeConversationDialog(){this.dispatchEscapeKey();}dispatchEscapeKey(){const e=document.activeElement||document.body||document.documentElement;if(e)try{const t=new KeyboardEvent("keydown",{key:"Escape",code:"Escape",keyCode:27,which:27,bubbles:!0,cancelable:!0});e.dispatchEvent(t);}catch{e.dispatchEvent(new Event("keydown",{bubbles:true,cancelable:true}));}}async scrollCmdkListToLoadAll(){const e=this.getCmdkListElement();if(!e)return;let t=-1,n=0;for(let r=0;r<16;r++){e.scrollTop=e.scrollHeight,await this.sleep(300);const r=e.scrollHeight;if(r===t){if(n++,n>=3)break}else t=r,n=0;}}async findConversationAnchorWithRetry(e,t){const n=this.findConversationAnchors(e)[0];if(n)return n;const r=Date.now();for(;Date.now()-rthis.extractConversationIdFromHref(t.getAttribute("href"))===e)}getConversationItemContainer(e){const t=[e.closest("[cmdk-item]"),e.closest('[data-sidebar="menu-button"]'),e.closest('[data-sidebar="menu-item"]'),e.closest("li"),e.parentElement,e];for(const n of t)if(n instanceof HTMLElement)return n;return e}revealConversationActions(e,t){try{e.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});}catch{}e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:true})),t&&(t.focus(),t.dispatchEvent(new FocusEvent("focus",{bubbles:true})));}async waitForDeleteButton(e,t){const n=Date.now();for(;Date.now()-ne.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickConfirmButton(e,t){for(const n of e)if(this.hasKeyword(this.getElementSignal(n),zu))return n;for(const n of e)if(this.hasKeyword(this.getIconSignal(n),zu))return n;for(const n of e)if(this.hasKeyword(this.getElementSignal(n),Ou))return n;if(false!==t?.allowIconOnlyFallback){const t=e.filter(e=>e.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickRightMostButton(e){if(0===e.length)return null;return [...e].sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]||null}findButtonsInScopes(e){const t=new Set,n=[];for(const r of e){const e=Array.from(r.querySelectorAll("button"));for(const r of e)t.has(r)||this.isVisible(r)&&(t.add(r),n.push(r));}return n}getElementSignal(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.getAttribute("data-testid")||"",e.className||""].join(" ").toLowerCase()}getIconSignal(e){return Array.from(e.querySelectorAll("svg, path, use, [data-icon], [class*='icon'], [aria-label]")).map(e=>[e.getAttribute("aria-label")||"",e.getAttribute("data-icon")||"",e.getAttribute("name")||"",e.className||""].join(" ")).join(" ").toLowerCase()}hasKeyword(e,t){const n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}async waitForConversationRemoved(e,t){const n=Date.now();for(;Date.now()-ne.isConnected&&this.isVisible(e))}extractConversationIdFromHref(e){if(!e)return null;const t=e.match(/\/c\/([a-zA-Z0-9-]+)/);return t?t[1]:null}isPinnedSidebarConversation(e){if(!e.closest('[data-sidebar="content"]'))return false;const t=e.closest('a[href^="/c/"]')??e;if(!this.hasPinnedIcon(t))return false;const n=t.closest('[data-sidebar="menu-item"]'),r=t.closest('[data-sidebar="menu"]');return !n||!r||this.isPinnedSectionItem(n)}hasPinnedIcon(e){const t=e.querySelector('[data-sidebar="icon"] svg');if(!t)return false;if(!this.isDomElementVisible(t))return false;const n=Array.from(t.querySelectorAll("path"));return 0!==n.length&&n.some(e=>{const t=(e.getAttribute("d")||"").replace(/\s+/g,"");return !!t&&Pu.some(e=>t===e)})}isPinnedSectionItem(e){let t=e.previousElementSibling;for(;t;){if(!t.matches('[data-sidebar="menu-item"]'))return false;t=t.previousElementSibling;}return true}isCmdkActionItem(e){const t=e.closest("[cmdk-item]");if(!t)return false;if((t.getAttribute("data-value")||"").toLowerCase().startsWith("action:"))return true;const n=t.closest("[cmdk-group]");if(!n)return false;const r=(n.getAttribute("data-value")||"").replace(/\s+/g,"").toLowerCase();return !("actionsshowall"!==r&&!r.startsWith("actions"))}isDomElementVisible(e){if(!e)return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isVisible(e){return e instanceof HTMLElement&&this.isDomElementVisible(e)}async sleep(e){await new Promise(t=>setTimeout(t,e));}getCurrentConversationTitleFromSources(){const e=this.extractConversationIdFromHref(window.location.pathname);if(!e)return null;const t=this.getConversationList().find(t=>t.id===e);if(t?.title?.trim())return t.title.trim();const n=document.querySelector(`[data-sidebar="content"] a[href="/c/${e}"], a[href="/c/${e}"]`);if(!n)return null;const r=n.querySelector("span.flex-1, span.truncate, span")?.textContent?.trim();return r||n.textContent?.trim()||null}getConversationTitleFromPage(){const e=document.querySelector(".conversation-title"),t=e?.textContent?.trim();return t||null}getSessionName(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()||this.getCleanedDocumentTitle()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()||this.getCleanedDocumentTitle()}getCleanedDocumentTitle(){const e=super.getSessionName();if(!e)return null;return e.replace(/\s*[|]\s*Shared Grok Conversation$/i,"").replace(/\s*[|]\s*Grok$/i,"").trim()||null}getNewChatButtonSelectors(){return ['a[href="/"]','[data-sidebar="header"] a','button[aria-label*="新"]','button[aria-label*="New"]']}getLatestReplyText(){const e=document.querySelectorAll(".message-bubble:not(.rounded-br-lg)");if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".response-content-markdown");if(n){const e=n.cloneNode(true);e.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=Hi(e).trim();return t||this.extractTextWithLineBreaks(e)}return this.extractTextWithLineBreaks(t)}normalizeContentMaxWidth(e){const t=e.trim();if(!t.endsWith("%"))return t;const n=Number.parseFloat(t);return Number.isFinite(n)?`min(${n}vw, calc(100vw - 32px))`:t}getWidthSelectors(){return [{selector:'[class*="[--content-max-width:"]',property:"--content-max-width",transformValue:e=>this.normalizeContentMaxWidth(e)},{selector:'[style*="--content-max-width"]',property:"--content-max-width",transformValue:e=>this.normalizeContentMaxWidth(e)}]}getUserQueryWidthSelectors(){return [{selector:".message-bubble.rounded-br-lg",property:"max-width",noCenter:true,extraCss:"margin-left: auto !important; margin-right: 0 !important;"}]}getTextareaSelectors(){return [".tiptap.ProseMirror[contenteditable='true']",'[contenteditable="true"].ProseMirror',".query-bar [contenteditable='true']","form [contenteditable='true']"]}getSubmitButtonSelectors(){return ['button[type="submit"]','form button[type="submit"]','.query-bar button[type="submit"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"true"===e.getAttribute("contenteditable"))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),"true"===t.getAttribute("contenteditable")){t.innerHTML=`

${e}

`,t.dispatchEvent(new Event("input",{bubbles:true}));const n=window.getSelection();if(n){const e=document.createRange();e.selectNodeContents(t),e.collapse(false),n.removeAllRanges(),n.addRange(e);}return true}return false}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"true"===this.textarea.getAttribute("contenteditable")&&(this.textarea.innerHTML='


',this.textarea.dispatchEvent(new Event("input",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=document.querySelector("main");if(e){const t=e.querySelector('[class*="overflow-auto"]');if(t&&t.scrollHeight>t.clientHeight)return t;if(e.scrollHeight>e.clientHeight)return e}const t=document.querySelectorAll('[class*="overflow-y-auto"], [class*="overflow-auto"]');for(const n of Array.from(t)){const e=n;if(e.scrollHeight>e.clientHeight+100)return e}return null}getResponseContainerSelector(){return "main"}getChatContentSelectors(){return ['[class*="prose"]','[dir="ltr"]']}getUserQuerySelector(){return ".message-bubble.rounded-br-lg"}cloneUserQuerySource(e){const t=e.querySelector(".response-content-markdown");if(!t)return null;const n=(t.querySelector(".gh-user-query-original")||t).cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown").forEach(e=>e.remove()),n}isLikelyInlineCodeSpan(e){if("span"!==e.tagName.toLowerCase())return false;if(e.childElementCount>0)return false;const t=e.getAttribute("class")||"",n=/(^|\s)!?font-mono(\s|$)/.test(t),r=/(^|\s)rounded-sm(\s|$)/.test(t);return n&&r}normalizeUserQueryMarkdownSource(e){return e.querySelectorAll("span").forEach(t=>{const n=t;if(!this.isLikelyInlineCodeSpan(n))return;const r=(e.ownerDocument||document).createElement("code");r.textContent=n.textContent||"",n.replaceWith(r);}),e}extractUserQueryMarkdownFromSource(e){return Hi(this.normalizeUserQueryMarkdownSource(e)).trim()}extractUserQueryText(e){const t=this.cloneUserQuerySource(e);return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=this.cloneUserQuerySource(e);if(t){const e=this.extractUserQueryMarkdownFromSource(t);if(e)return e}return e.textContent?.trim()||""}extractUserQueryExportContent(e){return this.extractGrokUserQueryExportContent(e)}extractGrokExportMessages(e){const t=document.querySelector(this.getResponseContainerSelector())||document.body,n=this.getGrokExportMessageItems(t),r=[];for(const o of n){const t=this.findGrokUserMessageRoot(o);if(t){const n=this.extractGrokUserQueryExportContent(t,e,o).trim();n&&r.push({role:"user",content:n});continue}const n=this.findGrokAssistantMessageRoot(o);if(n){const t=this.extractGrokAssistantExportContent(n,e).trim();t&&r.push({role:"assistant",content:t});}}return r}getGrokExportMessageItems(e){const t=Array.from(e.querySelectorAll('[id^="response-"]')).filter(e=>e.querySelector(".message-bubble")&&!e.closest(".gh-main-panel"));return t.length>0?t:Array.from(e.querySelectorAll(".message-bubble")).filter(e=>!e.closest(".gh-main-panel"))}findGrokUserMessageRoot(e){const t=this.getUserQuerySelector();return e.matches(t)?e:e.querySelector(t)}findGrokAssistantMessageRoot(e){const t=".message-bubble:not(.rounded-br-lg)";return e.matches(t)?e:e.querySelector(t)}extractGrokUserQueryExportContent(e,t,n){const r=this.extractGrokUserAttachments(e,n),o=this.extractGrokUserBodyMarkdown(e);if(0===r.length)return o||this.extractUserQueryText(e);const i=this.formatGrokUserImageAttachments(r,t),a=this.formatGrokUserFileAttachments(r,t),s=a.length>0?`${le("exportAttachmentsLabel")}:\n${a.join("\n")}`:"";return [i.join("\n\n"),s,o].filter(Boolean).join("\n\n")}extractGrokUserBodyMarkdown(e){const t=this.cloneUserQuerySource(e);if(!t)return this.extractUserQueryText(e);this.removeGrokUserAttachmentNodes(t),this.removeGrokExportDecorations(t,{removeImages:true});return this.extractUserQueryMarkdownFromSource(t)||this.extractTextWithLineBreaks(t).trim()}extractGrokAssistantExportContent(e,t){return [this.extractGrokAssistantBodyMarkdown(e),this.extractGrokImageMarkdown(e,t,"generated image").join("\n\n")].filter(Boolean).join("\n\n")}extractGrokAssistantBodyMarkdown(e){const t=(e.matches(".response-content-markdown")?e:e.querySelector(".response-content-markdown")||e).cloneNode(true);this.removeGrokExportDecorations(t,{removeImages:true});const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}removeGrokExportDecorations(e,t={}){const n=["button",'[role="button"]',"svg",'[aria-hidden="true"]',".gh-user-query-markdown"];t.removeImages&&n.push("img","picture","video"),e.querySelectorAll(n.join(", ")).forEach(e=>e.remove());}removeGrokUserAttachmentNodes(e){Array.from(e.querySelectorAll('a[href], [role="group"], [aria-label], [title], [class*="file"], [class*="attachment"]')).forEach(t=>{this.isLikelyGrokAttachmentCard(t,e)&&t.remove();});}extractGrokUserAttachments(e,t){const n=this.resolveGrokUserAttachmentScope(e,t);if(!n)return [];const r=[],o=new Set,i=e=>{if(this.hasEquivalentGrokAttachment(r,e))return;const t=this.getGrokAttachmentDedupKey(e);o.has(t)||(o.add(t),r.push(e));};return this.getCachedGrokUserAttachments(n).forEach(i),this.extractGrokUserImageAttachments(n).forEach(i),this.extractGrokUserFileAttachments(n).forEach(i),r}getGrokAttachmentDedupKey(e){const t=this.extractGrokAssetIdFromSource(e.source);if(t)return `${e.kind}:asset:${t}`;const n=e.name.toLowerCase();return n?`${e.kind}:name:${n}`:`${e.kind}:${e.source}:${e.type}:${e.size}`}hasEquivalentGrokAttachment(e,t){const n=this.extractGrokAssetIdFromSource(t.source),r=t.name.toLowerCase();return e.some(e=>{if(e.kind!==t.kind)return false;const o=this.extractGrokAssetIdFromSource(e.source);return !(!o||!n||o!==n)||Boolean(r&&e.name.toLowerCase()===r)})}getCachedGrokUserAttachments(e){if(!this.exportUserAttachmentsByResponseId)return [];const t=this.extractGrokResponseId(e);return t&&this.exportUserAttachmentsByResponseId.get(t)||[]}extractGrokResponseId(e){const t=e.closest('[id^="response-"]');return (t?.id||(e.id.startsWith("response-")?e.id:"")).replace(/^response-/,"")}resolveGrokUserAttachmentScope(e,t){if(t instanceof HTMLElement)return t;const n=e.closest('[id^="response-"]');if(n instanceof HTMLElement)return n;const r=e.closest(".message-bubble")?.parentElement;if(r instanceof HTMLElement)return r;const o=e.closest(this.getUserQuerySelector());return o instanceof HTMLElement?o:null}extractGrokUserImageAttachments(e){return this.getGrokExportImages(e).filter(e=>!e.closest(".gh-user-query-markdown")).flatMap(e=>{const t=this.getGrokImageExportSource(e);if(!this.isExportableGrokImageSource(t))return [];const n=this.extractGrokImageAlt(e,t,"uploaded image");return [{kind:"image",name:n,source:t,type:this.extractFileTypeFromName(n)||"image",size:""}]})}extractGrokUserFileAttachments(e){return Array.from(e.querySelectorAll('a[href], [role="group"], [aria-label], [title], [class*="file"], [class*="attachment"]')).filter(t=>this.isLikelyGrokAttachmentCard(t,e)).flatMap(e=>{const t=this.extractGrokAttachmentCardName(e);if(!t)return [];const n=this.extractGrokAttachmentCardSource(e),r=this.extractFileTypeFromName(t);return [{kind:this.isImageAttachmentName(t,r)?"image":"file",name:t,source:n,type:r,size:this.extractGrokAttachmentCardSize(e)}]})}isLikelyGrokAttachmentCard(e,t){if(e===t)return false;if(e.closest(".gh-user-query-markdown"))return false;if(e.closest("pre, code"))return false;if(e.closest(".response-content-markdown p"))return false;return !!this.extractGrokAttachmentCardName(e)&&Boolean(e.querySelector("a[href], img, svg")||e.matches("a[href]")||this.extractGrokAttachmentCardSource(e))}extractGrokImageMarkdown(e,t,n){const r=new Set,o=[];for(const i of this.getGrokExportImages(e)){const e=this.getGrokImageExportSource(i);if(!this.isExportableGrokImageSource(e)||r.has(e))continue;r.add(e);const a=this.extractGrokImageAlt(i,e,n),s=La({source:e,alt:a,extensionHint:a},t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:n});s&&o.push(s);}return o}getGrokExportImages(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement)}getGrokImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.closest("a[href]")?.getAttribute("href")||""];for(const n of t){const e=va(n);if(e)return e}return ""}isExportableGrokImageSource(e){return !!e&&(!e.startsWith("data:image/svg+xml")&&(!/\/images\/(?:favicon|apple-touch-icon|android-chrome)/i.test(e)&&(xa(e)||e.startsWith("data:image/"))))}extractGrokImageAlt(e,t,n){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractFilenameFromUrl(t),n].map(e=>this.normalizeAttachmentText(e)).find(Boolean)||n}formatGrokUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatGrokUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"image"!==e.kind||!e.source,getLabel:e=>this.formatGrokAttachmentLabel(e)})}formatGrokAttachmentLabel(e){const t=this.formatGrokAttachmentDetails(e);return t?`${e.name} (${t})`:e.name}formatGrokAttachmentDetails(e){return [e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?e.type:"",e.size].filter(Boolean).join(", ")}extractGrokAttachmentCardName(e){const t=[...this.extractGrokAttachmentLeafTexts(e),e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e instanceof HTMLAnchorElement&&e.download||"",e.textContent||"",this.extractFilenameFromUrl(this.extractGrokAttachmentCardSource(e))];for(const n of t){const e=this.extractFilenameFromText(n);if(e)return e}return ""}extractGrokAttachmentLeafTexts(e){return Array.from(e.querySelectorAll("div, span, p")).filter(e=>0===e.children.length&&!e.querySelector("svg, img")).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean)}extractGrokAttachmentCardSource(e){const t=[];e instanceof HTMLAnchorElement&&t.push(e.getAttribute("href")||e.href||"");const n=e.closest("a[href]");n instanceof HTMLAnchorElement&&t.push(n.getAttribute("href")||n.href||""),e.querySelectorAll("a[href]").forEach(e=>{e instanceof HTMLAnchorElement&&t.push(e.getAttribute("href")||e.href||"");});for(const o of ["data-url","data-src","data-file-url","data-download-url"])t.push(e.getAttribute(o)||"");const r=e.querySelector("img");r instanceof HTMLImageElement&&t.push(this.getGrokImageExportSource(r));for(const o of t){const e=va(o);if(xa(e)||e.startsWith("data:"))return e}return ""}extractGrokAttachmentCardSize(e){const t=this.normalizeAttachmentText(e.textContent||"");return t.match(/\b\d+(?:\.\d+)?\s*[KMGT]?B\b/i)?.[0]||""}extractFilenameFromText(e){const t=this.normalizeAttachmentText(e).replace(/^(attached\s+file|attachment|file|附件|文件)[::]?\s+/i,"").trim();if(!t||this.isFileMetaText(t))return "";if(/^[^/\\]+\.[A-Za-z0-9]{1,10}$/.test(t))return t;const n=t.match(/(?:^|[\s([{])([^/\\]+?\.[A-Za-z0-9]{1,10})(?=$|[\s)\]}])/);return n?.[1]?.trim()||""}isFileMetaText(e){return /^[A-Za-z0-9.+-]{1,12}\s+\d+(?:\.\d+)?\s*[KMGT]?B$/i.test(e)}isImageAttachmentName(e,t){const n=(this.extractFileTypeFromName(e)||t).toLowerCase();return ["avif","gif","jpg","jpeg","png","svg","webp"].includes(n)}extractFileTypeFromName(e){return e.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toUpperCase()||""}extractFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename")||t.searchParams.get("file_name");return n?.trim()?n.trim():decodeURIComponent(t.pathname).split("/").pop()?.trim()||""}catch{return ""}}extractGrokAssetIdFromSource(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname.split("/").filter(Boolean),n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return t.reverse().find(e=>n.test(e))||""}catch{return ""}}normalizeAttachmentText(e){return e.replace(/\s+/g," ").trim()}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}replaceUserQueryContent(e,t){const n=e.querySelector(".response-content-markdown");if(!n)return false;if(n.querySelector(".gh-user-query-markdown"))return false;const r=Array.from(n.children),o=document.createElement("div");o.className="gh-user-query-original",o.style.display="none",r.forEach(e=>{o.appendChild(e);}),n.appendChild(o);const i=document.createElement("div");return i.className="gh-user-query-markdown gh-markdown-preview",i.innerHTML=t,n.insertBefore(i,o),true}getExportConfig(){return {userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:".message-bubble:not(.rounded-br-lg) .response-content-markdown",turnSelector:"",useShadowDOM:false}}async prepareConversationExport(e){return this.exportUserAttachmentsByResponseId=await this.collectGrokShareUserAttachments(),null}async restoreConversationAfterExport(e,t){this.exportUserAttachmentsByResponseId=null;}async collectGrokShareUserAttachments(){const e=this.extractGrokShareId();if(!e)return null;try{const t=await fetch(`/rest/app-chat/share_links/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});return t.ok?this.parseGrokShareUserAttachments(await t.json()):(console.warn("[GrokAdapter] Failed to load share attachment metadata:",t.status),null)}catch(RS){return console.warn("[GrokAdapter] Failed to load share attachment metadata:",RS),null}}extractGrokShareId(){const e=window.location.pathname.match(/^\/share\/([^/?#]+)/);return e?.[1]?decodeURIComponent(e[1]):""}parseGrokShareUserAttachments(e){const t=this.toGrokRecord(e),n=t?.responses;if(!Array.isArray(n))return null;const r=new Map;for(const o of n){const e=this.toGrokRecord(o),t=this.readGrokString(e?.responseId);if(!t)continue;const n=e?.fileAttachmentsMetadata;if(!Array.isArray(n))continue;const i=n.map(e=>this.parseGrokFileAttachmentMetadata(e)).filter(e=>null!==e);i.length>0&&r.set(t,i);}return r.size>0?r:null}parseGrokFileAttachmentMetadata(e){const t=this.toGrokRecord(e);if(!t)return null;const n=this.readGrokString(t.fileName)||this.readGrokString(t.fileMetadataId)||"file",r=this.readGrokString(t.fileMimeType)||this.extractFileTypeFromName(n),o=this.buildGrokAssetSource(this.readGrokString(t.fileUri));return {kind:r.toLowerCase().startsWith("image/")||this.isImageAttachmentName(n,r)?"image":"file",name:n,source:o,type:r,size:""}}buildGrokAssetSource(e){const t=e.trim();if(!t)return "";if(/^(blob:|data:|https?:\/\/)/i.test(t))return va(t);if(t.startsWith("//"))return `https:${t}`;if(t.startsWith("assets.grok.com/"))return `https://${t}`;const n=t.replace(/^\/+/,"");return /^(users|generated)\//i.test(n)?`https://assets.grok.com/${n}`:va(t)}toGrokRecord(e){return e&&"object"==typeof e?e:null}readGrokString(e){return "string"==typeof e?e.trim():""}async extractExportMessages(e){const t=this.extractGrokExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractGrokExportMessages(e))}getAssistantMermaidSupportMode(){return "native"}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest('[id^="response-"]');return t?t.id:null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector();if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,l)=>{if(this.isInRenderedMarkdownContainer(t))return;const c=parseInt(t.tagName.charAt(1),10);if(c<=e){const e={level:c,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=l+1;e{const c=t.tagName.toLowerCase();if(t.matches(l)){let e=this.extractUserQueryText(t),a=false;e.length>200&&(e=e.substring(0,200),a=true);const s={level:0,text:e,element:t,isUserQuery:true,isTruncated:a},c=i(t);c&&(s.id=c),n&&(s.wordCount=(e=>{const t=e.closest('[id^="response-"]');if(!t)return 0;let n=t.nextElementSibling,r=0;for(;n&&!n.querySelector(l);){const e=n.querySelector(".message-bubble:not(.rounded-br-lg)");if(e){const t=e.querySelector(".response-content-markdown");t&&(r+=t.textContent?.trim().length||0);}n=n.nextElementSibling;}if(0===r){const t=o.querySelectorAll(".message-bubble:not(.rounded-br-lg)");for(const n of Array.from(t)){if(!(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING))continue;const t=e.parentElement?.nextElementSibling?.querySelector(l);if(t&&!(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING))continue;const o=n.querySelector(".response-content-markdown");o&&(r+=o.textContent?.trim().length||0);}}return r})(t)),r.push(s);}else if(/^h[1-6]$/.test(c)){if(this.isInRenderedMarkdownContainer(t))return;const d=parseInt(c.charAt(1),10);if(d<=e){const e={level:d,text:t.textContent?.trim()||"",element:t},h=i(t);if(h&&(e.id=s(h,c,e.text)),n){let n=null;for(let t=a+1;t{const t=e.closest("ms-chat-turn")?.id||"";return this.normalizeTurnId(t)===o})||null}getScrollbarQueryEntries(){const e=Array.from(document.querySelectorAll(["ms-items-scrollbar button[aria-controls]","ms-items-scrollbar button[data-test-item-id]","ms-prompt-scrollbar button[aria-controls]","ms-prompt-scrollbar button[data-test-item-id]"].join(", "))).filter(e=>e instanceof HTMLElement),t=new Set,n=[];return e.forEach(e=>{const r=e.getAttribute("aria-controls")||e.getAttribute("data-test-item-id")||"",o=this.normalizeTurnId(r);if(!o||t.has(o))return;const i=this.normalizeScrollbarQueryText(e.getAttribute("aria-label")||e.getAttribute("title")||"");i&&(t.add(o),n.push({turnId:o,text:i,button:e,element:this.findUserQueryElementByTurnId(o),index:n.length}));}),n}getTextFromScrollbar(e){const t=this.normalizeTurnId(e);if(!t)return null;const n=this.getScrollbarQueryEntries().find(e=>e.turnId===t);return n?.text||null}async waitForUserQueryElementByTurnId(e,t,n=1600){const r=Date.now();for(;Date.now()-re.turnId===t);return !!n&&(n.button.scrollIntoView({block:"nearest",inline:"nearest"}),n.button.click(),true)}resolveScrollbarTurnIdForOutlineItem(e,t){const n=(e.id||"").match(/^aistudio-user:(.+)$/);if(n?.[1])return this.normalizeTurnId(n[1]);const r=this.getScrollbarQueryEntries();return void 0!==t?r[t-1]?.turnId||null:r.find(t=>this.isSameOutlineText(t.text,e.text))?.turnId||null}getCurrentConversationTitleFromSources(){const e=this.getSessionId();if(!e)return null;const t=document.querySelector("h1[class*='mode-title'], h1.page-title, .page-title h1"),n=t?.textContent?.trim();if(n)return n;if(this.cachedLibraryConversations&&this.cachedLibraryConversations.length>0){const t=this.cachedLibraryConversations.find(t=>t.id===e);if(t?.title?.trim())return t.title.trim()}const r=document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"]`),o=r?.textContent?.trim();return o||null}getSessionName(){return this.getCurrentConversationTitleFromSources()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()}getTextareaSelectors(){return ["textarea.textarea","textarea.cdk-textarea-autosize",'textarea[placeholder*="prompt"]','textarea[placeholder*="Start typing"]']}getSubmitButtonSelectors(){return ['ms-run-button button[type="submit"]','ms-run-button.supports-add-instead-of-run button[type="submit"]','button[ms-button][type="submit"]','button.ms-button-primary[type="submit"]']}getSubmitKeyConfig(){try{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return {key:"Enter"};return 2===JSON.parse(e).enterKeyBehavior?{key:"Ctrl+Enter"}:{key:"Enter"}}catch{return {key:"Enter"}}}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"textarea"===e.tagName.toLowerCase())}insertPrompt(e){const t=this.textarea;return !!t&&(t.isConnected?(t.focus(),"textarea"===t.tagName.toLowerCase()&&(t.value=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true})),t.selectionStart=t.selectionEnd=e.length,true)):(this.textarea=null,false))}clearTextarea(){const e=this.textarea;e&&(e.isConnected?(e.focus(),"textarea"===e.tagName.toLowerCase()&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=[".chat-container",".virtual-scroll-container",'[class*="scroll"]','main [style*="overflow"]'];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return e}const t=document.querySelector("main");if(t){const e=t.querySelector('[class*="overflow"]');if(e&&e.scrollHeight>e.clientHeight)return e}return null}getResponseContainerSelector(){return ".chat-container, main"}getChatContentSelectors(){return [".chat-turn-container",'[class*="message"]','[class*="response"]']}getWidthSelectors(){return [{selector:".chat-session-content",property:"max-width"},{selector:".chat-turn-container",property:"max-width"},{selector:".table-container > table",property:"width",value:"100%",noCenter:true,extraCss:"min-width: 100% !important;"}]}getZenModeConfig(){return {hide:["ms-navbar","ms-navbar-v2","ms-right-side-panel"]}}getCleanModeConfig(){return {hide:["ms-hallucinations-disclaimer"]}}getMarkdownFixerConfig(){return {selector:"ms-cmark-node span.ng-star-inserted",fixSpanContent:true}}getAIStudioModelSelectorButton(e=false){const t=["button.model-selector-card",".model-selector-card"];for(const o of t){const t=document.querySelector(o);if(t instanceof HTMLElement&&(!e||this.isVisible(t)))return t}const n=document.querySelector('[data-test-id="model-name"]'),r=n?.closest("button");return r instanceof HTMLElement&&(!e||this.isVisible(r))?r:null}getRunSettingsToggleButton(e=false){const t=document.querySelector('button[aria-label="Toggle run settings panel"]');return t instanceof HTMLElement&&(!e||this.isVisible(t))?t:null}clickModelSelector(){const e=this.getAIStudioModelSelectorButton();if(e)return this.simulateClick(e),true;const t=this.getRunSettingsToggleButton();if(!t)return false;this.simulateClick(t);const n=this.getAIStudioModelSelectorButton();return !!n&&(this.simulateClick(n),true)}lockModel(e,t){if(!e)return;let n=0;const r=setInterval(async()=>{n++;const o=this.getAIStudioModelSelectorButton();if(o){clearInterval(r),o.click();const n=await this.waitForModelSidebar();if(!n)return console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),void this.closeModelSidebar();await this.ensureAllModelsCategory(n);const a=`model-carousel-row-models/${e}`,s=document.getElementById(a);if(s){const n=s.querySelector("div > div > div > span:first-child"),r=n?.textContent?.trim()||e,o=this.getSessionId();o&&localStorage.setItem(`ophel:aistudio:model:${o}`,r),s.click(),t&&t();try{const e=Mi.getState().settings;e.aistudio?.collapseRunSettings&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500);}catch(i){console.error("[AIStudioAdapter] Auto-collapse run settings failed:",i);}}else console.warn(`[AIStudioAdapter] 未找到目标模型: ${e}`),this.closeModelSidebar();}else {const e=this.getRunSettingsToggleButton();e?(e.click(),n=Math.max(0,n-2)):n>=10&&(clearInterval(r),console.warn("[AIStudioAdapter] 未找到模型选择按钮"));}},1e3);}async getModelList(){let e=false,t=this.getAIStudioModelSelectorButton();if(!t){const n=this.getRunSettingsToggleButton();if(n){e=true,n.click();for(let e=0;e<20&&(await new Promise(e=>setTimeout(e,200)),t=this.getAIStudioModelSelectorButton(),!t);e++);}}if(!t)return console.warn("[AIStudioAdapter] 模型选择器按钮未找到"),[];t.click();const n=await this.waitForModelSidebar();if(!n){if(console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),e){const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();}return []}await this.ensureAllModelsCategory(n);const r=this.extractModelsFromSidebar(n);return this.closeModelSidebar(),e&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500),r}async waitForModelSidebar(){const e=Date.now();for(;Date.now()-e<5e3;){const e=document.querySelector(".ms-sliding-right-panel-dialog, mat-dialog-container.mat-mdc-dialog-container");if(e)return await new Promise(e=>setTimeout(e,300)),e;await new Promise(e=>setTimeout(e,100));}return null}async ensureAllModelsCategory(e){const t=Array.from(e.querySelectorAll("[data-test-category-button]"));if(0===t.length)return;const n=t.find(e=>"All"===e.textContent?.trim());n&&"true"!==n.getAttribute("aria-selected")&&(n.click(),await this.sleep(400));}extractModelsFromSidebar(e){const t=[];return e.querySelectorAll(".model-options-container button.content-button").forEach(e=>{const n=(e.id||"").replace("model-carousel-row-","").replace("models/",""),r=e.querySelector("div > div > div > span:first-child"),o=r?.textContent?.trim()||n;n&&o&&t.push({id:n,name:o});}),t}closeModelSidebar(){const e=document.querySelector("button[data-test-close-button]");e?e.click():document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:true}));}async loadAllConversations(){const e="/library"===window.location.pathname;if(!e){if(!(await this.navigateToLibraryViaSpa()))return void(window.location.href="/library")}const t=this.extractLibraryConversations();t.length>0&&(this.cachedLibraryConversations=t),e||window.history.back(),setTimeout(()=>{this.cachedLibraryConversations=null;},1e4);}async navigateToLibraryViaSpa(){const e=document.querySelector('ms-navbar-v2 a[href="/library"]'),t=document.querySelector('a[href="/library"]'),n=e??t;return n&&(n.closest("ms-navbar-v2")||n.hasAttribute("routerlink")||n.hasAttribute("ng-reflect-router-link"))&&n?(n.click(),this.waitForLibraryContent()):(window.history.pushState(null,"","/library"),window.dispatchEvent(new PopStateEvent("popstate",{state:null})),this.waitForLibraryContent())}async waitForLibraryContent(){for(let e=0;e<50;e++){await new Promise(e=>setTimeout(e,100));if(this.getLibraryContentElement())return await new Promise(e=>setTimeout(e,200)),true}return false}extractLibraryConversations(){const e=new Map;return Array.from(document.querySelectorAll(Hs)).forEach(t=>{const n=this.extractLibraryConversationInfo(t);n&&!e.has(n.id)&&e.set(n.id,n);}),Array.from(e.values())}getLibraryContentElement(){return document.querySelector(`${Us} table`)||document.querySelector(`${Us} .prompt-cards-container`)||document.querySelector(Hs)||this.getLibraryEmptyStateElement()}getLibraryEmptyStateElement(){return Array.from(document.querySelectorAll(Ws)).find(e=>this.isVisible(e))||null}getLibraryScrollContainer(){const e=document.querySelector(`${Us} .lib-table-wrapper`);if(e)return e;const t=document.querySelector(`${Us} .prompt-cards-container`);return t?document.scrollingElement||document.documentElement||t:document.querySelector(Us)}extractLibraryConversationInfo(e){const t=e.getAttribute("href")||"";if(!t||t.includes("new_chat"))return null;const n=t.match(/\/prompts\/([^/?#]+)/);if(!n)return null;const r=n[1],o=e.closest(".prompt-card"),i=o?.getAttribute("aria-label")?.replace(/^Open\s+/i,"").trim();return {id:r,title:e.getAttribute("title")?.trim()||e.textContent?.replace(/\s+/g," ").trim()||i||"Untitled",url:t,isActive:window.location.pathname.includes(r),isPinned:false}}extractSidebarConversations(){const e=new Map;return document.querySelectorAll('a[href*="/prompts/"]').forEach(t=>{const n=t.getAttribute("href");if(!n||n.includes("new_chat"))return;const r=n.match(/\/prompts\/([^/]+)/);if(!r)return;const o=r[1];if(e.has(o))return;const i=t.textContent?.trim()||"Untitled",a=window.location.pathname.includes(o);e.set(o,{id:o,title:i,url:n,isActive:a,isPinned:false});}),Array.from(e.values())}getConversationList(){return "/library"===window.location.pathname?this.extractLibraryConversations():this.cachedLibraryConversations&&this.cachedLibraryConversations.length>0?this.cachedLibraryConversations:this.extractSidebarConversations()}getSidebarScrollContainer(){return "/library"===window.location.pathname?this.getLibraryScrollContainer():document.querySelector("ms-navbar-v2")||document.querySelector("main")||document.body||null}getConversationObserverConfig(){return "/library"===window.location.pathname?{selector:Hs,shadow:false,extractInfo:e=>this.extractLibraryConversationInfo(e),getTitleElement:e=>e}:null}navigateToConversation(e,t){const n=document.querySelector(`${Us} a[href*="/prompts/${e}"]:not([href*="new_chat"])`);return n?(n.click(),true):(window.location.href=t||`/prompts/${e}`,true)}async deleteConversationOnSite(e){return (await this.deleteConversationsOnSite([e]))[0]||{id:e.id,success:false,method:"none",reason:xs}}async deleteConversationsOnSite(e){const t=await this.enterLibraryPageForDelete(),n=[],r=[];let o=false;try{for(let t=0;t0&&this.scheduleFullReloadAfterDelete(r),n}finally{t.enteredLibrary&&!o&&await this.restoreFromLibraryPage(t.originalPath);}}async deleteConversationOnSiteInternal(e){const t=this.shouldUseNativeDeleteApi()?await this.tryDeleteViaGrpcApi(e.id):{id:e.id,success:false,method:"none",reason:Ss};if(t.success)return t;const n=await this.deleteConversationViaUi(e.id);return {id:e.id,success:n,method:n?"ui":"none",reason:n?void 0:t.reason||xs}}shouldUseNativeDeleteApi(){return false}async tryDeleteViaGrpcApi(e){const t=await this.buildGoogleAuthorizationHeader(window.location.origin);if(!t)return {id:e,success:false,method:"none",reason:Cs};const n=this.resolveGoogleApiKey();if(!n)return {id:e,success:false,method:"none",reason:ks};const r=this.normalizePromptName(e),o=this.getDeletePromptEndpoints();let i=0;try{for(const a of o){const o=await fetch(a,{method:"POST",credentials:"include",headers:{accept:"*/*",authorization:t,"content-type":"application/json+protobuf","x-goog-api-key":n,"x-goog-authuser":this.resolveGoogAuthUser(),"x-user-agent":"grpc-web-javascript/0.1"},body:JSON.stringify([r])});if(i=o.status,o.ok)return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status){if(!(400===o.status||o.status>=500))return {id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}else if(!this.isConversationVisible(e))return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}}return 404===i?{id:e,success:!1,method:"api",reason:Es}:{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(i||0)}}catch{return {id:e,success:false,method:"api",reason:Ts}}}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}normalizePromptName(e){return e?e.startsWith("prompts/")?e:`prompts/${e}`:""}getDeletePromptEndpoints(){const e=[];this.cachedRpcOrigin&&e.push(this.cachedRpcOrigin),e.push(...this.resolveRpcOriginsFromPerformance()),e.push("https://alkalimakersuite-pa.clients6.google.com");return Array.from(new Set(e.filter(Boolean))).map(e=>`${e}${Is}/DeletePrompt`)}resolveRpcOriginsFromPerformance(){const e=performance.getEntriesByType("resource");if(!e||0===e.length)return [];const t=[];for(let n=e.length-1;n>=0;n--){const r=e[n]?.name;if(!r||!r.includes(Is))continue;const o=this.normalizeRpcOriginFromEndpoint(r);o&&t.push(o);}return Array.from(new Set(t))}normalizeRpcOriginFromEndpoint(e){try{const t=new URL(e);return this.isLikelyRpcHost(t.hostname)?`${t.protocol}//${t.host}`:null}catch{return null}}isLikelyRpcHost(e){return /(?:^|\.)alkalimakersuite-[a-z0-9-]+\.clients\d+\.google\.com$/i.test(e)}async buildGoogleAuthorizationHeader(e){const t=Math.floor(Date.now()/1e3),n=this.getCookieValue("SAPISID"),r=this.getCookieValue("__Secure-1PAPISID"),o=this.getCookieValue("__Secure-3PAPISID"),i=[],a=n||r||o;if(a){const n=await this.buildSapisidHashToken(a,e,t);n&&i.push(`SAPISIDHASH ${n}`);}if(r){const n=await this.buildSapisidHashToken(r,e,t);n&&i.push(`SAPISID1PHASH ${n}`);}if(o){const n=await this.buildSapisidHashToken(o,e,t);n&&i.push(`SAPISID3PHASH ${n}`);}return 0===i.length?null:i.join(" ")}async buildSapisidHashToken(e,t,n){try{const r=`${n} ${e} ${t}`,o=await crypto.subtle.digest("SHA-1",(new TextEncoder).encode(r));return `${n}_${Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}`}catch{return null}}resolveGoogleApiKey(){if(this.cachedApiKey&&this.isValidGoogleApiKey(this.cachedApiKey))return this.cachedApiKey;const e=window.WIZ_global_data,t=e?.SNlM0e;if(this.isValidGoogleApiKey(t))return this.cachedApiKey=t,t;for(let r=0;rt.id!==e));[`a.prompt-link[href*="/prompts/${e}"]`,`a.name-btn[href*="/prompts/${e}"]`,`a.name-link[href*="/prompts/${e}"]`,`a[href*="/prompts/${e}"]`].forEach(e=>{Array.from(document.querySelectorAll(e)).forEach(e=>{(e.closest("tr")||e.closest("li")||e.closest("mat-row")||e.closest(".prompt-card")||e).remove();});});}isConversationVisible(e){return Boolean(document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"], a.name-link[href*="/prompts/${e}"], a[href*="/prompts/${e}"]`))}scheduleFullReloadAfterDelete(e){if(0===e.length)return;const t=this.getSessionId();if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/prompts/new_chat");}catch{}}async deleteConversationViaUi(e){const t=await this.findLibraryRowByPromptId(e,1500);if(!t)return false;const n=this.findLibraryRowMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(2500);if(!r)return false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton(2500);if(!o)return false;this.simulateClick(o);const i=await this.waitForConversationRemoved(e,5e3);return i&&this.syncConversationListAfterDelete(e),i}async enterLibraryPageForDelete(){const e=`${window.location.pathname}${window.location.search}${window.location.hash}`;if("/library"===window.location.pathname)return {enteredLibrary:false,originalPath:e};return await this.navigateToLibraryViaSpa()&&"/library"===window.location.pathname?{enteredLibrary:true,originalPath:e}:{enteredLibrary:false,originalPath:e}}async restoreFromLibraryPage(e){if(!e||"/library"!==window.location.pathname)return;window.history.back();const t=Date.now();for(;Date.now()-t<3e3;){if("/library"!==window.location.pathname)return;await this.sleep(80);}}async findLibraryRowByPromptId(e,t=1200){const n=Date.now();for(;Date.now()-nthis.isVisible(e));if(n.length>0)return n.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];const r=Array.from(e.querySelectorAll("button")).filter(e=>this.isVisible(e));return 0===r.length?null:r.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getUserQuerySelector(){return ".chat-turn-container.user"}findUserQueryElement(e,t){const n=this.getScrollbarQueryEntries()[e-1];if(n){const e=this.findUserQueryElementByTurnId(n.turnId);if(!e)return null;const r=this.extractUserQueryText(e);return !t||this.isSameOutlineText(r,t)?e:null}return super.findUserQueryElement(e,t)}textCache=new Map;wordCountCache=new Map;lastSessionIdForCache=null;extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.getSessionId();this.lastSessionIdForCache!==t&&(this.textCache.clear(),this.wordCountCache.clear(),this.lastSessionIdForCache=t);const n=e.closest("ms-chat-turn")?.id;let r="";const o=this.findUserContentChunk(e);if(o)r=this.extractCleanTextFromChunk(o);else {const t=e.querySelector(".turn-content");if(t){const e=t.cloneNode(true);e.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),r=(e.textContent||"").trim();}else r=this.extractTextWithLineBreaks(e);}if(!r&&n){const e=this.getTextFromScrollbar(n);e&&(r=e);}return r?(n&&this.textCache.set(n,r),r):n&&this.textCache.has(n)?this.textCache.get(n):""}extractUserQueryMarkdown(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=(this.findUserContentChunk(e)||e).cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAttachments(e)}extractUserQueryExportContentWithAttachments(e,t){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const n=this.extractAIStudioUserAttachments(e),r=this.extractUserQueryMarkdown(e).trim()||(0===n.length?this.extractUserQueryText(e):"");if(0===n.length)return r;const o=this.formatAIStudioUserImageAttachments(n,t),i=this.formatAIStudioUserFileAttachments(n,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,r].filter(Boolean).join("\n\n")}extractAIStudioUserAttachments(e){const t=[],n=new Set;return this.extractAIStudioUserImageAttachments(e).forEach(e=>{const r=`image:${e.source||e.name}`;n.has(r)||(n.add(r),t.push(e));}),this.extractAIStudioUserFileAttachments(e).forEach(e=>{const r=`file:${e.source||e.name}:${e.details||""}`;n.has(r)||(n.add(r),t.push(e));}),t}extractAIStudioUserImageAttachments(e){return Array.from(e.querySelectorAll("ms-image-chunk img")).filter(e=>e instanceof HTMLImageElement).flatMap(e=>{const t=this.extractAIStudioImageSource(e);if(!t)return [];const n=(e.alt||e.getAttribute("title")||"uploaded image").replace(/\s+/g," ").trim();return [{kind:"image",name:n||"uploaded image",source:t,mimeHint:n}]})}extractAIStudioImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=va(n);if(e&&(!e.startsWith("data:image/svg+xml")&&xa(e)))return e}return ""}extractAIStudioUserFileAttachments(e){return Array.from(e.querySelectorAll("ms-file-chunk")).flatMap(e=>{const t=this.extractAIStudioFileName(e);return t?[{kind:"file",name:t,source:this.extractAIStudioFileSource(e),details:this.extractAIStudioFileDetails(e),mimeHint:t}]:[]})}extractAIStudioFileName(e){const t=e.querySelector(".name"),n=t?.getAttribute("title")?.trim();if(n)return n;const r=t?.textContent?.trim();if(r)return r;const o=e.getAttribute("aria-label")||e.querySelector("[aria-label]")?.getAttribute("aria-label");return o?.split(",")[0]?.trim()||""}extractAIStudioFileDetails(e){return Array.from(e.querySelectorAll(".token-count")).map(e=>e.textContent?.replace(/\s+/g," ").trim()||"").find(Boolean)||""}extractAIStudioFileSource(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=va(n.href||n.getAttribute("href")||"");if(xa(e))return e}return ""}formatAIStudioUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId(),getExtensionHint:e=>e.mimeHint||e.name})}formatAIStudioUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),getLabel:e=>this.formatAIStudioFileLabel(e),getMimeHint:e=>e.mimeHint||e.name})}formatAIStudioFileLabel(e){return e.details?`${e.name} (${e.details})`:e.name}createAIStudioUserQueryOutlineItem(e,t,n,r){let o=this.normalizeScrollbarQueryText(e),i=false;o.length>200&&(o=o.substring(0,200),i=true);const a=n?this.normalizeTurnId(n):"",s={level:0,text:o,element:t,isUserQuery:true,isTruncated:i};a&&(s.id=`aistudio-user:${a}`),void 0!==r&&(s.wordCount=r);const l=t?this.getNextTurnContextForUserQuery(t):void 0;return l&&(s.context=l),s}getNextTurnContextForUserQuery(e){const t=e.closest("ms-chat-turn"),n=t?.nextElementSibling;if(!n||"ms-chat-turn"!==n.tagName.toLowerCase())return;return this.extractTextWithLineBreaks(n).trim().substring(0,50)||void 0}findPreviousUserTurnIdForElement(e){const t=e.closest("ms-chat-turn");if(!t)return null;const n=t.querySelector(".chat-turn-container.user");if(n&&!n.contains(e))return this.normalizeTurnId(t.id);let r=t.previousElementSibling;for(;r;){if(r.querySelector(".chat-turn-container.user"))return this.normalizeTurnId(r.id);r=r.previousElementSibling;}return null}findUserContentChunk(e){const t=["ms-text-chunk","ms-prompt-chunk.text-chunk","ms-prompt-chunk","ms-cmark-node.cmark-node.user-chunk"];for(const n of t){const t=e.querySelector(n);if(!t)continue;if(this.extractCleanTextFromChunk(t))return t}return null}extractCleanTextFromChunk(e){const t=e.cloneNode(true);return t.querySelectorAll('.actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:zs,assistantResponseSelector:Fs,turnSelector:Os,useShadowDOM:false}:{userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:Rs,turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "fallback"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportBundleCache=null,this.clearExportSnapshot();const t="markdown"===e.format&&"zip"===e.packaging?la():void 0,n=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector()),r=document.querySelector(this.getResponseContainerSelector())||document.querySelector("main")||document.body,o=n instanceof HTMLElement?await this.collectExportMessageSnapshots(n,t):this.readVisibleExportMessageSnapshots(r,t);return 0===o.length?null:(t&&(this.exportBundleCache={messages:o.map(({role:e,content:t})=>({role:e,content:t})),assets:t.assets}),this.mountExportSnapshot(o),{count:o.length})}async extractExportBundle(e){return this.exportBundleCache}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundleCache=null;}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(".chat-container")||document.querySelector("main");if(!o)return r;const i=e=>{const t=e.closest("ms-chat-turn");return t&&t.id?t.id.replace(/^turn-/,""):null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector(),c=e=>{const t=e.closest("ms-chat-turn");if(!t)return 0;const n=t.id;let r=t.nextElementSibling,o=0,i=false;for(;r;){if(r.querySelector(l))break;const e=r.querySelector(".chat-turn-container.model, .chat-turn-container:not(.user)");if(e){const t=e.querySelectorAll("ms-cmark-node");for(const e of Array.from(t)){if(e.closest("ms-thought-chunk"))continue;const t=e.textContent?.trim().length||0;t>0&&(i=true,o+=t);}}r=r.nextElementSibling;}return i&&n&&this.wordCountCache.set(n,o),0===o&&n&&this.wordCountCache.has(n)?this.wordCountCache.get(n):o};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,l)=>{if(t.closest("textarea")||t.closest(".user-prompt-container"))return;if(this.isInRenderedMarkdownContainer(t))return;const c=parseInt(t.tagName.charAt(1),10);if(c<=e){const e={level:c,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=l+1;e0){const t=new Map,r=[],a=e=>{const t=(e.closest("ms-chat-turn")||e).getBoundingClientRect();if(o instanceof HTMLElement){const e=o.getBoundingClientRect();return o.scrollTop+(t.top-e.top)}return window.scrollY+t.top},l=u.filter(e=>Boolean(e.element)).map(e=>({index:e.index,renderOrder:a(e.element)})).sort((e,t)=>e.renderOrder-t.renderOrder),h=u.find(e=>"true"===e.button.getAttribute("aria-pressed")||e.button.classList.contains("ms-button-active")),g=e=>{const t=a(e);let n,r;for(const o of l){if(!(o.renderOrder<=t)){r=o;break}n=o;}return n?n.index:r?Math.max(0,r.index-1):h?.index??0};u.forEach(e=>{t.set(e.turnId,e.index);const o=e.element?this.extractUserQueryText(e.element):"",i=this.createAIStudioUserQueryOutlineItem(o||e.text,e.element,e.turnId,n&&e.element?c(e.element):void 0);r.push({item:i,order:1e5*e.index});});const p=Array.from(o.querySelectorAll(d.join(", ")));return p.forEach((a,l)=>{if(a.closest(".user-prompt-container")||a.closest("textarea"))return;if(this.isInRenderedMarkdownContainer(a))return;const c=a.tagName.toLowerCase(),d=parseInt(c.charAt(1),10);if(d>e)return;const u={level:d,text:a.textContent?.trim()||"",element:a},h=i(a);if(h&&(u.id=s(h,c,u.text)),n){let e=null;for(let n=l+1;ne.order-t.order).map(({item:e})=>e)}const h=`${l}, ${d.join(", ")}`,g=Array.from(o.querySelectorAll(h));return g.forEach((t,i)=>{const a=t.tagName.toLowerCase();if(t.classList.contains("user")&&t.classList.contains("chat-turn-container")){const e=t.closest("ms-chat-turn"),o=this.createAIStudioUserQueryOutlineItem(this.extractUserQueryText(t),t,e?.id,n?c(t):void 0);r.push(o);}else if(/^h[1-6]$/.test(a)){if(t.closest(".user-prompt-container")||t.closest("textarea"))return;if(this.isInRenderedMarkdownContainer(t))return;const s=parseInt(a.charAt(1),10);if(s<=e){const e={level:s,text:t.textContent?.trim()||"",element:t};if(n){let n=null;for(let t=i+1;te.remove());const r=this.extractAssistantResponseMarkdown(t).trim();if(n.length>0){const e=n.join("\n\n");return r?`${e}\n\n${r}`:e}return r}extractAssistantResponseMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll(`${Ds}, .author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]`).forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotesFromElement(e){const t=Array.from(e.querySelectorAll(Ds)),n=[];return t.forEach(e=>{const t=this.extractThoughtMarkdown(e).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractThoughtMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}normalizeAssistantExportDom(e){this.unwrapCmarkNodes(e),this.replaceInlineCodeSpans(e),this.replaceKatexComponents(e),this.replaceCodeBlockComponents(e);}unwrapCmarkNodes(e){Array.from(e.querySelectorAll("ms-cmark-node")).forEach(e=>{e instanceof HTMLElement&&e.parentNode&&e.replaceWith(...Array.from(e.childNodes));});}replaceInlineCodeSpans(e){e.querySelectorAll(".inline-code").forEach(e=>{if(!(e instanceof HTMLElement))return;if("code"===e.tagName.toLowerCase())return;const t=document.createElement("code");t.textContent=e.textContent||"",e.replaceWith(t);});}replaceKatexComponents(e){e.querySelectorAll("ms-katex").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim()||"";if(!t)return;const n=document.createElement(e.classList.contains("inline")?"span":"div");n.className=e.classList.contains("inline")?"math-inline":"math-block",n.setAttribute("data-math",t),e.replaceWith(n);});}replaceCodeBlockComponents(e){e.querySelectorAll("ms-code-block").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=this.extractCodeBlockFromComponent(e);if(!t)return;const n=document.createElement("pre"),r=document.createElement("code");t.language&&(r.className=`language-${t.language}`),r.textContent=t.code,n.appendChild(r),e.replaceWith(n);});}extractCodeBlockFromComponent(e){const t=e.querySelector("pre code")||e.querySelector("pre"),n=t?.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(!n.trim())return null;return {language:[e.getAttribute("data-test-language"),e.getAttribute("data-language"),e.querySelector(".mat-expansion-panel-header-title .ng-star-inserted:last-child")?.textContent].map(e=>e?.trim().toLowerCase()||"").find(e=>e&&"code"!==e)||"",code:n}}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=document.querySelectorAll(`${Rs}, .model-prompt-container`);try{for(let e=t.length-1;e>=0;e-=1){const n=this.extractAssistantResponseText(t[e]).trim();if(n)return n}return null}finally{this.exportIncludeThoughtsOverride=e;}}isExportSnapshotElement(e){return e.hasAttribute(Bs)}async collectExportMessageSnapshots(e,t){const n=Array.from((e.querySelector("ms-chat-session")||document).querySelectorAll(Ls)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ps}]`));return 0===n.length?this.collectExportMessageSnapshotsByScrollSweep(e,t):this.collectExportMessageSnapshotsByDomIteration(e,n,t)}async collectExportMessageSnapshotsByDomIteration(e,t,n){const r=e.scrollTop,o=this.shouldIncludeThoughtsInExport(),i=[];let a=[],s=[];const l=e=>{if(0===a.length||!o)return void(a=[]);const t=a[a.length-1],n=this.buildAssistantContentFromModelTurns(a,o);n&&i.push({role:_s,turnKey:`assistant:${t.id||`idx:${e}`}`,order:e,content:n}),a=[];},c=()=>{if(0===s.length)return;const e=[];for(const t of s){const r=this.getUserContainerForTurn(t);if(!r)continue;const o=this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAttachments(r,n));o&&e.push(o);}if(e.length>0){const n=s[0],r=t.indexOf(n);i.push({role:$s,turnKey:`user:${n.id||`idx:${r}`}`,order:r,content:e.join("\n\n")});}s=[];};try{for(let e=0;ee.order-t.order)}async retryMissingTurns(e,t,n,r){const o=new Set(t.filter(e=>e.role===$s).map(e=>e.turnKey.replace(/^user:/,""))),i=new Set(t.filter(e=>e.role===_s).map(e=>e.turnKey.replace(/^assistant:/,""))),a=[];let s=null;for(let c=0;c0&&t.push({role:$s,turnKey:`user:${n.id||`idx:${o}`}`,order:o,content:a.join("\n\n")});}for(const r of l){const o=e.indexOf(r);if(o<0)continue;const i=[];for(let t=o-1;t>=0;t-=1){const n=e[t],r=n.querySelector(".chat-turn-container.model");if(!r||!this.isThoughtOnlyModelTurn(r))break;i.unshift(n);}i.push(r);for(const e of i){try{e.scrollIntoView({block:"start",behavior:"instant"});}catch{e.scrollIntoView({block:"start"});}await this.waitForTurnContentMounted(e,5e3);}const a=this.buildAssistantContentFromModelTurns(i,n);a&&t.push({role:_s,turnKey:`assistant:${r.id||`idx:${o}`}`,order:o,content:a});}}}turnHasMountedContent(e){const t=e.querySelector("ms-prompt-chunk");if(!t)return false;if(t.querySelector("ms-text-chunk, ms-thought-chunk, ms-image-chunk, ms-file-chunk, img"))return true;return (t.textContent||"").trim().length>0}async waitForTurnContentMounted(e,t){const n=Date.now()+Math.floor(t/2);for(;Date.now()null!==e.closest(Ds))}buildAssistantContentFromModelTurns(e,t){if(0===e.length)return "";const n=[];for(const r of e){const e=r.querySelector(".chat-turn-container.model");if(!e)continue;if(this.isThoughtOnlyModelTurn(e)){if(!t)continue;this.extractThoughtBlockquotesFromElement(e).forEach(e=>n.push(e));continue}const o=this.getAssistantFragmentsForTurn(r),i=[];for(const t of o){const e=this.normalizeExportMessageContent(this.extractAssistantResponseText(t));e&&i.push(e);}i.length>0&&n.push(i.join("\n\n"));}return n.join("\n\n")}async collectExportMessageSnapshotsByScrollSweep(e,t){const n=this.buildExportSnapshotPositions(e),r=e.scrollTop;let o=[];try{for(const r of n){e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const n=this.readVisibleExportMessageSnapshots(e,t);o=this.mergeExportMessageBatch(o,n);}}finally{e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return this.repairLikelyTruncatedUserSnapshots(o,e,t)}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}readVisibleExportMessageSnapshots(e,t){return Array.from(e.querySelectorAll(Ls)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ps}]`)).flatMap(n=>this.extractExportSnapshotsFromTurn(n,e,t))}extractExportSnapshotsFromTurn(e,t,n){const r=[],o=this.getTurnRenderOrder(e,t),i=this.getUserContainerForTurn(e);if(i){const t=this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAttachments(i,n));t&&r.push({role:$s,turnKey:this.getExportTurnKey(e,"user",t),order:o,content:t});}const a=this.getAssistantFragmentsForTurn(e);if(a.length>0){let t="";a.forEach(e=>{const n=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));t=this.mergeSnapshotContent(t,n);}),t&&r.push({role:_s,turnKey:this.getExportTurnKey(e,"assistant",t),order:o+.5,content:t});}return r}getTurnRenderOrder(e,t){const n=e.getBoundingClientRect();if(t instanceof HTMLElement){const e=t.getBoundingClientRect();return t.scrollTop+(n.top-e.top)}return window.scrollY+n.top}getUserContainerForTurn(e){return Array.from(e.querySelectorAll(".chat-turn-container.user")).filter(t=>t instanceof HTMLElement&&t.closest(Ls)===e)[0]||null}getAssistantFragmentsForTurn(e){return Array.from(e.querySelectorAll(Ns)).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(Ls)!==e)return false;const n=t.parentElement?.closest(Ns);return n?.closest(Ls)!==e})}getExportTurnKey(e,t,n){const r=e.closest("ms-chat-turn")?.id?.replace(/^turn-/,"").trim();if(r)return `${t}:${r}`;return `${t}:content:${n.replace(/\s+/g," ").trim().slice(0,120)}`}mergeSnapshotContent(e,t){if(!t)return e;if(!e)return t;if(e===t||e.includes(t))return e;if(t.includes(e))return t;const n=this.normalizeSnapshotComparisonText(e),r=this.normalizeSnapshotComparisonText(t);if(n&&r){if(r.startsWith(n)&&t.length>=e.length)return t;if(n.startsWith(r)&&e.length>=t.length)return e}return `${e}\n\n${t}`.trim()}async repairLikelyTruncatedUserSnapshots(e,t,n){const r=e.filter(e=>this.isLikelyTruncatedUserSnapshot(e));if(0===r.length)return e;const o=e.map(e=>({...e})),i=t.scrollTop;try{for(const e of r){const r=Math.max(0,e.order-Math.max(120,.25*t.clientHeight)),i=e.order+Math.max(120,.25*t.clientHeight),a=[r,e.order,i].map(e=>Math.round(e));for(const s of a){t.scrollTop=s,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),await this.sleep(120);const r=this.readVisibleExportMessageSnapshots(t,n).find(t=>t.turnKey===e.turnKey);if(!r)continue;const i=o.findIndex(t=>t.turnKey===e.turnKey);if(-1===i)break;if(o[i]={...o[i],order:Math.min(o[i].order,r.order),content:this.mergeSnapshotContent(o[i].content,r.content)},!this.isLikelyTruncatedUserSnapshot(o[i]))break}}}finally{t.scrollTop=i,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return o}isLikelyTruncatedUserSnapshot(e){if(e.role!==$s)return false;const t=e.content.trim();return /(?:\.{3}|…)$/.test(t)}normalizeSnapshotComparisonText(e){return e.replace(/\r\n/g,"\n").replace(/\u2026/g,"...").replace(/\.{3}\s*$/g,"").replace(/\s+/g," ").trim()}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));const n=e.map(e=>({...e}));let r=null;for(let o=0;ot.turnKey===e.turnKey);if(-1!==i){const t=n[i];n[i]={...t,order:Math.min(t.order,e.order),content:this.mergeSnapshotContent(t.content,e.content)},r=i;continue}const a=this.findNextKnownSnapshotIndex(n,t,o+1);let s=n.length;null!==r?(s=r+1,null!==a&&s>a&&(s=a)):null!==a&&(s=a),n.splice(s,0,{...e}),r=s;}return n}findNextKnownSnapshotIndex(e,t,n){for(let r=n;re.turnKey===n);if(-1!==o)return o}return null}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(Ps,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(qs,"1");const r=document.createElement("div");r.setAttribute(Bs,e.role),r.textContent=e.content,n.appendChild(r),t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${Ps}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}getNewChatButtonSelectors(){return ['button[iconname="add"]','button[data-test-clear="outside"]','button .material-symbols-outlined[aria-hidden="true"]']}async toggleTheme(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);n.theme=e,localStorage.setItem("aiStudioUserPreference",JSON.stringify(n));const r=document.body;"dark"===e?(r.classList.add("dark-theme"),r.classList.remove("light-theme")):(r.classList.remove("dark-theme"),r.classList.add("light-theme")),r.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage}));const o=document.querySelector("app-root, ms-app, body");return o&&o.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}catch(RS){return console.error("[AIStudioAdapter] toggleTheme error:",RS),false}}applySettings(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);let r=!1;if(void 0!==e.collapseNavbar){const t=!e.collapseNavbar;n.isNavbarExpanded!==t&&(n.isNavbarExpanded=t,r=!0);}if(void 0!==e.collapseTools){const t=!e.collapseTools;n.areToolsOpen!==t&&(n.areToolsOpen=t,r=!0);}if(void 0!==e.collapseAdvanced){const t=!e.collapseAdvanced;n.isAdvancedOpen!==t&&(n.isAdvancedOpen=t,r=!0);}if(void 0!==e.enableSearch&&n.enableSearchAsATool!==e.enableSearch&&(n.enableSearchAsATool=e.enableSearch,r=!0),e.defaultModel&&""!==e.defaultModel.trim()){const t=e.defaultModel.trim();n.promptModel!==t&&(n.promptModel=t,n._promptModelOverride=t,r=!0);}r&&(localStorage.setItem("aiStudioUserPreference",JSON.stringify(n)),window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage})));}catch(RS){console.error("[AIStudioAdapter] applySettings error:",RS);}}},new class extends vs{activeOrganizationId=null;activeOrganizationIdExpiresAt=0;exportDocumentCache=[];exportIncludeThoughtsOverride=null;exportThoughtBlocks=new WeakMap;exportThoughtBlocksByAssistantIndex=new Map;match(){return window.location.hostname.includes("claude.ai")||window.location.hostname.includes("claude.com")}getSiteId(){return uo}getName(){return "Claude"}getThemeColors(){return {primary:"#d97757",secondary:"#c66045"}}getNewTabUrl(){return "https://claude.ai/new"}isNewConversation(){return "/new"===window.location.pathname||"/"===window.location.pathname}isSharePage(){return window.location.pathname.startsWith("/public/")||window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/chat\/[a-f0-9-]+(?:\/|$)/i.test(window.location.pathname)}getConversationList(){const e=document.querySelectorAll('a[data-dd-action-name="sidebar-chat-item"]');return Array.from(e).map(e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"",a=window.location.href.includes(r);let s=false;const l=e.closest("div.flex.flex-col");if(l){const e=l.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=l.querySelector("ul"),r=n?.classList.contains("-mx-1.5");s=t||r;}return {id:r,title:i,url:t.startsWith("http")?t:`https://claude.ai${t}`,isActive:a,isPinned:s}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("nav");if(e){return e.querySelector("div.overflow-y-auto")||e}return null}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.activeOrganizationId;if(this.isUserscriptRuntime()){const e=await this.fetchOrganizationIdFromApi();if(e)return this.activeOrganizationId=e,this.activeOrganizationIdExpiresAt=t+6e5,e;const n=this.getOrganizationIdFromStorage();if(n)return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getCookieValue("lastActiveOrg");return this.isValidOrganizationId(r)?(this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r):null}const n=this.getCookieValue("lastActiveOrg");if(this.isValidOrganizationId(n))return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getOrganizationIdFromStorage();if(r)return this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r;const o=await this.fetchOrganizationIdFromApi();return o?(this.activeOrganizationId=o,this.activeOrganizationIdExpiresAt=t+6e5,o):null}isUserscriptRuntime(){return true}async fetchOrganizationIdFromApi(){try{const e=await fetch("/api/organizations",{method:"GET",headers:{accept:"application/json, text/plain, */*"},credentials:"include"});if(!e.ok)return null;const t=await e.json();return this.extractOrganizationId(t)}catch{return null}}getOrganizationIdFromStorage(){const e=["lastActiveOrg","activeOrg","organizationId","lastActiveOrganization","LSS-lastActiveOrg"];for(const t of e){const e=localStorage.getItem(t),n=this.extractOrganizationId(e);if(n)return n}for(let t=0;t0?t:null}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;const n=await this.findConversationMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return false;if(this.simulateClick(r),await this.waitForConversationRemoved(e,1e3))return true;const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,5e3)}async isConversationStillVisible(e){return !!(await this.findConversationRowWithRetry(e))}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`a[data-dd-action-name="sidebar-chat-item"][href="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href$="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href*="/chat/${e}?"]`)}async findConversationMenuButton(e){const t=e.closest("li")||e.parentElement||e,n=['button[aria-haspopup="menu"]','button[data-testid*="menu"]','button[aria-label*="more"]','button[aria-label*="More"]','button[aria-label*="options"]','button[aria-label*="Options"]','button[aria-label*="更多"]','button[aria-label*="选项"]','button[aria-label*="選項"]'].join(", ");for(let r=0;r<10;r++){t.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),t.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const r=Array.from(t.querySelectorAll(n)).filter(e=>this.isVisible(e));if(r.length>0){const e=this.pickRightMostElement(r);if(e)return e}const o=Array.from(t.querySelectorAll("button")).filter(e=>this.isVisible(e));if(o.length>0){const e=this.pickRightMostElement(o);if(e)return e}await this.sleep(80);}return null}getMenuScopeFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"], [data-radix-menu-content], [data-state="open"]')).filter(e=>this.isVisible(e));return 0===n.length?null:this.pickNearestElement(e,n)}async waitForDeleteMenuItem(e,t=2500){const n=Date.now();for(;Date.now()-nthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nt.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}pickNearestElement(e,t){if(0===t.length)return null;const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2;let i=null,a=Number.POSITIVE_INFINITY;for(const s of t){const e=s.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,l=Math.hypot(t-r,n-o);ln.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getTextareaSelectors(){return ['[contenteditable="true"]',".ProseMirror",'div[role="textbox"]']}getSubmitButtonSelectors(){return ['button[aria-label="Send Message"]','button[data-testid="send-button"]','button[aria-label="Send"]']}isValidTextarea(e){if(null===e.offsetParent)return false;if(e.closest(".gh-main-panel"))return false;const t="true"===e.getAttribute("contenteditable"),n=e.classList.contains("ProseMirror"),r="textbox"===e.getAttribute("role");return t||n||r}insertPrompt(e){const t=this.getTextareaElement();if(!t)return false;t.focus();try{if(document.execCommand("selectAll",!1,void 0),!document.execCommand("insertText",!1,e))throw new Error("execCommand failed")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e){e.focus();try{document.execCommand("selectAll",!1,void 0),document.execCommand("delete",!1,void 0);}catch{e.textContent="";}e.dispatchEvent(new Event("input",{bubbles:true}));}}getConversationTitle(){const e=this.getSessionId();if(e&&"default"!==e){const t=document.querySelector(`a[href*="${e}"]`);if(t)return t.querySelector("span.truncate")?.textContent?.trim()||null}return null}findClaudeScrollContainer(){const e=e=>{if(!e)return false;const t=window.getComputedStyle(e).overflowY;return !("auto"!==t&&"scroll"!==t&&"overlay"!==t&&"true"!==e.getAttribute("data-autoscroll-container"))&&e.scrollHeight>e.clientHeight+4};let t=Array.from(document.querySelectorAll('.font-claude-response, [data-testid="user-message"]')).find(e=>!e.closest(Zl))||null;for(;t&&t!==document.body;){if(e(t))return t;t=t.parentElement;}const n=['[data-autoscroll-container="true"]',"#main-content .overflow-y-scroll","#root .overflow-y-auto.overflow-x-hidden"];for(const r of n){const t=document.querySelector(r);if(e(t))return t}return null}getScrollContainer(){const e=this.findClaudeScrollContainer(),t=document.scrollingElement,n=e?e.scrollHeight-e.clientHeight:-1,r=t?t.scrollHeight-t.clientHeight:-1;return e&&t&&r>n+100&&t.scrollHeight>t.clientHeight+4?t:e||(t&&t.scrollHeight>t.clientHeight+4?t:super.getScrollContainer())}getChatContentSelectors(){return ['div[data-testid="user-message"]',"div.font-claude-response"]}isClaudeDocumentPanelOpen(){return null!==this.getClaudeDocumentMarkdownElement()}getClaudeDocumentRoot(){return document.querySelector(Zl)}getClaudeDocumentMarkdownElement(){return document.querySelector("#wiggle-file-content .standard-markdown, #wiggle-file-content .progressive-markdown")}getClaudeDocumentTitle(){return this.getClaudeDocumentRoot()?.querySelector("h1")?.textContent?.trim()||""||null}getClaudeArtifactCells(e=document){return Array.from(e.querySelectorAll(Xl))}getClaudeDocumentArtifactCells(e=document){return this.getClaudeArtifactCells(e).filter(e=>this.isMarkdownDocumentArtifact(e))}isMarkdownDocumentArtifact(e){return /\bMD\b/i.test(this.getClaudeArtifactMetadata(e))}getClaudeArtifactMetadata(e){return e.querySelector(".text-text-400")?.textContent?.trim()||""}getClaudeArtifactTitle(e){return e.querySelector(".line-clamp-1")?.textContent?.trim()||""||"Document"}getClaudeArtifactButton(e){const t=e.closest(".group\\/artifact-block, [class*='group/artifact-block']"),n=t?.querySelector('button[aria-label="View Document"]')||e.querySelector('button[aria-label="View Document"]');return n instanceof HTMLElement?n:null}async openClaudeArtifactDocument(e){const t=this.getClaudeArtifactButton(e);if(!t)return null;const n=this.getClaudeDocumentSignature();return t.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),this.simulateClick(t),this.waitForClaudeDocumentMarkdown(n)}getClaudeDocumentSignature(e=this.getClaudeDocumentMarkdownElement()){const t=e?.textContent?.trim()||"";return t?`${t.length}:${t.slice(0,160)}:${t.slice(-160)}`:""}async waitForClaudeDocumentMarkdown(e="",t=3e3){const n=Date.now();for(;Date.now()-nsetTimeout(e,100));}return this.getClaudeDocumentMarkdownElement()}closeClaudeDocumentPanel(){const e=this.findClaudeDocumentPanelButton('button[aria-label="Go back"]');e instanceof HTMLElement&&this.simulateClick(e);}findClaudeDocumentPanelButton(e){const t=this.getClaudeDocumentRoot();let n=t?.parentElement||null;for(;n&&n!==document.body;){const t=n.querySelector(e);if(t instanceof HTMLElement)return t;n=n.parentElement;}return null}getModelName(){const e=document.querySelector('button[data-testid="model-selector-dropdown"]');return e&&e.textContent?e.textContent.trim():null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-testid="model-selector-dropdown"]'],menuItemSelector:'[role="menuitem"], [role="menuitemradio"]',checkInterval:1e3,maxAttempts:20,subMenuSelector:'[aria-haspopup="menu"]',subMenuTriggers:["more models","更多模型"]}}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,Math.max(t.width-1,1))),r=t.top+Math.max(1,Math.min(t.height/2,Math.max(t.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r},i=t=>{"function"==typeof PointerEvent&&e.dispatchEvent(new PointerEvent(t,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));};i("pointerenter"),i("pointerover"),i("pointermove"),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new MouseEvent("mousemove",o));const a=e.getAttribute("role"),s=(e.textContent||"").toLowerCase();"menuitem"===a&&(e.matches('[aria-haspopup="menu"]')||s.includes("more models")||s.includes("更多模型"))||(i("pointerdown"),e.dispatchEvent(new MouseEvent("mousedown",o)),i("pointerup"),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o)));}getNewChatButtonSelectors(){return ['a[data-dd-action-name="sidebar-new-item"]','a[href="/new"]']}getDefaultLockSettings(){return {enabled:false,keyword:"sonnet"}}getClaudeChatCandidates(e){return Array.from(e.querySelectorAll(this.getChatContentSelectors().join(", ")))}getRelativeTop(e,t){const n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}getOutlineRoot(){return this.getScrollContainer()||this.findClaudeScrollContainer()||document}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getClaudeChatCandidates(e);if(!t.length)return null;const n=e.scrollTop;let r=null,o=Number.NEGATIVE_INFINITY;t.forEach(t=>{const i=this.getRelativeTop(e,t);i<=n+100&&i>o&&(r=t,o=i);}),r||(r=t[0],o=this.getRelativeTop(e,r));const i=n-o,a=r.getAttribute("data-message-id")||r.id;if(a){let e=`[data-message-id="${a}"]`;return r.matches(e)||(e=`#${a}`),{type:"selector",selector:e,offset:i}}const s=t.indexOf(r);if(-1===s)return null;return {type:"index",index:s,offset:i,textSignature:(r.textContent||"").trim().substring(0,50)}}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getClaudeChatCandidates(t);if(r[e.index]){if(n=r[e.index],e.textSignature){(n.textContent||"").trim().substring(0,50)!==e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||n);}}else e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||null);}if(!n)return false;const r=this.getRelativeTop(t,n)+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}getOutlineSources(){const e=[{id:"conversation",kind:"conversation",label:"对话",available:true}],t=this.extractClaudeDocumentOutline(6,false);return t.length>0&&e.push({id:Kl,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=this.getClaudeDocumentSignature();return `conversation:1|${Kl}:${e||"0"}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===Kl?this.extractClaudeDocumentOutline(t,r):this.extractOutline(t,n,r)}extractOutline(e=6,t=false,n=false){const r=[],o=this.getOutlineRoot(),i=e=>e.replace(/[\s\S]*?<\/thinking>/gi,"").trim(),a=this.getUserQuerySelector(),s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(Zl)&&null!==e.closest(".font-claude-response"));if(s.forEach((t,o)=>{const i=parseInt(t.tagName[1]);if(i>e)return;if(t.classList.contains("pointer-events-none"))return;if(t.classList.contains("sr-only"))return;const a=t.textContent?.trim()||"";if(!a)return;const l={level:i,text:a.length>200?a.slice(0,200):a,element:t,isUserQuery:false,isTruncated:a.length>80};if(n){let e=null;for(let t=o+1;t{const t=e.textContent?.trim()||"";if(!t)return;const s={level:0,text:t.length>200?t.slice(0,200):t,element:e,isUserQuery:true,isTruncated:t.length>60};n&&(s.wordCount=(e=>{const t=Array.from(o.querySelectorAll(a)),n=Array.from(o.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(Zl)),r=t.indexOf(e);if(-1===r)return 0;const s=t[r+1];let l=0;for(const o of n){if(!(e.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(s&&s.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING)continue;const t=o.querySelector(".standard-markdown, .progressive-markdown");if(t){const e=t.textContent?.trim()||"";l+=i(e).length;}}return l})(e)),r.push(s);}),r.sort((e,t)=>{if(!e.element||!t.element)return 0;return e.element.compareDocumentPosition(t.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1});}return r}extractClaudeDocumentOutline(e=6,t=false){const n=this.getClaudeDocumentMarkdownElement();return n instanceof Element?Il(n,{maxLevel:e,showWordCount:t,idPrefix:"claude-document",shouldSkipHeading:e=>this.shouldSkipClaudeDocumentHeading(e),calculateWordCount:(e,t,n)=>this.calculateRangeWordCount(e,t,n)}):[]}shouldSkipClaudeDocumentHeading(e){return e.classList.contains("sr-only")||this.isInRenderedMarkdownContainer(e)}findClaudeDocumentHeading(e,t){const n=this.getClaudeDocumentMarkdownElement();return n?Ll(n,e,t,e=>this.shouldSkipClaudeDocumentHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===Kl){return Nl(this.getClaudeDocumentMarkdownElement())||this.getClaudeDocumentRoot()}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===Kl?this.findClaudeDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===Kl){if(Rl(e,Nl(e)||this.getOutlineScrollContainer(t)))return}this.scrollToOutlineTarget(e);}isGenerating(){if(document.querySelector('button[aria-label="Stop response"]'))return true;return !!document.querySelector('[class*="streaming"], [class*="typing"]')}getStopButtonSelectors(){return ['button[aria-label="Stop response"]']}getNetworkMonitorConfig(){return {urlPatterns:["/api/"],urlPathEndsWith:["/completion"],silenceThreshold:500}}getExportConfig(){return {userQuerySelector:'[data-testid="user-message"]',assistantResponseSelector:".font-claude-response",turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}getLatestReplyText(){const e=Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(Zl));if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".standard-markdown, .progressive-markdown");if(n){return Hi(n).trim()||n.textContent?.trim()||null}return t.textContent?.trim()||null}getResponseContainerSelector(){return ".font-claude-response"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportDocumentCache=[],this.exportThoughtBlocks=new WeakMap,this.exportThoughtBlocksByAssistantIndex=new Map;const t=e.includeThoughts?await this.expandClaudeThoughtBlocksForExport():[];e.includeThoughts&&this.captureClaudeThoughtBlocksForExport();const n={documentPanelWasOpen:this.isClaudeDocumentPanelOpen(),documentSignature:this.getClaudeDocumentSignature(),documentTitle:this.getClaudeDocumentTitle(),documentArtifactIndex:null,thoughtContainersExpandedForExport:t};if(!this.shouldCollectClaudeDocumentsForExport(e))return n;if(this.exportDocumentCache=await this.collectClaudeDocumentArtifacts(),n.documentPanelWasOpen&&n.documentSignature){const e=this.findCachedClaudeDocumentByState(n);n.documentArtifactIndex=e?.index??null;}return n}async restoreConversationAfterExport(e,t){try{if(!this.isClaudeExportLifecycleState(t))return;if(t.documentPanelWasOpen)return void(await this.restoreClaudeDocumentPanel(t));this.closeClaudeDocumentPanel();}finally{this.isClaudeExportLifecycleState(t)&&this.restoreClaudeThoughtBlocksAfterExport(t),this.exportDocumentCache=[],this.exportIncludeThoughtsOverride=null,this.exportThoughtBlocks=new WeakMap,this.exportThoughtBlocksByAssistantIndex=new Map;}}isClaudeExportLifecycleState(e){return "object"==typeof e&&null!==e&&"documentPanelWasOpen"in e&&"boolean"==typeof e.documentPanelWasOpen}shouldCollectClaudeDocumentsForExport(e){return "markdown"===e.format||"clipboard"===e.format}async restoreClaudeDocumentPanel(e){if(!e.documentSignature||this.getClaudeDocumentSignature()===e.documentSignature)return;const t=this.findCachedClaudeDocumentByState(e),n=true===t?.element.isConnected?t.element:this.getClaudeDocumentArtifactCells()[t?.index??-1];n&&await this.openClaudeArtifactDocument(n);}findCachedClaudeDocumentByState(e){if(null!==e.documentArtifactIndex&&void 0!==e.documentArtifactIndex){const t=this.exportDocumentCache.find(t=>t.index===e.documentArtifactIndex);if(t)return t}if(e.documentSignature){const t=this.exportDocumentCache.find(t=>t.signature===e.documentSignature);if(t)return t}if(e.documentTitle){const t=this.exportDocumentCache.filter(t=>t.title===e.documentTitle);if(1===t.length)return t[0]}return null}async extractExportBundle(e){return this.hasClaudeExportAssets()?this.createExportBundleFromMessages(e=>this.extractClaudeExportMessages(e)):null}async extractExportMessages(e){return 0!==this.exportDocumentCache.length||this.isClaudeDocumentPanelOpen()||this.hasClaudeUserAttachments()||this.hasClaudeThoughtExportCache()?this.extractClaudeExportMessages():null}getObserveTarget(){return this.getScrollContainer()}getUserQuerySelector(){return '[data-testid="user-message"]'}extractUserQueryText(e){return e.textContent?.trim()||""}extractUserQueryExportContent(e){return this.extractClaudeUserQueryExportContent(e)}hasClaudeExportAssets(){return this.exportDocumentCache.length>0||this.hasClaudeUserAttachments()}hasClaudeUserAttachments(){const e=this.getOutlineRoot();return Array.from(e.querySelectorAll(this.getUserQuerySelector())).some(e=>this.extractClaudeUserAttachments(e).length>0)}extractUserQueryMarkdown(e){const t=e.querySelectorAll("p.whitespace-pre-wrap");if(0===t.length)return "";const n=[];return t.forEach(e=>{const t=e.textContent||"";rc(t)&&n.push(t);}),0===n.length?"":"# CLAUDE_INCREMENTAL\nplaceholder"}replaceUserQueryContent(e,t){if(e.querySelector(".gh-claude-enhanced"))return false;const n=e.querySelectorAll("p.whitespace-pre-wrap");if(0===n.length)return false;let r=false;return n.forEach(e=>{const t=e.textContent||"";if(!rc(t))return;const n=$l(t,false,{enableMath:true}),o=document.createElement("div");o.className="gh-claude-enhanced gh-user-query-markdown gh-markdown-preview whitespace-pre-wrap break-words",o.innerHTML=n,e.replaceWith(o),r=true;}),r}extractClaudeUserQueryExportContent(e,t){const n=this.extractUserQueryText(e).trim(),r=this.extractClaudeUserAttachments(e);if(0===r.length)return n;const o=this.formatClaudeUserImageAttachments(r,t),i=this.formatClaudeUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractClaudeUserAttachments(e){const t=this.getClaudeUserMessageContainer(e);if(!t)return [];const n=[],r=new Set;return this.extractClaudeUserImageAttachments(t).forEach(e=>{const t=`image:${e.source||e.name}`;r.has(t)||(r.add(t),n.push(e));}),this.extractClaudeUserFileAttachments(t).forEach(e=>{const t=`file:${e.source||e.name}:${e.type||""}`;r.has(t)||(r.add(t),n.push(e));}),n}getClaudeUserMessageContainer(e){const t=e.closest('[data-user-message-bubble="true"]');if(!t)return e;let n=null,r=t.parentElement;for(;r&&r!==document.body&&!r.matches(".font-claude-response, main, [role='main']")&&!(r.querySelectorAll(this.getUserQuerySelector()).length>1);){if(r.querySelector(Jl)||r.querySelector("img")){n=r;break}r=r.parentElement;}return n||t}extractClaudeUserImageAttachments(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&!e.closest(Zl)).flatMap(e=>{if(e.closest(Jl))return [];const t=va(e.currentSrc||e.src||e.getAttribute("src")||"");if(!t||!xa(t))return [];const n=(e.alt||"uploaded image").replace(/\s+/g," ").trim();return [{kind:"image",name:n||"uploaded image",alt:n,source:t}]})}extractClaudeUserFileAttachments(e){return Array.from(e.querySelectorAll(Jl)).flatMap(e=>{const t=this.extractClaudeUserFileName(e);if(!t)return [];return [{kind:"file",name:t,type:this.extractClaudeUserFileType(e),source:this.extractClaudeUserFileSource(e)}]})}extractClaudeUserFileName(e){const t=e.querySelector("h1, h2, h3, h4, h5, h6")?.textContent?.trim();if(t)return t;const n=e.querySelector("[aria-label]")?.getAttribute("aria-label")||"";return n.split(",")[0]?.trim()||""}extractClaudeUserFileType(e){const t=Array.from(e.querySelectorAll("p")).map(e=>e.textContent?.trim()||"").find(e=>/^[A-Za-z0-9.+-]{1,12}$/.test(e));if(t)return t.toLowerCase();const n=e.querySelector("[aria-label]")?.getAttribute("aria-label")||"";return n.split(",")[1]?.trim().toLowerCase()||""}extractClaudeUserFileSource(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const o of t){const e=va(o.href||o.getAttribute("href")||"");if(xa(e))return e}const n=e.querySelector("img");if(n instanceof HTMLImageElement){const e=va(n.currentSrc||n.src||n.getAttribute("src")||"");if(xa(e))return e}const r=this.extractClaudeDownloadableAttributeUrl(e);return r||""}extractClaudeDownloadableAttributeUrl(e){const t=["href","src","data-href","data-src","data-url","data-file-url","data-download-url"],n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of t){const t=va(r.getAttribute(e)||"");if(xa(t))return t}return ""}formatClaudeUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId(),getAlt:e=>e.alt||e.name||"uploaded image"})}formatClaudeUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),getLabel:e=>e.type&&!this.fileNameEndsWithType(e.name,e.type)?`${e.name} (${e.type})`:e.name})}fileNameEndsWithType(e,t){const n=e.toLowerCase(),r=t.replace(/^\./,"").toLowerCase();return !!r&&n.endsWith(`.${r}`)}async collectClaudeDocumentArtifacts(){const e=[],t=this.getClaudeDocumentArtifactCells();for(let n=0;nt.element===e);if(t)return t;if(!this.isMarkdownDocumentArtifact(e))return null;const n=this.getClaudeDocumentArtifactCells().indexOf(e);if(n>=0){const e=this.exportDocumentCache.find(e=>e.index===n);if(e)return e}const r=this.getClaudeArtifactTitle(e),o=this.exportDocumentCache.filter(e=>e.artifactTitle===r||e.title===r);return 1===o.length?o[0]:1===this.exportDocumentCache.length?this.exportDocumentCache[0]:null}extractClaudeExportMessages(e){const t=[],n=this.getOutlineRoot(),r=Array.from(n.querySelectorAll(this.getUserQuerySelector())),o=Array.from(n.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(Zl)),i=Math.max(r.length,o.length);for(let a=0;a{if(e.matches(Xl))return void i.push(this.formatClaudeArtifactExportContent(e,t));const n=Hi(this.prepareClaudeAssistantMarkdownBlockForExport(e,t)).trim()||e.textContent?.trim()||"";i.push(n);});const a=i.filter(Boolean).join("\n\n").trim();if(r&&o.length>0){const e=o.join("\n\n");return a?`${e}\n\n${a}`:e}return a}getClaudeAssistantExportBlocks(e){return Array.from(e.querySelectorAll(`${Yl}, ${Xl}`)).filter(e=>!e.closest(Zl)&&!this.isInsideClaudeThoughtBlock(e)).filter(t=>{const n=t.parentElement?.closest(`${Yl}, ${Xl}`);return !n||!e.contains(n)})}prepareClaudeAssistantMarkdownBlockForExport(e,t){const n=this.getClaudeArtifactCells(e),r=e.cloneNode(true);return Array.from(r.querySelectorAll(Xl)).forEach((e,r)=>{const o=n[r]||e,i=document.createElement("p");i.textContent=this.formatClaudeArtifactExportContent(o,t),e.replaceWith(i);}),r}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}async expandClaudeThoughtBlocksForExport(){const e=this.getClaudeThoughtToggleButtons(document),t=[];for(const n of e){if("true"===n.getAttribute("aria-expanded"))continue;const e=this.getClaudeThoughtBlockContainer(n);if(!e)continue;await this.openClaudeThoughtBlock(n,e)&&t.push(e);}return t}async openClaudeThoughtBlock(e,t){try{e.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});}catch{e.scrollIntoView({block:"center",inline:"nearest"});}return this.simulateClick(e),!!(await this.waitForClaudeThoughtBlockExpanded(t,900))||(e.isConnected&&"true"!==e.getAttribute("aria-expanded")?(e.click(),this.waitForClaudeThoughtBlockExpanded(t,1800)):this.waitForClaudeThoughtBlockExpanded(t,1800))}async waitForClaudeThoughtBlockExpanded(e,t){const n=Date.now();for(;Date.now()-n{if(!e.isConnected)return;const t=e.querySelector(ec);t instanceof HTMLElement&&"true"===t.getAttribute("aria-expanded")&&this.simulateClick(t);});}getClaudeThoughtToggleButtons(e=document){return Array.from(e.querySelectorAll(ec)).filter(e=>e instanceof HTMLElement&&this.isClaudeThoughtToggleButton(e))}isClaudeThoughtToggleButton(e){if(!e.closest(".font-claude-response"))return false;const t=this.getClaudeThoughtBlockContainer(e);if(!t)return false;const n=t.querySelector(tc)?.textContent?.trim();return Boolean(n)}getClaudeThoughtBlockContainer(e){const t=e.closest(".font-claude-response");let n=null,r=e.parentElement;for(;r&&r!==t&&r!==document.body;){const e=null!==r.querySelector(tc),t=null!==r.querySelector(ec);if(e&&t&&(n=r,this.isClaudeThoughtRootCandidate(r)))return r;r=r.parentElement;}return n}isClaudeThoughtRootCandidate(e){return ("string"==typeof e.className?e.className:"").includes("grid-rows")||null!==e.querySelector(".row-start-2")}isInsideClaudeThoughtBlock(e){return null!==this.getClaudeThoughtBlockContainer(e)}captureClaudeThoughtBlocksForExport(){Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(Zl)).forEach((e,t)=>{const n=this.extractClaudeThoughtBlockquotes(e);n.length>0&&(this.exportThoughtBlocks.set(e,n),this.exportThoughtBlocksByAssistantIndex.set(t,n));});}hasClaudeThoughtExportCache(){return this.exportThoughtBlocksByAssistantIndex.size>0}getClaudeThoughtBlocksForElement(e,t){if(void 0!==t){const e=this.exportThoughtBlocksByAssistantIndex.get(t);if(e)return e}const n=this.exportThoughtBlocks.get(e);if(n)return n;const r=e.closest(".font-claude-response");if(r){const e=this.exportThoughtBlocks.get(r);if(e)return e}const o=this.getClaudeAssistantResponseIndex(e);if(o>=0){const e=this.exportThoughtBlocksByAssistantIndex.get(o);if(e)return e}return this.extractClaudeThoughtBlockquotes(e)}getClaudeAssistantResponseIndex(e){const t=e.matches(".font-claude-response")?e:e.closest(".font-claude-response");return t?Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(Zl)).indexOf(t):-1}extractClaudeThoughtBlockquotes(e){const t=this.getClaudeThoughtToggleButtons(e),n=[],r=new Set;return t.forEach(e=>{const t=this.getClaudeThoughtBlockContainer(e);if(!t||r.has(t))return;r.add(t);const o=this.extractClaudeThoughtMarkdown(t).trim();if(!o)return;const i=t.querySelector(tc)?.textContent?.trim()||"";n.push(this.formatAsThoughtBlockquote(o,i));}),n}extractClaudeThoughtMarkdown(e){const t=e.cloneNode(true);return t.querySelectorAll(`${ec}, ${tc}, svg`).forEach(e=>e.remove()),Hi(t).trim()||this.extractTextWithLineBreaks(t).trim()}formatAsThoughtBlockquote(e,t=""){const n=t.replace(/\s+/g," ").trim();return ["> [Thoughts]",...n?[`> **${n}**`,">"]:[],...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}formatClaudeArtifactExportContent(e,t){const n=this.getClaudeArtifactTitle(e),r=this.findCachedClaudeDocumentForArtifact(e);return r?.content?t?Pa(t,r.content,{title:r.title||n,fallbackTitle:"claude-document",directory:"assets/documents",idPrefix:"claude-document"}):this.formatClaudeDocumentInlineContent(r.content,r.title||n):this.formatClaudeArtifactPlaceholder(e)}formatClaudeDocumentInlineContent(e,t){const n=e.trim();return n?/^#{1,6}\s+/m.test(n)?n:`### ${t}\n\n${n}`:""}formatClaudeArtifactPlaceholder(e,t=""){const n=this.getClaudeArtifactTitle(e),r=this.getClaudeArtifactMetadata(e);return `[Artifact: ${n}${r?` - ${r}`:""}${t?` | Download: ${t}`:""}]`}extractAssistantResponseText(e){return this.extractClaudeAssistantResponseTextWithDocuments(e)}getConversationObserverConfig(){return {selector:'a[data-dd-action-name="sidebar-chat-item"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"";if(!r)return null;const o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"";let a=false;const s=e.closest("div.flex.flex-col");if(s){const e=s.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=s.querySelector("ul"),r=n?.classList.contains("-mx-1.5");a=t||r;}return {id:r,title:i,url:`https://claude.ai${t}`,isActive:window.location.href.includes(r),isPinned:a}},getTitleElement:e=>e.querySelector("span.truncate")}}navigateToConversation(e,t){const n=t||`https://claude.ai/chat/${e}`,r=document.querySelector(`a[href*="${e}"]`);return r?(r.click(),true):(window.location.href=n,true)}getSessionName(){return this.getConversationTitle()}getWidthSelectors(){return [{selector:"#main-content .max-w-3xl",property:"max-width"},{selector:"#main-content .max-w-4xl",property:"max-width"}]}getZenModeConfig(){return {hide:['nav:has(a[data-dd-action-name="sidebar-chat-item"])']}}getCleanModeConfig(){return {hide:['[data-disclaimer="true"]']}}getUserQueryWidthSelectors(){return [{selector:'[data-testid="user-message"]',property:"max-width"}]}async toggleTheme(e){try{const t=localStorage.getItem("LSS-userThemeMode"),n="system"===e?window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":e,r={value:"system"===e?"auto":e,tabId:nc(),timestamp:Date.now()},o=JSON.stringify(r);return localStorage.setItem("LSS-userThemeMode",o),function(e){const t=document.documentElement,n=document.body;t.classList.toggle("dark","dark"===e),t.classList.remove("light"),t.style.colorScheme=e,n&&(n.classList.remove("dark","light"),n.removeAttribute("data-theme"),n.style.removeProperty("color-scheme"));}(n),window.dispatchEvent(new StorageEvent("storage",{key:"LSS-userThemeMode",oldValue:t,newValue:o,storageArea:localStorage})),await new Promise(e=>setTimeout(e,300)),!0}catch(RS){return console.error("[ClaudeAdapter] toggleTheme error:",RS),false}}},new class extends vs{nativeOutlineCache=null;nativeOutlineRevealRequestId=0;exportSnapshotRoot=null;exportSnapshotActive=false;exportIncludeThoughtsOverride=null;exportBundleCache=null;match(){const e="chat.deepseek.com"===window.location.hostname;return e&&this.consumePendingDeleteRefresh(),e}getSiteId(){return xo}getName(){return "DeepSeek"}getThemeColors(){return {primary:"#4b6bfe",secondary:"#3a5ae0"}}getNativeThemeCss(){return "\n/* =============================================\n * DeepSeek 站点原生主题适配器 (DeepSeek Theme Adapter)\n * ============================================= */\nbody, page, .ds-theme {\n /* 核心页面背景层 - 覆盖基础背景 */\n // --dsw-alias-bg-base: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n --dsr-side-hover-bg: var(--gh-hover) !important;\n\n --dsw-alias-markdown-inline-code: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block-banner: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block: var(--gh-bg-secondary) !important;\n}\n\n/* 侧边栏背景 */\n.b8812f16, .f3d18f6a {\n background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n}\n"}getTextareaSelectors(){return ['textarea[placeholder*="DeepSeek"]','textarea[placeholder*="deepseek"]',"textarea.ds-scroll-area","form textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=window.location.pathname,t=e.match(oc);if(t?.[1])return t[1];const n=e.match(ic);return n?.[1]||""}isNewConversation(){const e=window.location.pathname;return !this.isSharePage()&&("/"===e||"/a/chat"===e||"/a/chat/"===e||!oc.test(e))}isSharePage(){return window.location.pathname.startsWith("/share/")}getNewTabUrl(){return "https://chat.deepseek.com/"}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";return t&&"DeepSeek"!==t&&t.replace(/\s*[-|]\s*DeepSeek$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:sc,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>this.findTitleElement(e)}}async deleteConversationOnSite(e){const t=this.getSessionId(),n=this.getUserToken();if(!n)return {id:e.id,success:false,method:"api",reason:Cc};const r=await this.deleteConversationViaApi(e,n);return r.success&&(e.id===t?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getSessionId(),n=this.getUserToken();if(!n)return e.map(e=>({id:e.id,success:false,method:"api",reason:Cc}));const r=[];let o=false,i=false;for(const a of e){const e=await this.deleteConversationViaApi(a,n);r.push(e),e.success&&(i=true,a.id===t&&(o=true));}return i&&(o?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}getConversationTitle(){if(this.isSharePage())return this.getShareConversationTitle();const e=this.getSessionId(),t=(e?document.querySelector(`${sc}[href*="/a/chat/s/${e}"]`):null)||document.querySelector(`${sc}[aria-current="page"]`);return t?this.extractConversationTitle(t):null}navigateToConversation(e,t){const n=document.querySelector(`${sc}[href*="/a/chat/s/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t||`https://chat.deepseek.com/a/chat/s/${e}`)}getSidebarScrollContainer(){const e=document.querySelector(sc);return e?.closest(".ds-scroll-area")||null}getZenModeConfig(){return {hide:[".dc04ec1d","._0fcaa63"]}}getCleanModeConfig(){return {hide:["._0fcaa63"]}}getScrollContainer(){const e=Array.from(document.querySelectorAll(lc)).filter(e=>!e.parentElement?.closest(lc)),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll(`${cc}, ${dc}`)).filter(e=>!e.closest(".gh-root, .gh-table-container"));return this.pickBestScrollableAncestor(n)}getResponseContainerSelector(){return 'main .ds-scroll-area:has(.ds-message), [role="main"] .ds-scroll-area:has(.ds-message), .ds-scroll-area:has(.ds-message)'}getUserQuerySelector(){return dc}findUserQueryElement(e,t){const n=this.getVisibleUserQueryElements();if(0===n.length)return null;if(e>0&&n.length>=e){const r=n[e-1];if(this.isEquivalentUserQueryText(this.extractUserQueryText(r),t))return r}return n.find(e=>this.isEquivalentUserQueryText(this.extractUserQueryText(e),t))||null}getChatContentSelectors(){return [cc,dc]}scrollToOutlineTarget(e){this.nativeOutlineRevealRequestId+=1,super.scrollToOutlineTarget(e);}extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.findUserContentRoot(e);if(!t)return this.resolveUserMessageElement(e)?"":this.extractTextWithLineBreaks(e).trim();const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, .ds-icon-button, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractDeepSeekUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-user-query-markdown-deepseek gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}extractAssistantResponseText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.shouldIncludeThoughtsInExport(),n=this.resolveAssistantMessageElement(e),r=this.resolveAssistantBodyMarkdownElement(e),o=t&&n?this.extractThoughtBlockquotesFromMessage(n):[],i=r?this.extractMarkdownText(r):"";return t&&o.length>0?i?`${o.join("\n\n")}\n\n${i}`:o.join("\n\n"):i}extractOutline(e=6,t=false,n=false){const r=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!r)return [];const o=[],i=[],a=Array.from(r.querySelectorAll(lc)).filter(e=>!e.parentElement?.closest(lc));if(a.forEach((r,s)=>{const l=this.getAssistantBodyMarkdown(r);if(!l){if(!t)return;const e=this.extractUserQueryMarkdown(r);if(!e)return;let l;n&&(l=this.findNextAssistantMarkdown(a,s)?.textContent?.trim().length||0);const c=this.createUserQueryOutlineItem(e,r,l);return i.push(c),void o.push(c)}const c=Array.from(l.querySelectorAll("h1, h2, h3, h4, h5, h6"));c.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let s;if(n){let e=null;for(let t=r+1;t80;return {level:0,text:o?`${r.slice(0,80)}...`:r,element:t,isUserQuery:true,isTruncated:o,wordCount:n}}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:vc,assistantResponseSelector:xc,turnSelector:null,useShadowDOM:false}:{userQuerySelector:dc,assistantResponseSelector:cc,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportBundleCache=null,this.clearExportSnapshot();const t="markdown"===e.format&&"zip"===e.packaging?la():void 0,n=await this.collectShareExportMessageSnapshots(t);if(n?.length)return t&&(this.exportBundleCache={messages:n,assets:t.assets}),this.mountExportSnapshot(n),{count:n.length};const r=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!(r instanceof HTMLElement))return null;const o=await this.collectExportMessageSnapshots(r,t);return 0===o.length?null:(t&&(this.exportBundleCache={messages:o,assets:t.assets}),this.mountExportSnapshot(o),{count:o.length})}async extractExportBundle(e){return this.exportBundleCache}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundleCache=null;}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=t.scrollTop,n=Math.max(0,t.scrollHeight-t.clientHeight);try{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}finally{t.scrollTop=e,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getLastCodeBlockText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=this.buildBottomUpScanPositions(t),n=t.scrollTop;try{for(const n of e){t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}}finally{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getSubmitButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d="${Sc}"])`,`button.ds-icon-button:has(svg path[d="${Sc}"])`]}findSubmitButton(e){const t=this.getSubmitButtonSelectors().join(", ");if(!t)return null;const n=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),r=new Set;for(const o of n){const e=o.querySelectorAll(t);for(const t of Array.from(e)){const e=t;if(!r.has(e)&&null!==e.offsetParent)return r.add(e),e}}return null}getNewChatButtonSelectors(){return ['a[href="/a/chat"]','a[href="/a/chat/"]']}getWidthSelectors(){return [{selector:":root",property:"--message-list-max-width",noCenter:true},{selector:".ds-virtual-list-items, .ds-virtual-list-visible-items",property:"--message-list-max-width",noCenter:true}]}getUserQueryWidthSelectors(){const e=["max-width: 100% !important;","min-width: 0 !important;","box-sizing: border-box !important;","margin-left: auto !important;","margin-right: 0 !important;","overflow-wrap: anywhere !important;","word-break: break-word !important;"].join(" ");return [{selector:hc,property:"width",extraCss:e,noCenter:true}]}isGenerating(){const e=this.findComposerButtons();for(const t of e){const e=t.querySelector("svg path");if((e?.getAttribute("d")||"").startsWith(wc))return true}return false}getStopButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d^="${wc}"])`,`button.ds-icon-button:has(svg path[d^="${wc}"])`]}getModelName(){const e=Array.from(document.querySelectorAll(".ds-toggle-button--selected")).map(e=>e.innerText?.trim()||e.textContent?.trim()||"").filter(Boolean);return 0===e.length?"DeepSeek":`DeepSeek (${e.join(", ")})`}getNetworkMonitorConfig(){return {urlPatterns:["/api/v0/chat/completion"],silenceThreshold:500}}async toggleTheme(e){try{const t="system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e,n=JSON.stringify({value:e,__version:"0"});localStorage.setItem(ac,n);const r=document.body;return r&&(r.classList.remove("light","dark"),r.classList.add("change-theme",t),"dark"===t?r.setAttribute("data-ds-dark-theme","dark"):r.removeAttribute("data-ds-dark-theme"),r.style.colorScheme=t,window.setTimeout(()=>{document.body===r&&r.classList.remove("change-theme");},300)),window.dispatchEvent(new StorageEvent("storage",{key:ac,newValue:n,storageArea:localStorage})),!0}catch(RS){return console.error("[DeepSeekAdapter] toggleTheme error:",RS),false}}findComposerButtons(){const e=this.getTextareaElement(),t=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),n=new Set,r=[];for(const o of t){const e=o.querySelectorAll('div[role="button"].ds-icon-button, button.ds-icon-button, .ds-icon-button[aria-disabled="false"]');for(const t of Array.from(e)){const e=t;null===e.offsetParent||n.has(e)||(n.add(e),r.push(e));}if(r.length>0)return r}return r}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(lc).length,i=e.querySelectorAll(dc).length,a=e.querySelectorAll(cc).length;let s=0;return s+=200*Math.min(o,80),s+=120*Math.min(i,40),s+=120*Math.min(a,40),e.scrollTop>0&&(s+=800),r.height>=.35*t&&(s+=500),r.width>=.45*n&&(s+=350),(e.matches("main, [role='main']")||e.closest("main, [role='main']"))&&(s+=250),e.querySelector("textarea")&&(s-=700),e.querySelector(".gh-table-container")&&(s-=250),s}extractNativeUserQueries(e){const t=this.collectNativeOutlineEntries();if(0===t.length)return [];const n=[],r=new Map;let o=0;return t.forEach(t=>{const i=this.findMatchingUserQueryIndex(e,t.text,o),a=i>=0?e[i]:null;i>=0&&(o=i+1);const s=this.createUserQueryOutlineItem(t.text,a?.element||null);s.wordCount=a?.wordCount;const l=this.normalizeUserQueryMatchText(t.text),c=r.get(l)||0;r.set(l,c+1),s.id=a?.id||`deepseek-user-query::${c}::${this.normalizeUserQueryMatchText(t.text)}`,n.push(s);}),n}mergeOutlineWithNativeUserQueries(e,t){if(!e.some(e=>e.isUserQuery))return [...t,...e];const n=[],r=[];let o=null,i=0;e.forEach(e=>{if(!e.isUserQuery)return void(o?o.assistantItems.push(e):n.push(e));const a=this.findMatchingNativeUserQueryIndex(t,e,i);a>=0?(o={type:"matched",nativeIndex:a,assistantItems:[]},i=a+1):o={type:"unmatched",userItem:e,assistantItems:[]},r.push(o);});const a=r.find(e=>"matched"===e.type);if(!a)return [...t,...e];const s=[];let l=0;if(n.length>0){const e=Math.max(a.nativeIndex-1,0);for(;l<=e&&l{if("matched"!==e.type)s.push(e.userItem,...e.assistantItems);else {for(;l<=e.nativeIndex&&l({...e})):[];const n=this.findNativeOutlineScrollContainer(t),r=this.getNativeOutlineSnapshot(e,t,n);if(this.nativeOutlineCache&&this.nativeOutlineCache.sessionId===e&&this.nativeOutlineCache.snapshot===r)return this.nativeOutlineCache.items.map(e=>({...e}));const o=this.scanNativeOutlineEntries(t,n);return o.length>0&&(this.nativeOutlineCache={sessionId:e,snapshot:r,items:o.map(e=>({...e}))}),o}findNativeOutlineList(){const e=Array.from(document.querySelectorAll(".ds-virtual-list")).filter(e=>e instanceof HTMLElement&&e.querySelector(".ds-virtual-list-items, .ds-virtual-list-visible-items")&&!e.querySelector(sc)&&!e.closest("aside, nav"));let t=null,n=-1;return e.forEach(e=>{const r=e.getBoundingClientRect();let o=0;e.closest('[style*="--scroll-nav-page-padding"]')&&(o+=2500),e.closest("main, [role='main']")&&(o+=600),e.querySelector(".ds-virtual-list-visible-items")&&(o+=400),r.width>=140&&r.width<=420&&(o+=350),r.height>=120&&(o+=250),e.scrollHeight>e.clientHeight+20&&(o+=300),e.querySelector(lc)&&(o-=1500),o>n&&(t=e,n=o);}),n>0?t:null}findNativeOutlineScrollContainer(e){const t=[e,e.closest(".ds-scroll-area"),e.parentElement,e.closest('[style*="--scroll-nav-page-padding"]')?.querySelector(".ds-scroll-area")].filter(e=>e instanceof HTMLElement);let n=null,r=-1;return t.forEach(t=>{const o=window.getComputedStyle(t);if(!(t.scrollHeight>t.clientHeight+8||"auto"===o.overflowY||"scroll"===o.overflowY||t.classList.contains("ds-virtual-list")||t.classList.contains("ds-scroll-area"))||t.clientHeight<=0)return;let i=0;t===e&&(i+=500),t.classList.contains("ds-virtual-list")&&(i+=350),t.classList.contains("ds-scroll-area")&&(i+=250),i+=Math.min(t.scrollHeight-t.clientHeight,2e3),i>r&&(n=t,r=i);}),r>0?n:null}getNativeOutlineSnapshot(e,t,n){const r=t.querySelector(".ds-virtual-list-items"),o=t.querySelector(".ds-virtual-list-visible-items"),i=n||t;return [e,i.scrollHeight,i.clientHeight,r?.scrollHeight||0,o?.childElementCount||0].join("::")}scanNativeOutlineEntries(e,t){const n=this.readVisibleNativeOutlineEntries(e);if(!t)return n;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(r<=0)return n;const o=t.scrollTop,i=Math.max(48,Math.floor(.6*t.clientHeight)),a=new Set([0,r,o]);for(let l=0;le-t).forEach(n=>{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),e.getBoundingClientRect();const r=this.readVisibleNativeOutlineEntries(e);s=this.mergeNativeOutlineEntryBatch(s,r,n);});}finally{t.scrollTop=o,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return s}readVisibleNativeOutlineEntries(e){const t=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!t)return [];const n=[];return Array.from(t.children).forEach((e,t)=>{if(!(e instanceof HTMLElement))return;const r=this.extractNativeOutlineText(e);r&&n.push({text:r,batchIndex:t});}),n}extractNativeOutlineText(e){const t=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(const n of t){const e=this.normalizeOutlineText(n.innerText||n.textContent||"");if(e)return e}return this.normalizeOutlineText(e.innerText||e.textContent||"")}mergeNativeOutlineEntryBatch(e,t,n){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e,scrollTop:e.scrollTop??n}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const o=e.slice(-r),i=t.slice(0,r);if(this.nativeOutlineEntrySequenceEquals(o,i))return [...e,...t.slice(r).map(e=>({...e,scrollTop:e.scrollTop??n}))]}return [...e,...t.map(e=>({...e,scrollTop:e.scrollTop??n}))]}nativeOutlineEntrySequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.nativeOutlineEntryEquals(e,t[n]))}nativeOutlineEntryEquals(e,t){return this.normalizeUserQueryMatchText(e.text)===this.normalizeUserQueryMatchText(t.text)}findMatchingUserQueryIndex(e,t,n){for(let r=n;r0&&t<=e.length?e[t-1]:e.find(e=>this.isEquivalentUserQueryText(e.text,n))||null}buildNativeOutlineJumpPositions(e,t,n,r,o){const i=Math.max(0,r.scrollHeight-r.clientHeight),a=e.length>1?Math.round(i*Math.max(n-1,0)/Math.max(e.length-1,1)):0,s=e.filter(e=>this.isEquivalentUserQueryText(e.text,o)).map(e=>e.scrollTop).filter(e=>"number"==typeof e),l=[t.scrollTop,a,a-.5*r.clientHeight,a+.5*r.clientHeight,...s,0,i],c=new Set;return l.map(e=>Math.max(0,Math.min(i,Math.round(e||0)))).filter(e=>!c.has(e)&&(c.add(e),true))}findVisibleNativeOutlineItem(e,t,n){const r=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!r)return null;const o=Array.from(r.children).filter(e=>e instanceof HTMLElement);if("number"==typeof t.batchIndex&&t.batchIndex>=0&&t.batchIndexthis.isEquivalentUserQueryText(this.extractNativeOutlineText(e),n))||null}dispatchNativeOutlineClick(e){const t=e.querySelector('button, [role="button"], a')||e;t.dispatchEvent(new MouseEvent("mousedown",{bubbles:true,cancelable:true})),t.dispatchEvent(new MouseEvent("mouseup",{bubbles:true,cancelable:true})),t.click();}async waitForUserQueryElement(e,t,n){const r=Date.now();for(;Date.now()-r<3200;){if(n!==this.nativeOutlineRevealRequestId)return null;const r=this.findUserQueryElement(e,t);if(r)return r;await this.sleep(80);}return n!==this.nativeOutlineRevealRequestId?null:this.findUserQueryElement(e,t)}getVisibleUserQueryElements(){return Array.from(document.querySelectorAll(dc)).filter(e=>e instanceof HTMLElement&&!e.parentElement?.closest(lc))}sleep(e){return new Promise(t=>window.setTimeout(t,e))}isExportSnapshotElement(e){return e.hasAttribute(fc)}async collectShareExportMessageSnapshots(e){if(!this.isSharePage())return null;const t=this.getSessionId();if(!t)return null;try{const n=await fetch(`/api/v0/share/content?share_id=${encodeURIComponent(t)}`,{credentials:"include"});if(!n.ok)return null;const r=await n.json(),o=this.extractShareExportMessagesFromPayload(r,e);return o.length>0?o:null}catch(RS){return console.warn("[DeepSeekAdapter] Failed to collect share export payload:",RS),null}}extractShareExportMessagesFromPayload(e,t){const n=this.getNestedRecord(e,["data","biz_data"]),r=n?.messages;if(!Array.isArray(r))return [];const o=[];return r.forEach(e=>{const n=this.toRecord(e);if(!n)return;const r="string"==typeof n.role?n.role.toUpperCase():"",i=Array.isArray(n.fragments)?n.fragments:[];if("USER"===r){const e=[],n=[];i.forEach(t=>{const r=this.toRecord(t);if(!r)return;const o="string"==typeof r.type?r.type.toUpperCase():"";"FILE"!==o?"REQUEST"===o&&"string"==typeof r.content&&n.push(r.content):e.push(...this.extractShareUserAttachments(r));});const r=this.normalizeExportMessageContent(this.formatUserQueryExportContent(n.join("\n\n"),e,t));return void(r&&o.push({role:bc,content:r}))}if("ASSISTANT"===r){const e=[],t=[];i.forEach(n=>{const r=this.toRecord(n);if(!r||"string"!=typeof r.content)return;const o="string"==typeof r.type?r.type.toUpperCase():"";"THINK"===o?t.push(r.content):"RESPONSE"===o&&e.push(r.content);});const n=this.shouldIncludeThoughtsInExport()?t.map(e=>e.trim()).filter(Boolean).map(e=>this.formatAsThoughtBlockquote(e)):[],r=this.normalizeExportMessageContent([...n,...e.map(e=>e.trim()).filter(Boolean)].filter(Boolean).join("\n\n"));r&&o.push({role:yc,content:r});}}),o}extractShareUserAttachments(e){return (Array.isArray(e.files)?e.files:[]).flatMap(e=>{const t=this.toRecord(e);if(!t)return [];const n="string"==typeof t.file_name?t.file_name.trim():"";if(!n)return [];const r="string"==typeof t.signed_path?t.signed_path.trim():"",o="number"==typeof t.file_size?this.formatFileSize(t.file_size):"";return [{kind:true===t.is_image?"image":"file",name:n,type:this.extractFileTypeFromName(n),size:o,source:r?va(r):""}]})}getNestedRecord(e,t){let n=this.toRecord(e);for(const r of t){if(!n)return null;n=this.toRecord(n[r]);}return n}toRecord(e){return e&&"object"==typeof e?e:null}extractDeepSeekUserQueryExportContent(e,t){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const n=this.extractDomUserAttachments(e),r=this.extractUserQueryText(e);return this.formatUserQueryExportContent(r,n,t)}resolveUserMessageElement(e){if(e.matches(dc))return e;const t=e.closest(dc);return t instanceof HTMLElement?t:null}extractDomUserAttachments(e){const t=this.resolveUserMessageElement(e);if(!t)return [];const n=[],r=new Set;return this.extractDomUserImageAttachments(t).forEach(e=>{const t=`image:${e.source||e.name}`;r.has(t)||(r.add(t),n.push(e));}),this.extractDomUserFileAttachments(t).forEach(e=>{const t=`file:${e.source||e.name}:${e.type}:${e.size}`;r.has(t)||(r.add(t),n.push(e));}),n}extractDomUserImageAttachments(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&!e.closest(".gh-user-query-markdown")).flatMap(e=>{const t=this.getDeepSeekImageExportSource(e);if(!t)return [];const n=this.extractImageAttachmentName(e,t);return [{kind:"image",name:n,type:this.extractFileTypeFromName(n)||"image",size:"",source:t}]})}extractDomUserFileAttachments(e){return Array.from(e.querySelectorAll("div")).filter(t=>this.isLikelyUserFileAttachmentCard(t,e)).flatMap(e=>{const t=this.extractAttachmentCardName(e);if(!t)return [];const n=this.extractAttachmentCardSource(e),r=this.extractAttachmentCardType(e,t)||this.extractFileTypeFromName(t);return [{kind:this.isImageAttachmentName(t,r)?"image":"file",name:t,type:r,size:this.extractAttachmentCardSize(e),source:n}]})}formatUserQueryExportContent(e,t,n){const r=this.stripUserAttachmentBodyText(e,t);if(0===t.length)return r;const o=this.formatUserImageAttachments(t,n),i=this.formatUserFileAttachments(t,n),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,r].filter(Boolean).join("\n\n")}formatUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"image"!==e.kind||!e.source,getLabel:e=>this.formatAttachmentLabel(e)})}formatAttachmentLabel(e){const t=this.formatAttachmentDetails(e);return t?`${e.name} (${t})`:e.name}formatAttachmentDetails(e){return [e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?e.type:"",e.size].filter(Boolean).join(", ")}getDeepSeekImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=va(n);if(e&&(!e.startsWith("data:image/svg+xml")&&xa(e)))return e}return ""}extractImageAttachmentName(e,t){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractFilenameFromUrl(t),"uploaded image"].map(e=>this.normalizeAttachmentText(e)).find(Boolean)||"image"}isLikelyUserFileAttachmentCard(e,t){if(e===t)return false;if(e.closest(".gh-user-query-markdown"))return false;if(!this.isWithinUserAttachmentContainer(e,t))return false;if(!e.querySelector("svg")||e.querySelector("img"))return false;const n=this.extractAttachmentCardName(e);if(!n)return false;return this.normalizeAttachmentText(e.textContent||"")!==n}isWithinUserAttachmentContainer(e,t){let n=e;for(;n&&n!==t;){if(n.parentElement===t)return this.isLikelyUserAttachmentContainer(n);n=n.parentElement;}return false}isLikelyUserAttachmentContainer(e){if(e.matches(".gh-inline-bookmark, .gh-user-query-raw, .gh-user-query-markdown"))return false;if(e.matches("button, [role=button], .ds-icon-button, .ds-focus-ring"))return false;if(e.querySelector("img"))return true;return !!this.normalizeAttachmentText(e.textContent||"")&&(!!e.querySelector("svg")&&""!==this.extractAttachmentCardName(e))}stripUserAttachmentBodyText(e,t){return e&&0!==t.length?e.replace(/\r\n/g,"\n").split("\n").filter(e=>!this.isUserAttachmentBodyLine(e,t)).join("\n").trim():e}isUserAttachmentBodyLine(e,t){const n=this.normalizeAttachmentComparisonText(e);return !!n&&t.some(e=>{const t=this.normalizeAttachmentComparisonText(e.name);if(!t||!n.includes(t))return false;const r=this.normalizeAttachmentComparisonText(e.size);if(r&&n.includes(r))return true;const o=e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?this.normalizeAttachmentComparisonText(e.type):"";return !(!o||!n.includes(o))||n===t})}extractAttachmentCardName(e){const t=Array.from(e.querySelectorAll("div, span, p")).filter(e=>!e.querySelector("svg, img")),n=[...t.filter(e=>0===e.children.length).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean),...t.map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean)].find(e=>this.looksLikeFilename(e));if(n)return n;const r=this.normalizeAttachmentText(e.getAttribute("aria-label")||"");if(this.looksLikeFilename(r))return r;const o=this.normalizeAttachmentText(e.getAttribute("title")||"");return this.looksLikeFilename(o)?o:""}extractAttachmentCardType(e,t=""){const n=this.normalizeAttachmentText(t).toLowerCase(),r=Array.from(e.querySelectorAll("div, span, p")).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean).find(e=>(!n||!e.toLowerCase().includes(n))&&!this.looksLikeFilename(e)&&/^[A-Za-z0-9.+-]{1,12}(?:\s+\d+(?:\.\d+)?\s*[KMGT]?B)?$/i.test(e));return r?.match(/^[A-Za-z0-9.+-]{1,12}/)?.[0]?.toUpperCase()||""}extractAttachmentCardSize(e){const t=this.normalizeAttachmentText(e.textContent||"");return t.match(/\b\d+(?:\.\d+)?\s*[KMGT]?B\b/i)?.[0]||""}extractAttachmentCardSource(e){const t=Array.from(e.querySelectorAll("a[href]")),n=e.closest("a[href]");n&&t.unshift(n);for(const r of t){if(!(r instanceof HTMLAnchorElement))continue;const e=va(r.getAttribute("href")||r.href||"");if(xa(e))return e}return ""}looksLikeFilename(e){const t=this.normalizeAttachmentText(e);return !this.isFileMetaText(t)&&/[^/\\]+\.[A-Za-z0-9]{1,10}$/.test(t)}isFileMetaText(e){return /^[A-Za-z0-9.+-]{1,12}\s+\d+(?:\.\d+)?\s*[KMGT]?B$/i.test(e)}isImageAttachmentName(e,t){const n=(this.extractFileTypeFromName(e)||t).toLowerCase();return ["avif","gif","jpg","jpeg","png","svg","webp"].includes(n)}extractFileTypeFromName(e){return e.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toUpperCase()||""}formatFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?0:2;return `${n.toFixed(o)}${t[r]}`}extractFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename")||t.searchParams.get("file_name");if(n?.trim())return n.trim();const r=decodeURIComponent(t.pathname);return r.split("/").pop()?.trim()||""}catch{return ""}}normalizeAttachmentText(e){return e.replace(/\s+/g," ").trim()}normalizeAttachmentComparisonText(e){return this.normalizeAttachmentText(e).toLowerCase().replace(/[(]/g,"(").replace(/[)]/g,")").replace(/\s+/g,"")}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}async collectExportMessageSnapshots(e,t){const n=this.buildExportSnapshotPositions(e),r=e.scrollTop;let o=[];try{for(const r of n){e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const n=this.readVisibleExportMessageSnapshots(e,t);o=this.mergeExportMessageBatch(o,n);}}finally{e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return o}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}buildBottomUpScanPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight);if(t<=0)return [e.scrollTop];const n=Math.max(160,Math.floor(.9*e.clientHeight)),r=[];for(let o=t;o>0;o-=n)r.push(o);return 0!==r[r.length-1]&&r.push(0),r}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}resolveAssistantMessageElement(e){if(e.matches(lc))return e;const t=e.closest(lc);return t instanceof HTMLElement?t:null}resolveAssistantBodyMarkdownElement(e){if(e.matches(".ds-markdown")&&!this.isThoughtMarkdownElement(e))return e;const t=this.resolveAssistantMessageElement(e);return t?this.getAssistantBodyMarkdown(t):null}getAssistantBodyMarkdown(e){const t=Array.from(e.querySelectorAll(".ds-markdown")).filter(e=>e instanceof HTMLElement&&!this.isThoughtMarkdownElement(e));return t.length>0?t[t.length-1]:null}isThoughtMarkdownElement(e){return null!==e.closest(uc)}extractThoughtBlockquotesFromMessage(e){const t=Array.from(e.querySelectorAll(`${uc} .ds-markdown`)).filter(e=>e instanceof HTMLElement),n=[];return t.forEach(e=>{const t=this.extractMarkdownText(e);t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractMarkdownText(e){const t=e.cloneNode(true);t.querySelectorAll('button, [role="button"], svg, .ds-icon-button, .ds-focus-ring, [aria-hidden="true"]').forEach(e=>e.remove());const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getVisibleAssistantMessages(e){return Array.from(e.querySelectorAll(cc)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${mc}]`)&&!e.closest(".gh-root")&&!e.parentElement?.closest(lc))}extractLatestReplyTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=this.extractAssistantResponseText(e[t]).trim();if(n)return n}return null}extractLastCodeBlockTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=this.getAssistantBodyMarkdown(n);if(!r)continue;const o=this.extractAssistantResponseText(n),i=this.extractLastFencedCodeBlock(o);if(i)return i;const a=this.extractLastCodeBlockTextFromDom(r);if(a)return a}return null}extractLastFencedCodeBlock(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDom(e){const t=Array.from(e.querySelectorAll("pre code, pre"));for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, .ds-icon-button, [aria-hidden="true"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}readVisibleExportMessageSnapshots(e,t){return Array.from(e.querySelectorAll(lc)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${mc}]`)&&!e.parentElement?.closest(lc)).map(e=>this.extractExportMessageSnapshot(e,t)).filter(e=>null!==e)}extractExportMessageSnapshot(e,t){if(this.getAssistantBodyMarkdown(e)){const t=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));return t?{role:yc,content:t}:null}const n=this.normalizeExportMessageContent(this.extractDeepSeekUserQueryExportContent(e,t));return n?{role:bc,content:n}:null}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const n=e.slice(-r),o=t.slice(0,r);if(this.exportMessageSequenceEquals(n,o))return [...e,...t.slice(r).map(e=>({...e}))]}const n=e.map(e=>({...e}));return t.forEach(e=>{this.exportMessageEntryEquals(n[n.length-1],e)||n.push({...e});}),n}exportMessageSequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.exportMessageEntryEquals(e,t[n]))}exportMessageEntryEquals(e,t){return !(!e||!t)&&(e.role===t.role&&e.content===t.content)}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(mc,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(fc,e.role),n.textContent=e.content,t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${mc}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}async deleteConversationViaApi(e,t){try{const n=await fetch("/api/v0/chat_session/delete",{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_session_id:e.id}),credentials:"include"});if(!n.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)};const r=await this.safeParseJson(n);return this.isDeleteSuccessPayload(r)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(r)}}catch{return {id:e.id,success:false,method:"api",reason:kc}}}buildDeleteHeaders(e){return {accept:"*/*",authorization:`Bearer ${e}`,"content-type":"application/json","x-client-platform":"web","x-client-locale":this.getClientLocale(),"x-client-timezone-offset":String(60*-(new Date).getTimezoneOffset())}}getUserToken(){const e=localStorage.getItem("userToken");if(!e)return null;try{const t=JSON.parse(e).value;if("string"==typeof t&&t.trim())return t.trim()}catch{}return e.trim().replace(/^"|"$/g,"")||null}getClientLocale(){return (document.documentElement.lang||navigator.language||"en-US").replace(/-/g,"_")}isDeleteSuccessPayload(e){if(!e||"object"!=typeof e)return false;const t=e;if(0!==t.code)return false;const n=t.data;if(!n||"object"!=typeof n)return true;const r=n.biz_code;return void 0===r||0===r}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return Tc;const t=e;if("string"==typeof t.msg&&t.msg.trim())return `${Ec}:${t.msg.trim()}`;const n=t.data;if(n&&"object"==typeof n){const e=n;if("string"==typeof e.biz_msg&&e.biz_msg.trim())return `${Ec}:${e.biz_msg.trim()}`}return Ec}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleHomeRefreshAfterDelete(){try{sessionStorage.setItem(pc,"1");}catch{}window.location.replace(gc);}schedulePageReloadAfterDelete(){window.setTimeout(()=>{window.location.reload();},0);}consumePendingDeleteRefresh(){let e=false;try{if(e="1"===sessionStorage.getItem(pc),!e)return;sessionStorage.removeItem(pc);}catch{return}if("/"===window.location.pathname||""===window.location.pathname)setTimeout(()=>{window.location.reload();},0);else {try{sessionStorage.setItem(pc,"1");}catch{}window.location.replace(gc);}}findNextAssistantMarkdown(e,t){for(let n=t+1;n!e.parentElement?.closest(lc)),t=e?this.extractUserQueryText(e):"",n=this.normalizeOutlineText(t);if(n)return n.length>80?`${n.slice(0,80)}...`:n;const r=document.querySelector('meta[property="og:title"], meta[name="twitter:title"]')?.getAttribute("content")?.replace(/\s*[-|]\s*DeepSeek$/i,"")?.trim();return r&&"来自分享的对话"!==r?r:r||"DeepSeek Share"}isPinnedConversationLink(e){const t=this.findConversationGroup(e);if(!t)return false;const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(0===r.length)return false;const o=r[0],i=n.indexOf(o);if(i<=0)return false;const a=n.find((e,t)=>t0,l=null!==a.querySelector(":scope > .ds-focus-ring, .ds-focus-ring"),c=null!==a.querySelector(":scope > span, span");return s&&l&&c}findConversationGroup(e){let t=e.parentElement;for(;t&&t!==document.body;){const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(r.length>0){const o=n.indexOf(r[0]);if(n.some((e,t)=>tt===e))return t}t=t.parentElement;}return null}isConversationLink(e){return e.matches(sc)}extractConversationTitle(e){const t=e.getAttribute("aria-label")?.trim();if(t)return t;const n=this.findTitleElement(e),r=n?.innerText?.trim()||n?.textContent?.trim()||"";if(r)return r.replace(/\s+/g," ").trim();return (e.innerText?.trim()||e.textContent?.trim()||"").replace(/\s+/g," ").trim()}findTitleElement(e){const t=Array.from(e.children).find(e=>e instanceof HTMLElement&&(!e.classList.contains("ds-focus-ring")&&(!e.querySelector('[role="button"], .ds-icon-button')&&!!e.innerText?.trim())));if(t)return t;const n=e.querySelectorAll("span, p, div");for(const r of Array.from(n)){if(r.innerText?.trim()||r.textContent?.trim()||"")return r}return e}findUserContentRoot(e){const t=this.resolveUserMessageElement(e);if(!t)return null;return Array.from(t.children).filter(e=>e instanceof HTMLElement&&(!this.isLikelyUserMessageDecoration(e)&&(!this.isLikelyUserAttachmentContainer(e)&&Boolean(e.innerText?.trim()))))[0]||null}isLikelyUserMessageDecoration(e){return e.matches(".gh-inline-bookmark, .gh-user-query-raw, .gh-user-query-markdown, button, [role=button], .ds-icon-button, .ds-focus-ring")}},new class extends vs{outlineCacheSessionKey="";outlineCacheTransitionEndAt=0;outlineItemCache=new Map;match(){return "www.doubao.com"===window.location.hostname}getSiteId(){return yo}getName(){return "豆包"}getThemeColors(){return {primary:"#315efb",secondary:"#0f6eff"}}supportsHostThemeSync(){return false}getTextareaSelectors(){return ['[data-slate-editor="true"]','textarea[data-testid="chat_input_input"]',"textarea.semi-input-textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length);}else if(t.isContentEditable){const n=window.getSelection();if(n){t.focus(),n.selectAllChildren(t),n.collapseToEnd();const e=t.querySelector('[data-slate-node="element"]');if(e&&n.rangeCount>0){const t=document.createRange();t.selectNodeContents(e),t.collapse(false),n.removeAllRanges(),n.addRange(t);}}const r=new DataTransfer;r.setData("text/plain",e),t.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:true,cancelable:true,composed:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected)if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true}));}else e.isContentEditable&&(e.focus(),document.execCommand("selectAll",false),e.dispatchEvent(new KeyboardEvent("keydown",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})),document.execCommand("delete",false),e.dispatchEvent(new InputEvent("input",{inputType:"deleteContentBackward",bubbles:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})));}extractConversationId(e){const t=e.id.match(/^conversation_(.+)$/)?.[1];if(t)return t;const n=(e.getAttribute("href")||"").match(Ac);return n?.[1]||null}extractConversationTitle(e){const t=e.querySelector(Nc)||Array.from(e.querySelectorAll("span")).find(e=>e.textContent?.trim())||null;return t?.textContent?.trim()||""}getConversationRows(e=document){return Array.from(e.querySelectorAll(Lc))}getHistoryContainer(){return document.querySelector(Ic)}findScrollableAncestor(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t),n=e.overflowY,r=e.overflow;if(("auto"===n||"scroll"===n||"overlay"===n||"auto"===r||"scroll"===r||"overlay"===r)&&t.clientHeight>0)return t;t=t.parentElement;}return null}getActiveConversationRow(){const e=this.getSessionId(),t=this.getConversationRows();return t.find(e=>"page"===e.getAttribute("aria-current"))||t.find(e=>e.className.includes("active-link-")||e.className.includes("e2e-test-active"))||t.find(t=>this.extractConversationId(t)===e)||null}getVirtualScrollContainer(){return Array.from(document.querySelectorAll(Dc)).find(e=>{if(!e.isConnected)return false;if(!(e.querySelector('[data-name="scroll_holder"]')||e.querySelector(Pc)||e.querySelector(qc)))return false;const t=window.getComputedStyle(e);return ("auto"===t.overflowY||"scroll"===t.overflowY||"auto"===t.overflow||"scroll"===t.overflow||e.scrollHeight>e.clientHeight)&&e.clientHeight>0})||null}getSharePageMessageContainer(){if(!this.isSharePage())return null;const e=document.querySelector('[class*="message-list-root-"]');if(e)return this.findScrollableAncestor(e)||e;const t=document.querySelector(`${Bc}, ${Oc}`);return t?this.findScrollableAncestor(t)||t.parentElement||t:null}getOutlineContentContainer(){return this.getVirtualScrollContainer()||this.getSharePageMessageContainer()}getAssistantContentRoots(e){const t=[];return e instanceof HTMLElement&&e.matches(Fc)&&t.push(e),Array.from(e.querySelectorAll(Fc)).forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);}),t}getAssistantContentRoot(e){return e.matches(Fc)?e:e.querySelector(Fc)||e}getConversationTitle(){const e=this.getActiveConversationRow();return e&&this.extractConversationTitle(e)||null}getSessionId(){const e=window.location.pathname.match(Ac),t=e?.[1]||"";return t&&"new"!==t?t:""}isNewConversation(){return /^(?:\/code)?\/chat\/(new\/?)?$/.test(window.location.pathname)}isSharePage(){return window.location.pathname.startsWith("/thread/")}getNewTabUrl(){return `https://www.doubao.com${window.location.pathname.startsWith("/code/")?"/code":""}/chat/`}supportsNewTab(){return true}getConversationList(){const e=this.getConversationRows();if(!e.length)return [];const t=new Map;return e.forEach(e=>{const n=e,r=this.extractConversationId(n);if(!r||"new"===r)return;const o=this.extractConversationTitle(n),i="page"===n.getAttribute("aria-current")||n.className.includes("active-link-")||n.className.includes("e2e-test-active"),a=!!n.querySelector('[class*="pin-"]');t.set(r,{id:r,title:o,url:`https://www.doubao.com/chat/${r}`,isActive:i,isPinned:a});}),Array.from(t.values())}navigateToConversation(e,t){const n=document.querySelector(`#conversation_${e}, ${Lc}[href*="/chat/${e}"]`);return n?(n.click(),true):(window.location.href=t||`https://www.doubao.com/chat/${e}`,true)}getSidebarScrollContainer(){const e=this.getHistoryContainer();return this.findScrollableAncestor(e)||e}getZenModeConfig(){return {hide:["nav",".container-qOgFQp"]}}getCleanModeConfig(){return {hide:[".container-qOgFQp",'[aria-label="活动入口"]']}}getConversationObserverConfig(){return {selector:Lc,shadow:false,extractInfo:e=>{const t=e,n=this.extractConversationId(t);if(!n||"new"===n)return null;return {id:n,title:this.extractConversationTitle(t),url:`https://www.doubao.com/chat/${n}`,isActive:"page"===t.getAttribute("aria-current")||t.className.includes("active-link-")||t.className.includes("e2e-test-active"),isPinned:!!t.querySelector('[class*="pin-"]')}},getTitleElement:e=>e.querySelector(Nc)||Array.from(e.querySelectorAll("span")).find(e=>e.textContent?.trim())||null}}async deleteConversationOnSite(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Gc}}async deleteConversationsOnSite(e){const t=[];for(let n=0;ne.remove());const n=Hi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantResponseTextWithAssets(e,t,n){return [this.extractAssistantMarkdown(e),this.formatDoubaoAssistantImages(this.extractDoubaoAssistantImages(e,n),t).join("\n\n")].filter(Boolean).join("\n\n")}getLatestReplyText(){const e=document.querySelectorAll(Oc);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantMarkdown(t)||null}getUserMessageTextContainer(e){return e.matches($c)?e:e.matches(Bc)?e.querySelector($c):e.querySelector(_c)||e.querySelector($c)}extractUserQueryText(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryMarkdown(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}extractUserQueryExportContentWithAssets(e,t){const n=this.getUserMessageTextContainer(e),r=n?.textContent?.trim()||""||(n?this.extractUserQueryText(n):""),o=this.extractDoubaoUserAttachments(e);if(0===o.length)return r||this.extractUserQueryText(e);const i=this.formatDoubaoUserImageAttachments(o,t),a=this.formatDoubaoUserFileAttachments(o,t),s=a.length>0?`${le("exportAttachmentsLabel")}:\n${a.join("\n")}`:"";return [i.join("\n\n"),s,r].filter(Boolean).join("\n\n")}extractDoubaoUserAttachments(e){const t=Array.from(e.querySelectorAll('[data-plugin-identifier="block_type:10052"] [data-available="true"]')),n=[],r=new Set;return t.forEach(e=>{const t=this.extractDoubaoUserAttachment(e);if(!t)return;const o=`${t.kind}:${t.source||t.name}:${t.type}`;r.has(o)||(r.add(o),n.push(t));}),n}extractDoubaoUserAttachment(e){const t=this.extractDoubaoDownloadableSource(e),n=this.extractDoubaoCleanTextParts(e),{name:r,type:o}=this.parseDoubaoAttachmentLabel(n);if(!r&&!t)return null;const i=r||"attachment";return {kind:this.isDoubaoImageAttachment(i,o,t)?"image":"file",name:i,source:t,type:o}}parseDoubaoAttachmentLabel(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=["image","图片","圖像","图像","file","文件","附件","document","文档","音频","视频"];let r="",o=t;const i=t[t.length-1]||"";n.some(e=>e.toLowerCase()===i.toLowerCase())&&(r=i,o=t.slice(0,-1));let a=o.join(" ").trim();if(!a&&t.length>0){const e=t.join(" ").trim(),o=n.find(t=>e.toLowerCase().endsWith(t.toLowerCase()));o&&e.length>o.length?(r=o,a=e.slice(0,-o.length).trim()):a=e;}return {name:a,type:r}}extractDoubaoCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}const i=n.join("");return n.length<=1&&i?[i]:n}isDoubaoImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}formatDoubaoUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatDoubaoUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"file"===e.kind||!e.source,getLabel:e=>e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?e.name:`${e.name} (${e.type})`:e.name})}formatDoubaoAssistantImages(e,t){return Na(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractDoubaoAssistantImages(e,t){const n=[],r=new Set,o=(e,o)=>{const i=this.normalizeDoubaoImageSource(e);i&&!r.has(i)&&(r.add(i),t?.usedSources.add(i),n.push({source:i,alt:o||`generated image ${n.length+1}`}));};Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement).forEach(e=>{const t=this.extractDoubaoImageSource(e);if(!t)return;const n=(e.alt||e.getAttribute("aria-label")||"generated image").replace(/\s+/g," ").trim();o(t,n);});const i=this.countDoubaoGeneratedImageSlots(e);for(;t&&n.length0)return t}return t.reduce((e,t)=>{const n=t.querySelectorAll('[class*="image-box-grid-item"]').length;if(n>0)return e+n;const r=t.querySelectorAll('[class*="image-wrapper"]').length;return r>0?e+r:e+t.querySelectorAll("img").length},0)}extractDoubaoImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",...this.extractDoubaoSrcsetCandidates(e.getAttribute("srcset")||""),...Array.from(e.closest("picture")?.querySelectorAll("source")||[]).flatMap(e=>this.extractDoubaoSrcsetCandidates(e.getAttribute("srcset")||e.getAttribute("src")||""))];for(const n of t){const e=this.normalizeDoubaoImageSource(n);if(e)return e}return ""}extractDoubaoSrcsetCandidates(e){return e?e.split(",").map(e=>e.trim().split(/\s+/)[0]||"").filter(Boolean):[]}normalizeDoubaoImageSource(e){const t=va(e);return t?/^data:image\/svg\+xml/i.test(t)?"":/^data:image\//i.test(t)||xa(t)?t:"":""}extractDoubaoDownloadableSource(e){const t=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&t.push(e.href||e.getAttribute("href")||""),e instanceof HTMLImageElement&&t.push(this.extractDoubaoImageSource(e)),jc.forEach(n=>{t.push(e.getAttribute(n)||"");});});for(const n of t){const e=va(n);if(!/^data:image\/svg\+xml/i.test(e)&&(this.normalizeDoubaoImageSource(e)||xa(e)))return e}return ""}createDoubaoAssistantImageFallbackState(){return {sources:this.getDoubaoPerformanceImageSources(),nextIndex:0,usedSources:new Set}}takeNextDoubaoFallbackImageSource(e){for(;e.nextIndex{const r=this.normalizeDoubaoImageSource(n.name);if(r&&!t.has(r)){try{const e=new URL(r);if(!(/(^|\.)byteimg\.com$/i.test(e.hostname)&&(/\/rc_gen_image\//i.test(e.pathname)||/flow-imagex-sign/i.test(e.hostname))))return}catch{return}t.add(r),e.push(r);}}),e}replaceUserQueryContent(e,t){const n=this.getUserMessageTextContainer(e);if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}findModelSelectorButton(){const e=document.querySelectorAll('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]');for(const t of e){const e=t;if(null!==e.offsetParent){const t=e.querySelector(".truncate");if(t&&t.textContent?.trim())return e}}return null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'],menuItemSelector:'div[role="menuitem"][data-slot="dropdown-menu-item"]',menuRenderDelay:100}}getModelName(){const e=this.findModelSelectorButton();if(!e)return null;const t=e.innerText?.trim();return t?t.split("\n")[0].trim():null}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,t.width-1)),r=t.top+Math.max(1,Math.min(t.height/2,t.height-1)),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r};e.dispatchEvent(new PointerEvent("pointerenter",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new PointerEvent("pointerover",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new PointerEvent("pointerdown",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mousedown",o)),e.dispatchEvent(new PointerEvent("pointerup",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;if(!(await this.openConversationMenu(t,e)))return false;const n=await this.waitForDeleteMenuItem(2500);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteConfirmButton(2500);return r&&this.simulateClick(r),this.waitForConversationRemoved(e,7e3)}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#conversation_${e}`)}getConversationMenuButtons(e){const t=[],n=[],r=new Set,o=e=>{e&&(r.has(e)||(r.add(e),this.isVisible(e)?t.push(e):n.push(e)));},i=e.querySelector('[class*="chat-item-menu-wrapper-"]');if(!i)return [];const a=i.querySelector('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'),s=i.querySelector('button[data-dbx-name="button"]'),l=i.querySelector('button[aria-haspopup="menu"]');return o(a),o(s),o(l),[...t,...n]}async openConversationMenu(e,t){for(let n=0;n<10;n+=1){e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const t=this.getConversationMenuButtons(e);if(0!==t.length){for(const n of t){document.body.click(),await this.sleep(50);if(await this.tryActivateConversationAction(e,n))return true}await this.sleep(100);}else await this.sleep(80);}return false}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e));if(e)return e;return Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"], [role="dialog"]')).find(e=>{if(!this.isVisible(e))return false;const t=this.getSignalText(e);return t.includes("删除")||t.includes("刪除")||t.includes("delete")})||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nthis.isVisible(e)))return true;await this.sleep(50);}return false}getSignalText(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.className||""].join(" ").toLowerCase()}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getOutlineCacheSessionKey(){return `${this.getCurrentCid()||"default"}:${this.getSessionId()||"default"}:${window.location.pathname}`}ensureOutlineCacheSession(){const e=this.getOutlineCacheSessionKey();if(e===this.outlineCacheSessionKey)return;const t=""===this.outlineCacheSessionKey;this.outlineCacheSessionKey=e,this.outlineItemCache.clear(),this.outlineCacheTransitionEndAt=t?0:Date.now()+1200;}isInOutlineCacheTransition(){return Date.now()>>0;return t.toString(16)}buildOutlineItemId(e,t,n=0){const r=this.getOutlineMessageKey(e);return t.isUserQuery?`doubao:${r}:user`:`doubao:${r}:h${t.level}:${n}:${this.hashOutlineText(t.text)}`}trimOutlineCache(){if(this.outlineItemCache.size<=1200)return;const e=Array.from(this.outlineItemCache.values()).sort((e,t)=>e.rowIndex!==t.rowIndex?e.rowIndex-t.rowIndex:e.orderInMessage-t.orderInMessage),t=new Set(e.slice(-1200).map(e=>e.id));for(const n of this.outlineItemCache.keys())t.has(n)||this.outlineItemCache.delete(n);}clearOutlineCacheForMeta(e){for(const[t,n]of this.outlineItemCache)e.messageId&&n.messageId===e.messageId?this.outlineItemCache.delete(t):n.messageId||n.rowIndex!==e.rowIndex||this.outlineItemCache.delete(t);}mergeCachedOutlineItems(e,t,n,r,o){if(0===this.outlineItemCache.size)return e;const i=[...e];for(const a of this.outlineItemCache.values())t.has(a.id)||a.isUserQuery&&!r||!a.isUserQuery&&a.level>n||a.text.trim()&&i.push({level:a.level,text:a.text,element:null,id:a.id,isUserQuery:a.isUserQuery,isTruncated:a.isTruncated,wordCount:o?a.wordCount:void 0,scrollTop:a.scrollTop});return i.map((e,t)=>{const n=e.id?this.outlineItemCache.get(e.id):void 0;return {item:e,originalIndex:t,rowIndex:n?.rowIndex??Number.MAX_SAFE_INTEGER,orderInMessage:n?.orderInMessage??t}}).sort((e,t)=>e.rowIndex!==t.rowIndex?e.rowIndex-t.rowIndex:e.orderInMessage!==t.orderInMessage?e.orderInMessage-t.orderInMessage:e.originalIndex-t.originalIndex).map(({item:e})=>e)}escapeAttributeValue(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}findMessageElementByCacheEntry(e,t){if(t.messageId){const n=this.escapeAttributeValue(t.messageId),r=e.querySelector(`[data-message-id="${n}"]`);if(r)return r}const n=Array.from(e.querySelectorAll(Pc)).find(e=>this.getVirtualRowIndex(e,-1)===t.rowIndex);return n?.querySelector("[data-message-id]")||null}findHeadingInsideMessage(e,t){if(t.isUserQuery)return e;const n=Array.from(e.querySelectorAll(`h${t.level}`)),r=t.headingMatchIndex??0;let o=0;for(const i of n)if((i.textContent||"").trim()===t.text){if(o===r)return i;o+=1;}return null}resolveCachedDoubaoOutlineTarget(e){if(!e)return null;this.ensureOutlineCacheSession();const t=this.outlineItemCache.get(e);if(!t)return null;const n=this.getOutlineContentContainer();if(!n)return null;const r=this.findMessageElementByCacheEntry(n,t);return r?t.isUserQuery?r:this.findHeadingInsideMessage(r,t):null}scrollVirtualContainerTo(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,Math.min(t,n));e.scrollTo({top:r,behavior:"instant",__bypassLock:true}),e.dispatchEvent(new Event("scroll",{bubbles:true}));}async waitForCachedDoubaoOutlineTargetMount(e,t=1500){if(!e)return null;const n=Date.now()+t;for(;Date.now(){if(a)return;const t=this.getOutlineMessageKey(e);if(!s.has(t)){s.add(t);for(const[t,n]of this.outlineItemCache)(e.messageId&&n.messageId===e.messageId||!n.messageId&&n.rowIndex===e.rowIndex)&&l.set(t,n);this.clearOutlineCacheForMeta(e);}},d=(e,t,n,r,o)=>{const s=this.buildOutlineItemId(t,e,o);if(e.id=s,e.scrollTop=n,i.add(s),a)return;const d=this.outlineItemCache.get(s)??l.get(s);c(t),this.outlineItemCache.set(s,{id:s,level:e.level,text:e.text,messageId:t.messageId,rowIndex:t.rowIndex,scrollTop:n,orderInMessage:r,headingMatchIndex:o,isUserQuery:e.isUserQuery,isTruncated:e.isTruncated,wordCount:e.wordCount??d?.wordCount});},u=(t,i,a,s,l)=>{const c=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));c.forEach((t,u)=>{const h=parseInt(t.tagName[1],10);if(h>e)return;const g=t.textContent?.trim()||"";if(!g)return;const p=`${h}:${g}`,m=a.get(p)||0;let f;if(a.set(p,m+1),n){let e=null;for(let t=u+1;te instanceof HTMLElement);let g=null;return (h.length>0?h:Array.from(o.querySelectorAll(`${Bc}, ${Oc}`)).filter(e=>e instanceof HTMLElement)).forEach((e,i)=>{const a=this.getVirtualMessageMeta(e,i),s=e.matches(Bc)?e:e.querySelector(Bc)??null;if(s){const e=this.extractUserQueryMarkdown(s);g=e?{element:s,text:e,meta:a,scrollTop:this.getElementVirtualScrollTop(o,s)}:null;}const l=this.getAssistantContentRoots(e);if(0===l.length)return;c(a);const h=n?l.reduce((e,t)=>e+(t.textContent?.length||0),0):void 0;if(g){const e={level:0,text:g.text.length>80?g.text.slice(0,80)+"...":g.text,element:g.element,isUserQuery:true,isTruncated:g.text.length>80,wordCount:h};d(e,g.meta,g.scrollTop,0),t&&r.push(e);}const p=new Map;let m=0;l.forEach(e=>u(e,a,p,()=>m++,e)),g=null;}),a?r:(this.trimOutlineCache(),this.mergeCachedOutlineItems(r,i,e,t,n))}getExportConfig(){return {userQuerySelector:Bc,assistantResponseSelector:Oc,turnSelector:qc,useShadowDOM:false}}async extractExportMessages(e){const t=this.extractDoubaoExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractDoubaoExportMessages(e))}extractDoubaoExportMessages(e){const t=[],n=this.createDoubaoAssistantImageFallbackState(),r=Array.from(document.querySelectorAll(qc)).filter(e=>e instanceof HTMLElement);if(r.length>0)return r.forEach(r=>{this.getOrderedDoubaoMessages(r).forEach(({role:r,element:o})=>{t.push({role:r,content:"user"===r?this.extractUserQueryExportContentWithAssets(o,e):this.extractAssistantResponseTextWithAssets(o,e,n)});});}),t;return this.getOrderedDoubaoMessages(document).forEach(({role:r,element:o})=>{t.push({role:r,content:"user"===r?this.extractUserQueryExportContentWithAssets(o,e):this.extractAssistantResponseTextWithAssets(o,e,n)});}),t}getOrderedDoubaoMessages(e){const t=[],n=new Set,r=(e,r)=>{r&&!n.has(r)&&(n.add(r),t.push({role:e,element:r}));};return e instanceof Element&&(e.matches(Bc)?r("user",e):e.matches(Oc)&&r("assistant",e)),e.querySelectorAll(Bc).forEach(e=>r("user",e)),e.querySelectorAll(Oc).forEach(e=>r("assistant",e)),t.sort((e,t)=>{if(e.element===t.element)return 0;const n=e.element.compareDocumentPosition(t.element);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0})}toggleTheme(){return Promise.resolve(false)}isGenerating(){const e=document.querySelector('[data-testid="chat_input_local_break_button"]');return null!==e&&null!==e.offsetParent}getStopButtonSelectors(){return ['[data-testid="chat_input_local_break_button"]']}getNewChatButtonSelectors(){return [Rc]}getSubmitButtonSelectors(){return ["[data-testid='chat_input_send_button']","#flow-end-msg-send",".send-btn-wrapper button"]}getWidthSelectors(){return [{selector:'[data-container-name="main"]',property:"max-width"},{selector:".max-w-\\(--content-max-width\\)",property:"max-width"},{selector:".max-w-\\[var\\(--content-max-width\\)\\]",property:"max-width"},{selector:'[style*="--content-max-width"]',property:"--content-max-width"},{selector:".chrome70-container",property:"--center-content-max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${Bc} .w-fit[class*="max-w-"]`,property:"max-width"}]}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getChatContentSelectors();if(!t.length)return null;const n=Array.from(e.querySelectorAll(t.join(", ")));if(!n.length)return null;const r=e.getBoundingClientRect();let o=null;for(let i=0;i=r.top-50&&t.bottom<=r.bottom+50){o=e;break}if(t.top<=r.top&&t.bottom>=r.top){o=e;break}}if(!o)for(let i=0;ir.bottom){o=e;break}}if(o){const e=n.indexOf(o);if(-1!==e){return {type:"index",index:e,offset:0,textSignature:(o.textContent||"").trim().substring(0,50)}}}return null}scrollToOutlineTarget(e){const t=this.getScrollContainer();if(!t)return void super.scrollToOutlineTarget(e);const n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),o=t.scrollTop+r.top-n.top;t.scrollTo({top:Math.max(0,o),behavior:"instant",__bypassLock:true});}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}return !!n&&(this.scrollToOutlineTarget(n),true)}},new class extends vs{exportIncludeThoughts=void 0;match(){return window.location.hostname===Fu}getSiteId(){return vo}getName(){return "ima"}getThemeColors(){return {primary:"#07a45f",secondary:"#05854d"}}supportsHostThemeSync(){return false}getSessionId(){const e=window.location.pathname.match(Uu);return e?.[1]||""}isNewConversation(){return "/"===(window.location.pathname.replace(/\/+$/,"")||"/")}isSharePage(){return window.location.pathname.startsWith("/share/")}getCurrentCid(){const e=window.localStorage.getItem("ima-official-website-uid");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","userId","openId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=this.getActiveHistoryTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*ima$/i,"").replace(/^ima\s*[-|]\s*/i,"").trim();return n&&"ima"!==n.toLowerCase()?n:null}getNewTabUrl(){return "https://ima.qq.com/"}getConversationTitle(){return this.getActiveHistoryTitle()||this.getSessionName()}getTextareaSelectors(){return ['#tagTextarea [contenteditable="true"], [class*="chatInputContainer"] .tiptap.ProseMirror']}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!!e.isContentEditable&&!!e.closest("#tagTextarea, [class*='chatInputContainer']"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus(),this.selectAllEditorContent(t);if(this.tryPasteText(t,e))return true;try{if(document.execCommand("insertText",!1,e))return this.dispatchEditorInput(t,e,"insertText"),!0}catch{}return t.textContent=e,this.dispatchEditorInput(t,e,"insertText"),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus(),this.selectAllEditorContent(e);try{document.execCommand("delete",!1);}catch{}e.textContent="",this.dispatchEditorInput(e,"","deleteContentBackward");}}getSubmitButtonSelectors(){return [uh]}findSubmitButton(e){const t=[e?.closest("#tagTextarea"),e?.closest('[class*="chatInputContainer"]'),document.querySelector('[class*="chatInputContainer"]'),document.body].filter(Boolean);for(const n of t){const e=n.querySelector(uh);if(e&&this.isVisibleElement(e)&&!e.querySelector('.icon-send-disable-big, [class*="sendDisableIcon"]'))return e}return null}getNewChatButtonSelectors(){return ['[class*="newChatWrap"]']}getSidebarScrollContainer(){return document.querySelector("#HistoryScrollContainer")}getScrollContainer(){const e=document.querySelector(Hu);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Wu}getChatContentSelectors(){return [Vu,Xu]}getUserQuerySelector(){return Vu}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg").forEach(e=>{e.remove();}),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}getLatestReplyText(){const e=document.querySelectorAll(Xu),t=e[e.length-1];if(!t)return null;return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Wu)||document.querySelector(Hu);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(`${Vu}, ${Xu}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((r,a)=>{if(r.matches(Vu)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Xu));s=e?this.extractAssistantResponseText(e).length:0;}return void o.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractImaExportMessages(e))}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [hh]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/cgi-bin/assistant/qa"],urlPathEndsWith:["/cgi-bin/assistant/qa"],silenceThreshold:2e3}}getModelName(){const e=this.findVisibleElementBySelectors([ph]),t=e?.innerText?.trim()||e?.textContent?.trim()||"";if(t)return t.split("\n")[0].trim();const n=this.findVisibleElementBySelectors([gh]),r=n?.innerText?.trim()||n?.textContent?.trim()||"";return r?r.split("\n")[0].trim():null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[gh,ph],menuItemSelector:'.modelDropdown .t-dropdown__item, .modelDropdown [class*="modelOption"], .t-popup .modelDropdown .t-dropdown__item',menuRenderDelay:200,checkInterval:1e3,maxAttempts:10}}getWidthSelectors(){return [{selector:Hu,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:Wu,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:'[class*="_chatInputContainer_"] [class*="_editorContainer_"]',property:"max-width",extraCss:"width: 100vw !important; margin: 0 auto;"}]}getUserQueryWidthSelectors(){return [{selector:Zu,property:"max-width"}]}getZenModeConfig(){return {hide:[".expandable-sidebar-panel-sidebar"]}}getCleanModeConfig(){return {hide:['[class*="_downloadContainer_"]','[class*="footTips"]','[class*="_activityBanner"]','[class*="_activityBannerContent"]','[class*="_qaDownloadGuide"]']}}extractImaExportMessages(e){const t=document.querySelector(Wu)||document.querySelector(Hu)||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${Vu}, ${Xu}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches(Vu)?"user":"assistant";return {role:n,content:("user"===n?this.extractUserQueryExportContentWithAssets(t,e):this.extractAssistantResponseTextWithAssets(t,e)).trim()}}).filter(e=>e.content.length>0)}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserQueryText(e),r=this.extractImaUserAttachments(e);if(0===r.length)return n;const o=this.formatImaUserImageAttachments(r,t),i=this.formatImaUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatImaAssistantImages(this.extractImaAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport(),n=e.cloneNode(true),r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(`${oh}, ${ch}`).forEach(e=>e.remove()),n.querySelectorAll(nh).forEach(e=>e.remove());const o=this.findAssistantMarkdownRoot(n),i=o instanceof HTMLElement?o:this.findAssistantBubbleRoot(n),a=(i?Hi(i).trim():"")||(i?this.extractTextWithLineBreaks(i).trim():"");if(t&&r.length>0){const e=r.join("\n\n");return a?`${e}\n\n${a}`:e}return a}extractImaUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getImaAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return this.queryElementsIncludingSelf(t,ah).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractImaUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,sh).forEach(e=>{o(this.extractImaUserFileAttachment(e));}),n}extractImaUserImageAttachment(e){const t=this.extractImaImageSource(e);if(!t)return null;const n=e.alt?.trim()||e.getAttribute("title")?.trim()||ga(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:pa(n)||ma(t)||"image"}}extractImaUserFileAttachment(e){if(e instanceof HTMLImageElement||e.closest('[class*="imgWrap"], [id^="image-toolkit-"]')||e.querySelector("img"))return null;const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=fa(t),i=this.extractImaDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||ga(i,{ignoreGenericDownload:true})||this.extractDataAttributeFilename(e);if(!a&&!i)return null;const s=a||"attachment";return {kind:"file",name:s,source:i,type:r||pa(s)||ma(i),sizeLabel:o}}formatImaUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatImaUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId()})}extractImaAssistantImages(e){const t=this.findAssistantBubbleRoot(e)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,lh).forEach(e=>{if(!(e instanceof HTMLImageElement))return;if(e.closest(".gh-root, .gh-user-query-markdown"))return;const t=this.extractImaImageSource(e),o=ha(t);t&&!r.has(o)&&(r.add(o),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`,extensionHint:this.extractImaImageExtensionHint(e)}));}),n}formatImaAssistantImages(e,t){return Na(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractImaImageSource(e){const t=[e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeImaExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractImaDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractImaImageSource(e)),!t.includeImages&&e instanceof HTMLImageElement||dh.forEach(t=>{n.push(e.getAttribute(t)||"");});});for(const r of n){const e=this.normalizeImaExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeImaExportSource(e,t){const n=e.trim();if(!n||n.startsWith("#")||/^javascript:/i.test(n))return "";const r=va(n);if(!r)return "";if(/^data:image\/svg\+xml/i.test(r))return "";if(/^data:image\//i.test(r))return t.allowDataImage?r:"";if(/^data:/i.test(r))return r;if(!xa(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===Fu&&/^\/(?:chat|share|ai-chat)(?:\/|$)/i.test(e.pathname))return "";if(e.hostname===Fu&&/\/(?:static|assets)\//i.test(e.pathname))return "";if(/\/wupload\/xy\/(?:qb_tool|ima_tool)\//i.test(e.pathname))return "";if(/\.(?:svg|ico)$/i.test(e.pathname)&&/(?:icon|logo|sprite)/i.test(e.pathname))return ""}catch{return ""}return r}extractImaImageExtensionHint(e){return [e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.alt||""].map(e=>ma(e)||pa(e)).find(Boolean)||""}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll(oh).forEach(e=>e.remove()),t.querySelectorAll("img").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getImaAttachmentKeys(e){const t=[],n=ha(e.source),r=e.name.trim().toLowerCase(),o=e.type.trim().toLowerCase(),i=e.sizeLabel?.trim().toLowerCase()||"";return n&&t.push(`${e.kind}:source:${n}`),r&&o&&t.push(`${e.kind}:name-type:${r}:${o}`),r&&i&&t.push(`${e.kind}:name-size:${r}:${i}`),t.length>0?t:[`${e.kind}:fallback:${r}:${o}`]}extractDataAttributeFilename(e){const t=["data-file-name","data-filename","data-name","title","aria-label","data-file-id","data-doc-id","data-resource-id"];for(const n of t){const t=e.getAttribute(n)?.trim();if(t)return t}return ""}findUserMessageScope(e){return e.matches(Vu)?e:e.closest(Vu)||e}findAssistantBubbleRoot(e){if(e.matches(Ju))return e;const t=e.querySelector(Ju);if(t instanceof HTMLElement)return t;const n=e.querySelector('[class*="bubble"]');return n instanceof HTMLElement?n:e instanceof HTMLElement?e:null}shouldSkipExportElement(e){return null!==e.closest(".gh-root, .gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}getActiveHistoryTitle(){const e=document.querySelector('[class*="historyListWrap"] [class*="itemWrap"][class*="highLight"] [class*="main"]');return e?.textContent?.trim()||""||null}findUserContentRoot(e){return e.matches(Yu)?e:e.querySelector(Yu)||e.querySelector("p")||e}findAssistantMarkdownRoot(e){return e.matches(th)?e:e.querySelector(th)}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll(rh).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(nh)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="tipsWrap"], [class*="thinkingTitle"], [class*="thinkingHeader"], button, [role=\'button\'], svg, [aria-hidden=\'true\']').forEach(e=>e.remove());const t=(Hi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}tryPasteText(e,t){if("undefined"==typeof DataTransfer||"undefined"==typeof ClipboardEvent)return false;try{const n=new DataTransfer;n.setData("text/plain",t);const r=new ClipboardEvent("paste",{clipboardData:n,bubbles:!0,cancelable:!0,composed:!0});if(!e.dispatchEvent(r))return !0}catch{return false}return false}selectAllEditorContent(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}dispatchEditorInput(e,t,n){e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:t,inputType:n})),e.dispatchEvent(new Event("change",{bubbles:true}));}isVisibleElement(e){if(!e||!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}findStopButton(){const e=Array.from(document.querySelectorAll('div[class*="stopButton"], [class*="stopButton"]'));for(const t of e){if(!(t instanceof HTMLElement&&this.isVisibleElement(t)))continue;const e=[t.querySelector(":scope > div"),t.querySelector('[class*="container"]'),t];for(const t of e)if(t instanceof HTMLElement&&this.isVisibleElement(t))return t}return null}},new class extends vs{exportIncludeThoughtsOverride=null;exportApiMessages=null;match(){return js.has(window.location.hostname)}getSiteId(){return po}getName(){return "智谱清言"}getThemeColors(){return {primary:"#2454FF",secondary:"#1F46D6"}}async toggleTheme(e){const t=Qs[e]||Qs.light;try{localStorage.setItem(Vs,t);if(await this.applyThemeByClick(e))return !0;const n="system"===e&&"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,r="system"===e?n?"dark":"light":e,o=e=>{e&&(e.classList.toggle("dark-theme","dark"===r),e.classList.remove("light-theme"),e.setAttribute("data-theme",r),e.setAttribute("data-color-scheme",r),e.style.colorScheme=r);},i=new Set;document.documentElement&&i.add(document.documentElement),document.body&&i.add(document.body);const a=[document.querySelector("#app"),document.querySelector("[data-v-app]"),document.querySelector(".app"),document.querySelector(".app-container")];for(const e of a)e instanceof HTMLElement&&i.add(e);for(const e of i)o(e);return window.dispatchEvent(new StorageEvent("storage",{key:Vs,newValue:t,storageArea:localStorage})),!0}catch{return false}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t){const t=new MouseEvent(r,{bubbles:true,cancelable:true,view:window});n=e.dispatchEvent(t)||n;}n||e.click();}async applyThemeByClick(e){const t=this.findVisibleElement(Ks);if(!t)return false;this.simulateClick(t),await this.delay(120);const n=await this.waitForVisibleElement(".themes",1500);if(!n)return false;this.simulateClick(n),await this.delay(120);const r=await this.findThemeOption(e,1500);return !!r&&(this.simulateClick(r),await this.delay(80),true)}findVisibleElement(e){for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return this.resolveClickable(e)}return null}resolveClickable(e){return e.closest(".me-icon")||e.closest(".me")||e.closest(".userInfoBar-header")||e}async waitForVisibleElement(e,t=800){const n=Date.now();for(;Date.now()-n0)break}return Array.from(t)}matchThemeOption(e,t){const n=t.map(e=>e.replace(/\s+/g,"").toLowerCase());for(const r of e){const e=r.textContent?.replace(/\s+/g,"").toLowerCase()||"";if(e&&n.some(t=>e.includes(t)))return r}return null}async delay(e){await new Promise(t=>window.setTimeout(t,e));}getTextareaSelectors(){return il}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=new URLSearchParams(window.location.search);if(this.isSharePage())return e.get(Gs)?.trim()||e.get("share_id")?.trim()||window.location.pathname.match(/^\/share\/([^/?#]+)/)?.[1]?.trim()||"";const t=e.get("cid");return t?t.trim():""}isNewConversation(){return !this.getSessionId()}getNewChatButtonSelectors(){return [".new-session",'div[class~="new-session"]']}getNewTabUrl(){return new URL("/main/alltoolsdetail?lang=zh",window.location.origin).toString()}isSharePage(){return window.location.pathname.startsWith("/glmsShare")||window.location.pathname.startsWith("/share/")||"1"===new URLSearchParams(window.location.search).get("is_share")}isUserConversationPage(){const e=new URLSearchParams(window.location.search).get("cid")?.trim();return !this.isSharePage()&&Boolean(e)&&e===this.getSessionId()}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*(智谱清言|ChatGLM(?:\s*\d+)?)\s*$/i,"").trim();return n&&"智谱清言"!==n&&"chatglm"!==n.toLowerCase()?n:null}getConversationTitle(){const e=document.querySelector(".conversation-name");if(e){const t=e.textContent?.trim();if(t)return t}return null}getSubmitButtonSelectors(){return [`${al}:not(.empty)`]}findSubmitButton(){const e=document.querySelector(al);return !e||e.classList.contains("empty")||null===e.offsetParent?null:e}getScrollContainer(){const e=document.querySelector(Ys);if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chatScrollContainer");return t&&t.scrollHeight>t.clientHeight?t:super.getScrollContainer()}getResponseContainerSelector(){return Ys}getChatContentSelectors(){return [tl,Js]}getUserQuerySelector(){return Xs}extractUserQueryText(e){const t=e.querySelector(Js)||e;return this.extractTextWithLineBreaks(t).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractChatGLMUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=e.querySelector(Js);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=[...n.classList,"gh-user-query-markdown","gh-markdown-preview"].filter(e=>"dots"!==e&&"dot-3-line"!==e).join(" ").trim(),r.innerHTML=t;const o=n.getAttribute("style");o&&r.setAttribute("style",o),r.style.textAlign="left",r.style.display="block",r.style.width="100%",n.style.display="none";const i=e.querySelector(".collapse-button-bg");return i&&(i.style.display="none"),n.after(r),true}extractAssistantResponseText(e){return this.extractChatGLMAssistantExportContent(e).trim()}getLatestReplyText(){const e=document.querySelector(Ys)||document.body,t=this.collectChatGLMAssistantExportElements(e),n=t[t.length-1];if(!n)return null;return this.extractAssistantResponseText(n)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Ys);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(".conversation-item"));return i.forEach((r,a)=>{const s=r.querySelector(Xs);if(s&&t){const e=this.extractUserQueryMarkdown(s);if(e){let t;if(n){const e=(e=>{for(let t=e+1;t80?`${e.slice(0,80)}...`:e,element:s,isUserQuery:true,isTruncated:e.length>80,wordCount:t});}}const l=r.querySelectorAll(tl);l.length&&l.forEach(t=>{const r=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));r.forEach((i,a)=>{if(this.isInRenderedMarkdownContainer(i))return;const s=Number.parseInt(i.tagName.slice(1),10);if(Number.isNaN(s)||s>e)return;const l=i.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=a+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractChatGLMExportMessages(e))}async fetchShareApiMessages(){const e=this.getShareConversationId();if(!e)return null;try{const t=await fetch(`/chatglm/share-api/conversation/info/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`share conversation info failed with ${t.status}`);const n=await t.json(),r=n?.result?.messages;return Array.isArray(r)?r:null}catch(RS){return console.warn("[ChatGLMAdapter] Failed to load share export metadata:",RS),null}}getShareConversationId(){return new URLSearchParams(window.location.search).get(Gs)?.trim()||""}extractChatGLMExportMessages(e){return this.exportApiMessages?.length?this.extractChatGLMApiExportMessages(this.exportApiMessages,e):this.extractChatGLMDomExportMessages(e)}extractChatGLMApiExportMessages(e,t){const n=[];return e.forEach(e=>{const r=this.extractChatGLMApiUserContent(e,t).trim();r&&n.push({role:"user",content:r});const o=this.extractChatGLMApiAssistantContent(e,t).trim();o&&n.push({role:"assistant",content:o});}),n}extractChatGLMApiUserContent(e,t){const n=[],r=[];return e.input?.content?.forEach(e=>{"text"===e.type&&e.text?.trim()&&n.push(e.text.trim()),e.image?.forEach(e=>{const t=this.createChatGLMApiAttachment(e,"image");t&&r.push(t);}),e.file?.forEach(e=>{const t=this.createChatGLMApiAttachment(e,"file");t&&r.push(t);});}),this.formatChatGLMUserExportContent(n.join("\n\n"),r,t)}extractChatGLMApiAssistantContent(e,t){const n=this.shouldIncludeThoughtsInExport(),r=[],o=[],i=[];e.output?.parts?.forEach(e=>{const t=this.extractChatGLMApiThought(e,e);t?n&&r.push(this.formatAsThoughtBlockquote(t)):e.content?.forEach(t=>{const a=this.extractChatGLMApiThought(t,e);if(a)return void(n&&r.push(this.formatAsThoughtBlockquote(a)));t.image?.forEach(e=>{const t=this.createChatGLMGeneratedImageAttachment(e.image_url||"");t&&i.push(t);});const s=this.extractChatGLMApiBodyText(t);s&&o.push(s);});}),e.output?.image_list?.forEach(e=>{const t=this.createChatGLMGeneratedImageAttachment(e);t&&i.push(t);});const a=this.formatChatGLMAssistantImageAttachments(i,t);return [r.join("\n\n"),a.join("\n\n"),o.join("\n\n")].filter(Boolean).join("\n\n")}extractChatGLMApiThought(e,t){const n=this.extractChatGLMApiThoughtText(e);if(!n)return "";const r="type"in e&&e.type||"",o=e.answer_type||"";if(/^(think|text_thinking|advanced_thinking)$/i.test(r||o))return n;const i=e.meta_data?.show_type||t.meta_data?.show_type||"",a=e.meta_data?.engine?.type||t.meta_data?.engine?.type||"";return /think|thought|reason|cot/i.test(`${i} ${a}`)?n:""}extractChatGLMApiBodyText(e){return "tool_calls"===e.type||this.extractChatGLMApiThought(e,{meta_data:e.meta_data})?"":this.extractChatGLMApiContentText(e)}extractChatGLMApiThoughtText(e){const t=e.advancedThinkingData?.map(e=>this.extractChatGLMApiContentText(e)).filter(Boolean).join("\n\n");return t||this.extractChatGLMApiContentText(e)}extractChatGLMApiContentText(e){return e.think?.trim()||e.text?.trim()||e.answer?.trim()||("content"in e&&"string"==typeof e.content?e.content.trim():"")||"intent_original_output"in e&&e.intent_original_output?.trim()||""||"type"in e&&"code"===e.type&&e.code?.trim()||""}createChatGLMApiAttachment(e,t){const n=this.decodeChatGLMAttachmentName(e.file_name||e.file_id||("image"===t?"uploaded image":"file")),r=this.normalizeChatGLMAttachmentSource(e.file_url||e.image_url||""),o=e.file_type||e.type||n.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"",i=this.isChatGLMImageAttachment(n,o,r)?"image":t;return n||r?{kind:i,name:n||("image"===i?"uploaded image":"file"),source:r,type:o,size:e.file_size}:null}createChatGLMGeneratedImageAttachment(e){const t=this.normalizeChatGLMAttachmentSource(e);return t?{kind:"image",name:this.extractChatGLMFilenameFromUrl(t)||"generated image",source:t,type:"image"}:null}extractChatGLMDomExportMessages(e){const t=document.querySelector(Ys)||document.body,n=this.collectChatGLMAssistantExportElements(t),r=[...Array.from(t.querySelectorAll(Xs)).map(e=>({role:"user",element:e})),...n.map(e=>({role:"assistant",element:e}))].filter(({element:e})=>!e.closest(".gh-root, .gh-user-query-markdown")).sort((e,t)=>this.compareDomOrder(e.element,t.element)),o=[];return r.forEach(({role:t,element:n})=>{const r=("user"===t?this.extractChatGLMUserQueryExportContent(n,e):this.extractChatGLMAssistantExportContent(n,e)).trim();if(!r)return;const i=o[o.length-1];i?.role!==t?o.push({role:t,content:r}):i.content=`${i.content}\n\n${r}`;}),o}collectChatGLMAssistantExportElements(e){const t=[],n=new Set;return Array.from(e.querySelectorAll(`${el}, ${nl}`)).forEach(e=>{if(e.closest(".gh-root, .gh-user-query-markdown"))return;const r=this.findChatGLMThoughtRoot(e),o=r?.closest(el);if(r&&o&&o!==r)return;const i=r||e;!r&&e.closest(nl)||n.has(i)||(n.add(i),t.push(i));}),t.sort((e,t)=>this.compareDomOrder(e,t))}findChatGLMThoughtRoot(e){let t=e.matches(nl)?e:e.closest(nl);if(!t)return null;let n=t.parentElement?.closest(nl)||null;for(;n;)t=n,n=t.parentElement?.closest(nl)||null;return t}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractChatGLMUserQueryExportContent(e,t){const n=this.extractUserQueryMarkdown(e).trim(),r=this.extractChatGLMUserAttachmentsFromDom(e);return this.formatChatGLMUserExportContent(n,r,t)}extractChatGLMAssistantExportContent(e,t){const n=this.shouldIncludeThoughtsInExport(),r=e.matches(nl),o=e.cloneNode(true),i=this.extractThoughtBlockquotes(o),a=n?i.blocks:[];if(r)return a.join("\n\n");i.removalNodes.forEach(e=>e.remove()),o.querySelectorAll(nl).forEach(e=>e.remove());const s=this.extractChatGLMAssistantImageMarkdown(e,t),l=(o.matches(el)||o.matches(".markdown-body")?o:o.querySelector(".markdown-body")||o).cloneNode(true);l.querySelectorAll(rl).forEach(e=>e.remove()),l.querySelectorAll("img").forEach(e=>{e instanceof HTMLImageElement&&this.isExportableChatGLMImage(e)&&e.remove();});const c=(Hi(l)||this.extractTextWithLineBreaks(l)).trim();return [a.join("\n\n"),s.join("\n\n"),c].filter(Boolean).join("\n\n")}formatChatGLMUserExportContent(e,t,n){if(0===t.length)return e;const r=this.dedupeChatGLMAttachments(t),o=this.formatChatGLMUserImageAttachments(r,n),i=this.formatChatGLMUserFileAttachments(r,n),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,e].filter(Boolean).join("\n\n")}extractChatGLMUserAttachmentsFromDom(e){const t=e.matches(Xs)?e:e.closest(Xs);if(!t)return [];const n=[];Array.from(t.querySelectorAll("img")).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractChatGLMImageSource(e);if(!t)return;const r=this.extractChatGLMAttachmentNameFromElement(e)||e.alt||"uploaded image";n.push({kind:"image",name:r,source:t,type:r.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"image"});});return Array.from(t.querySelectorAll("a[href], button, [class*='file'], [class*='image-with-text']")).forEach(e=>{if(e.closest(".gh-root, .gh-user-query-markdown"))return;const t=this.extractChatGLMDomAttachment(e);t&&n.push(t);}),this.dedupeChatGLMAttachments(n)}extractChatGLMDomAttachment(e){const t=this.extractTextWithLineBreaks(e).replace(/\s+/g," ").trim(),n=this.extractChatGLMDownloadableSource(e),r=this.extractChatGLMAttachmentNameFromText(t)||this.extractChatGLMFilenameFromUrl(n);if(!r)return null;const o=r.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"";return {kind:this.isChatGLMImageAttachment(r,o,n)?"image":"file",name:r,source:n,type:o,size:this.parseChatGLMSizeLabel(t)}}extractChatGLMAttachmentNameFromElement(e){const t=this.extractTextWithLineBreaks(e.closest("button, a, [class*='file']")||e);return this.extractChatGLMAttachmentNameFromText(t)}extractChatGLMAttachmentNameFromText(e){const t=e.replace(/\s+/g," ").trim();return t.match(/[^\s/\\]+\.[A-Za-z0-9]{1,10}/)?.[0]||""}extractChatGLMAssistantImageMarkdown(e,t){const n=Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&this.isExportableChatGLMImage(e)).map(e=>({kind:"image",name:e.alt||this.extractChatGLMFilenameFromUrl(this.extractChatGLMImageSource(e))||"generated image",source:this.extractChatGLMImageSource(e),type:"image"}));return this.formatChatGLMAssistantImageAttachments(n,t)}formatChatGLMUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatChatGLMAssistantImageAttachments(e,t){return Ra(this.dedupeChatGLMAttachments(e),t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}formatChatGLMUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),getLabel:e=>{const t=e.size?`, ${this.formatChatGLMFileSize(e.size)}`:"";return e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?`${e.name}${t}`:`${e.name} (${e.type}${t})`:`${e.name}${t}`}})}dedupeChatGLMAttachments(e){const t=new Set,n=[];return e.forEach(e=>{const r=this.getChatGLMAttachmentSourceKey(e.source),o=`${e.kind}:${e.name.trim().toLowerCase()}:${e.type.trim().toLowerCase()}`,i=r?`${e.kind}:source:${r}`:o;t.has(i)||(t.add(i),n.push(e));}),n}extractThoughtBlockquotes(e){const t=[...e.matches(nl)?[e]:[],...Array.from(e.querySelectorAll(nl))].filter(e=>!e.parentElement?.closest(nl)),n=[],r=[];return t.forEach(e=>{const t=(e.querySelector("blockquote[slot='content'], blockquote, .text-advance-thinking-content .markdown-body, .thinking-content .markdown-body, .advance-thinking-area .markdown-body, .markdown-body")||e).cloneNode(true);t.querySelectorAll(rl).forEach(e=>e.remove());const o=document.createElement("div");Array.from(t.childNodes).forEach(e=>o.appendChild(e.cloneNode(true)));const i=(Hi(o)||this.extractTextWithLineBreaks(t)).trim();i&&n.push(this.formatAsThoughtBlockquote(i)),r.push(e);}),{blocks:n,removalNodes:r}}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> [Thought]",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim()?`> ${e}`:">")].join("\n")}isExportableChatGLMImage(e){const t=this.extractChatGLMImageSource(e);if(!t)return false;if(!xa(t))return false;if(t.startsWith("data:image/svg+xml"))return false;try{const e=new URL(t,window.location.href);if("chatglm.cn"===e.hostname&&/^\/(assets|icon)\//i.test(e.pathname))return !1;if(/image_loading|newLogo|avatar|favicon|icon/i.test(e.pathname))return !1;if(/\/(chat\/image|testpath|file)\//i.test(e.pathname))return !0}catch{return false}const n=e.getBoundingClientRect();return Math.max(e.naturalWidth||0,n.width)>=80&&Math.max(e.naturalHeight||0,n.height)>=80}extractChatGLMImageSource(e){if(this.isChatGLMAvatarImage(e))return "";const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=this.normalizeChatGLMAttachmentSource(n);if(e)return e}return ""}isChatGLMAvatarImage(e){if(e.classList.contains("user-img")||e.classList.contains("avatar"))return true;if(e.closest(".user-img, .avatar, .user-avatar, .userInfoBar-header"))return true;const t=e.currentSrc||e.src||e.getAttribute("src")||"";return /\/wechat_avatar\//i.test(t)}extractChatGLMDownloadableSource(e){const t=Array.from(e.querySelectorAll("img")).find(e=>e instanceof HTMLImageElement&&Boolean(this.extractChatGLMImageSource(e)));if(t)return this.extractChatGLMImageSource(t);const n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of ol){const t=this.normalizeChatGLMAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeChatGLMAttachmentSource(e){const t=va(e);if(!t||!xa(t))return "";try{const e=new URL(t,window.location.href);if("chatglm.cn"===e.hostname&&/^\/(assets|icon)\//i.test(e.pathname))return "";if(/wechat_avatar|image_loading|newLogo|avatar|favicon|iconfont/i.test(e.pathname))return ""}catch{return ""}return t}isChatGLMImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}parseChatGLMSizeLabel(e){const t=e.match(/(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)/i);if(!t)return;const n=Number(t[1]);if(!Number.isFinite(n))return;const r=t[2].toUpperCase(),o="TB"===r?1024**4:"GB"===r?1024**3:"MB"===r?1048576:"KB"===r?1024:1;return Math.round(n*o)}formatChatGLMFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?Math.round(n).toString():n.toFixed(1)} ${t[r]}`}extractChatGLMFilenameFromUrl(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname;return this.decodeChatGLMAttachmentName(t.split("/").pop()||"")}catch{return ""}}getChatGLMAttachmentSourceKey(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.hostname}${t.pathname}`.toLowerCase()}catch{return e.split("?")[0].toLowerCase()}}decodeChatGLMAttachmentName(e){try{return decodeURIComponent(e)}catch{return e}}isGenerating(){const e=[".stop-generate",".stop-answer-default",".stop-stream-tip",".answer-content-wrap .generating-icon",".enter-icon-container.stop",".enter.searching",".enter.is-main-chat.searching"];for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return true}return false}getStopButtonSelectors(){return [".stop-generate",".stop-answer-default",".stop-stream-tip",".answer-content-wrap .generating-icon",".enter-icon-container.stop",".enter.searching",".enter.is-main-chat.searching"]}getModelName(){const e=[".wrapper-title .showHideText",".wrapper-title .wrapper-title-innerText",".wrapper-title",".selected-model-info .model-select-name",".model-select-container .model-select-name",".model-select-list .model-select-item.selected .model-select-name",".model-select-name"];for(const t of e){const e=document.querySelectorAll(t);for(const t of Array.from(e)){const e=t.textContent?.trim();if(!e)continue;if(null!==t.offsetParent)return e.split("\n")[0].trim()}}for(const t of e){const e=document.querySelector(t),n=e?.textContent?.trim();if(n)return n.split("\n")[0].trim()}return null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".wrapper-title",".wrapper-title .showHideText",".model-select-icon-container",".selected-model-info",".model-select-container"],menuItemSelector:".model-select-list .model-select-item",menuRenderDelay:150,checkInterval:1e3,maxAttempts:10}}getNetworkMonitorConfig(){return {urlPatterns:["/chatglm/backend-api/assistant/stream"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:".conversation-container",property:"max-width"},{selector:".conversation-inner",property:"max-width"},{selector:".conversation-list",property:"max-width"},{selector:".dialogue .detail .item, .dialogue .detail .item.item, .dialogue .detail .item.item.item",property:"max-width"},{selector:".markdown-body, .markdown-body.markdown-body, .answer-content-wrap .markdown-body",property:"max-width"},{selector:".code-no-artifacts .markdown-body.md-code, .code-no-artifacts .md-code",property:"max-width",value:"100%",extraCss:["width: 100% !important;","margin-left: 0 !important;","margin-right: 0 !important;","box-sizing: border-box !important;"].join(" "),noCenter:true},{selector:".code-no-artifacts .markdown-body.md-code > .language, .code-no-artifacts .markdown-body.md-code pre",property:"max-width",value:"100%",extraCss:"width: 100% !important; box-sizing: border-box !important;",noCenter:true},{selector:".markdown-body table, .answer-content-wrap .markdown-body table",property:"width",value:"100%",extraCss:"table-layout: fixed !important; display: table !important; min-width: 100% !important;",noCenter:true},{selector:".markdown-body table th, .markdown-body table td",property:"min-width",value:"0",noCenter:true},{selector:".conversation-list",property:"width",value:"100%"},{selector:".conversation-bottom[data-v-e5578310]",property:"max-width",extraCss:"flex: 1 !important;"},{selector:".component-box-new[data-v-fb010f38]",property:"max-width"}]}getZenModeConfig(){return {hide:[".el-aside"]}}getCleanModeConfig(){return {hide:[".policy-wrap, .policy-wrap *",".vip-btn",".slogan-banner"]}}},new class extends vs{deleteReloadScheduled=false;loggedMissingDeleteToken=false;fullListSnapshot=[];fullListSnapshotExpiresAt=0;fullListSnapshotUsesLeft=0;exportIncludeThoughts=void 0;match(){const e="www.kimi.com"===window.location.hostname;return e&&this.normalizeThemeStorageValue(),e}getSiteId(){return wo}getName(){return "Kimi"}getThemeColors(){return {primary:"#7C3AED",secondary:"#6D28D9"}}getNativeThemeCss(){return "\n/* =============================================\n * Kimi 站点原生主题适配器 (Kimi Theme Adapter)\n * ============================================= */\n:root {\n /* 1. 主体与大容器背景 */\n // --Bg-Primary: var(--gh-bg) !important;\n // --Bg-Tertiary: var(--gh-bg) !important;\n // --Bg-Quaternary: var(--gh-bg) !important;\n // --BgGp-Secondary: var(--gh-bg-secondary) !important;\n // --Always-White: var(--gh-bg) !important;\n\n /* 2. 灰色次级容器层 (底色画布、侧边栏、交互卡片) */\n --Bg-GroundPC: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n --Bg-Secondary: color-mix(in srgb, var(--gh-primary) 3%, var(--gh-bg)) !important;\n --BgGp-Primary: color-mix(in srgb, var(--gh-primary) 3%, var(--gh-bg)) !important;\n --BgGp-Tertiary: color-mix(in srgb, var(--gh-primary) 4%, var(--gh-bg)) !important;\n --Others-BubbleGray_PC: var(--gh-bg-secondary) !important;\n\n /* 3. 强调与品牌色 (主色系挂载为 Ophel 主题) */\n --Colors-KMBlue: var(--gh-primary) !important;\n --Colors-KMBlue-hover: color-mix(in srgb, var(--gh-primary) 85%, white) !important;\n --Colors-KMBlue-active: color-mix(in srgb, var(--gh-primary) 85%, black) !important;\n --Others-KMBlue10: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n\n /* 4. 辅助状态的高亮 */\n --Others-TextSelected: color-mix(in srgb, var(--gh-primary) 20%, transparent) !important;\n --Others-LightBlueBg: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n\n /* 代码块背景色 */\n --Fills-F1: var(--gh-bg-tertiary) !important;\n\n}\n\n.sidebar {\n background-color: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n}\n\n"}supportsFormulaCopy(){return false}getNewTabUrl(){return "https://www.kimi.com/"}getSessionId(){const e=window.location.pathname;if("/chat/history"===e||e.startsWith("/chat/history/"))return "";const t=e.endsWith("/")?e:`${e}/`;if(bh.some(e=>t.startsWith(e)))return "";const n=e.match(mh);if(n?.[1])return n[1];const r=e.match(fh);return r?.[1]||""}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e||"/chat/history"===e||e.startsWith("/chat/history/")}isSharePage(){return window.location.pathname.startsWith("/share/")||window.location.pathname.startsWith("/kimiplus/")}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t||"Kimi"===t)return null;return t.replace(/^Kimi\s*\|\s*/i,"").replace(/\s*-\s*Kimi$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(e,t);r&&n.push(r);}),this.mergeConversationInfos(n)}getConversationObserverConfig(){return {selector:Th,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(`${Ah}, ${Mh}`)||e}}getSidebarScrollContainer(){const e=[document.querySelector(".history .group-list-container"),document.querySelector(Eh),document.querySelector(".history .usage-content"),document.querySelector(".history .content"),document.querySelector(".history")].filter(Boolean);for(const t of e){const e=this.findScrollableParent(t);if(e)return e;if(t instanceof HTMLElement&&t.scrollHeight>t.clientHeight)return t}return null}async loadAllConversations(){await this.openMoreHistoryView();try{let e=0,t=0;const n=4;for(;tsetTimeout(e,500));const r=document.querySelectorAll(Th).length;r===e?t++:(e=r,t=0);}this.cacheFullListSnapshot(this.collectConversationListFromDom());}finally{await this.closeMoreHistoryView();}}async deleteConversationOnSite(e){const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),{id:e.id,success:false,method:"api",reason:Wh};const n=this.getSessionId(),r=await this.deleteConversationViaApi(e,t);return r.success&&e.id===n&&this.navigateToHomeAfterDelete(),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),e.map(e=>({id:e.id,success:false,method:"api",reason:Wh}));const n=this.getSessionId(),r=[],o=[];for(const i of e){const e=await this.deleteConversationViaApi(i,t);r.push(e),e.success&&o.push(i.id);}if(o.length>0){n&&o.includes(n)?this.navigateToHomeAfterDelete():this.scheduleReloadAfterBatchDelete();}return r}navigateToConversation(e,t){const n=this.buildConversationUrl(e,t),r=this.findConversationLinkById(e);if(r){const t=this.getSessionId();return r.click(),window.setTimeout(()=>{this.getSessionId()!==e&&this.getSessionId()===t&&this.navigateToKimiConversationRoute(n);},120),true}return !!this.navigateToKimiConversationRoute(n)||super.navigateToConversation(e,n)}getConversationTitle(){const e=document.querySelector(".chat-header-content h2")?.textContent?.trim();if(e)return e;const t=this.getActiveConversationLink();if(t){const e=this.extractConversationTitle(t);if(e)return e}const n=this.getSessionId();if(n){const e=this.findConversationLinkById(n);if(e){const t=this.extractConversationTitle(e);if(t)return t}}return null}getTextareaSelectors(){return ['.chat-input-editor[data-lexical-editor="true"]','.chat-input-editor[contenteditable="true"]','[role="textbox"].chat-input-editor']}isValidTextarea(e){return null!==e.offsetParent&&(!!e.isContentEditable&&(!e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&!!e.closest(".chat-input-editor-container")))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return false;if(this.insertByExecCommand(t,e))return true;return this.insertByPasteEvent(t,e)||(t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}))),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=()=>0===(e.textContent||"").replace(/[\u200b\u00a0]/g,"").trim().length,n=()=>{this.selectEditorAll(e);try{document.dispatchEvent(new Event("selectionchange"));}catch{}},r=t=>{try{e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,composed:!0,cancelable:!0,inputType:t}));}catch{}},o=(t,n,r)=>{e.dispatchEvent(new KeyboardEvent("keydown",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true}));},i=()=>{if(e.isConnected){e.focus(),n(),r("deleteContentBackward");try{document.execCommand("delete",!1,void 0);}catch{}if(!t())try{document.execCommand("insertText",!1,"");}catch{}if(t()||o("Backspace","Backspace",8),t()||(r("deleteContentForward"),o("Delete","Delete",46)),t()||(()=>{try{const e=window.getSelection();if(!e||0===e.rangeCount)return;e.getRangeAt(0).deleteContents();}catch{}})(),!t()){this.clearByExecCommand(e)&&t()||(e.innerHTML="


");}(t=>{try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,inputType:t}));}catch{e.dispatchEvent(new Event("input",{bubbles:true}));}})("deleteContentBackward"),e.dispatchEvent(new Event("change",{bubbles:true}));}};i();[30,120,240].forEach(n=>{setTimeout(()=>{e.isConnected&&(t()||i());},n);});}getSubmitButtonSelectors(){return [".send-button-container:not(.disabled):not(.stop)"]}findSubmitButton(e){const t=[e?.closest(".chat-editor"),e?.closest(".chat-input-editor-container"),e?.parentElement,document.body].filter(Boolean),n=new Set;for(const r of t){const e=r.querySelectorAll(".send-button-container");for(const t of Array.from(e)){const e=t;if(!n.has(e)&&(n.add(e),null!==e.offsetParent&&!e.classList.contains("disabled")&&!e.classList.contains("stop")))return e}}return null}getScrollContainer(){const e=document.querySelector(".share-detail");if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chat-detail-content");if(t&&t.scrollHeight>t.clientHeight)return t;const n=document.querySelector(".chat-content-container"),r=this.findScrollableParent(n);return r&&!r.closest(Eh)?r:super.getScrollContainer()}getResponseContainerSelector(){return Lh}getChatContentSelectors(){return [zh,_h]}getUserQuerySelector(){return qh}extractUserQueryText(e){const t=e.querySelector(".segment-content-box");return this.extractTextWithLineBreaks(t||e).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractKimiUserQueryExportContent(e)}replaceUserQueryContent(e,t){if(e.querySelector(".gh-user-query-markdown"))return false;const n=e.querySelector(".segment-content-box");if(!n)return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}extractAssistantResponseText(e){const t=e.cloneNode(true);t.querySelectorAll(Uh).forEach(e=>e.remove());const n=this.shouldIncludeThoughtsInExport()?this.extractThoughtBlockquotes(t):[];t.querySelectorAll(Fh).forEach(e=>e.remove());const r=this.findAssistantBodyMarkdownRoot(t);if(!r)return n.length>0?n.join("\n\n"):"";const o=(Hi(r)||this.extractTextWithLineBreaks(r)).trim();if(n.length>0){const e=n.join("\n\n");return o?`${e}\n\n${o}`:e}return o}getLatestReplyText(){const e=document.querySelectorAll(zh);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Lh);if(!r)return [];const o=[],i=this.getChatItems(r);return i.forEach((r,a)=>{if(r.matches(Dh)||r.matches(qh)||r.querySelector(qh)){if(!t)return;const e=r.querySelector(qh)||r,s=this.extractUserQueryMarkdown(e);if(!s)return;let l;if(n){const e=this.findNextAssistantMarkdown(i,a);l=e?.textContent?.trim().length||0;}return void o.push({level:0,text:s.length>80?`${s.slice(0,80)}...`:s,element:e,isUserQuery:true,isTruncated:s.length>80,wordCount:l})}if(!r.matches(Ph)&&!r.matches(Bh)&&!r.querySelector(zh))return;const s=this.findAssistantBodyMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6"));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractKimiExportMessages(e))}async prepareConversationExport(e){return this.exportIncludeThoughts=e.includeThoughts,null}async restoreConversationAfterExport(e,t){this.exportIncludeThoughts=void 0;}isGenerating(){const e=document.querySelectorAll(".send-button-container.stop");for(const n of Array.from(e))if(null!==n.offsetParent)return true;const t=document.querySelectorAll('.send-button-container svg[name="stop"]');for(const n of Array.from(t)){const e=n.closest(".send-button-container");if(e&&null!==e.offsetParent)return true}return false}getStopButtonSelectors(){return [".send-button-container.stop",'.send-button-container:has(svg[name="stop"])']}getModelName(){const e=document.querySelector(".current-model .model-name .name");return e?.textContent?.trim()||null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".current-model.active .model-name",".current-model .model-name"],menuItemSelector:['[role="menuitem"]','[role="option"]',".n-base-select-option",".n-dropdown-option",".model-item",".model-option"].join(", "),checkInterval:1e3,maxAttempts:15,menuRenderDelay:350}}getNetworkMonitorConfig(){return {urlPatterns:["apiv2/kimi.gateway.chat.v1.ChatService/Chat"],silenceThreshold:2e3}}async toggleTheme(e){try{const t=JSON.stringify(e);localStorage.setItem(Hh,t);const n=document.documentElement;return n.classList.remove("light","dark"),n.classList.add(e),window.dispatchEvent(new StorageEvent("storage",{key:Hh,newValue:t,storageArea:localStorage})),!0}catch(RS){return console.error("[KimiAdapter] toggleTheme error:",RS),false}}getNewChatButtonSelectors(){return ["a.new-chat-btn",'a.new-chat-btn[href="/"]','a.new-chat-btn[href="https://www.kimi.com/"]']}getWidthSelectors(){return [{selector:".chat-detail-content",property:"width",value:"100%",noCenter:true,extraCss:"max-width: 100% !important; min-width: 0 !important;"},{selector:".chat-content-container",property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:Nh,property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important; min-width: 0 !important; padding-left: 0 !important; padding-right: 0 !important;"},{selector:Nh,property:"width",value:"100%",noCenter:true},{selector:".chat-editor",property:"max-width"}]}getUserQueryWidthSelectors(){const e=["margin-left: auto !important; margin-right: 0 !important;","max-width: 100% !important;","box-sizing: border-box !important;"].join(" "),t=["max-width: 100% !important;","margin-left: 0 !important;","margin-right: 0 !important;","box-sizing: border-box !important;"].join(" "),n=["max-width: 100% !important;","box-sizing: border-box !important;","overflow-wrap: anywhere !important;"].join(" ");return [{selector:$h,property:"width",extraCss:e,noCenter:true},{selector:_h,property:"width",value:"100%",extraCss:t,noCenter:true},{selector:Oh,property:"width",value:"100%",extraCss:n,noCenter:true}]}getZenModeConfig(){return {hide:[".sidebar-placeholder"],rootClass:{selector:".app.has-sidebar",className:"fold"}}}getCleanModeConfig(){return {hide:[".chat-bottom .legal-footer, .legal-footer",".membership-upgrade",".download-app-btn",".activity-area"]}}getMarkdownFixerConfig(){return {selector:".segment-assistant .markdown p",fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(".segment-assistant");if(!t)return false;const n=document.querySelectorAll(`${Ph} .segment-assistant`);return t===n[n.length-1]}}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}normalizeThemeStorageValue(){const e=localStorage.getItem(Hh);if(!e)return;const t=e.trim();if(t)if("light"!==t&&"dark"!==t)try{const e=JSON.parse(t);if("light"===e||"dark"===e)return}catch{}else localStorage.setItem(Hh,JSON.stringify(t));}async deleteConversationViaApi(e,t){try{const n=new URL("/apiv2/kimi.chat.v1.ChatService/DeleteChat",window.location.origin).toString(),r=await fetch(n,{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_id:e.id}),credentials:"include"});if(!r.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(r.status)};const o=await this.safeParseJson(r);return this.isDeleteSuccessPayload(o,e.id)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(o)}}catch{return {id:e.id,success:false,method:"api",reason:jh}}}buildDeleteHeaders(e){const t=this.parseJwtPayload(e),n={accept:"*/*",authorization:`Bearer ${e}`,"connect-protocol-version":"1","content-type":"application/json","x-language":this.getClientLanguage(),"r-timezone":this.getClientTimezone(),"x-msh-platform":"web","x-msh-version":"1.0.0"},r="string"==typeof t.device_id?t.device_id.trim():"",o="string"==typeof t.ssid?t.ssid.trim():"",i="string"==typeof t.sub?t.sub.trim():"";return r&&(n["x-msh-device-id"]=r),o&&(n["x-msh-session-id"]=o),i&&(n["x-traffic-id"]=i),n}getAuthToken(){const e=this.getCookieToken(vh);if(e)return e;const t=this.findAuthTokenInStorage(localStorage);if(t)return t;try{const e=this.findAuthTokenInStorage(sessionStorage);if(e)return e}catch{}return null}getCookieToken(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return n?.[1]?this.extractTokenFromRaw(n[1]):null}findAuthTokenInStorage(e){for(const t of xh){const n=e.getItem(t),r=this.extractTokenFromRaw(n);if(r)return r}for(let t=0;t6||null==e)return null;if("string"==typeof e)return this.extractTokenFromRaw(e);if(Array.isArray(e)){for(const r of e){const e=this.findTokenInUnknown(r,t+1,n);if(e)return e}return null}if("object"!=typeof e)return null;if(n.has(e))return null;n.add(e);const r=e;for(const o of wh){if(!(o in r))continue;const e=this.findTokenInUnknown(r[o],t+1,n);if(e)return e}for(const[o,i]of Object.entries(r)){if(wh.includes(o)||t>0&&!Ch.test(o)&&"object"!=typeof i)continue;const e=this.findTokenInUnknown(i,t+1,n);if(e)return e}return null}logMissingDeleteTokenOnce(){this.loggedMissingDeleteToken||(this.loggedMissingDeleteToken=true,console.warn("[KimiAdapter] DeleteChat skipped: auth token not found in cookie/storage."));}parseJwtPayload(e){try{const t=e.split(".");if(t.length<2)return {};const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(4*Math.ceil(n.length/4),"="),o=atob(r),i=JSON.parse(o);return i&&"object"==typeof i?i:{}}catch{return {}}}getClientLanguage(){return document.documentElement.lang||navigator.language||"en-US"}getClientTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return "UTC"}}isDeleteSuccessPayload(e,t){if(!e||"object"!=typeof e)return false;const n=e,r=n.chatId,o=n.chat_id;return r===t||o===t}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return Gh;const t=e,n="string"==typeof t.message&&t.message.trim()||"string"==typeof t.msg&&t.msg.trim()||"string"==typeof t.error&&t.error.trim()||"";return n?`${Vh}:${n}`:Vh}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleReloadAfterBatchDelete(){this.deleteReloadScheduled||(this.deleteReloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120));}navigateToHomeAfterDelete(){const e=window.location.pathname;"/"!==e&&""!==e?window.location.href=this.getNewTabUrl():this.scheduleReloadAfterBatchDelete();}extractConversationInfo(e,t){const n=e.getAttribute("href")||"",r=this.extractConversationIdFromHref(n);if(!r)return null;return {id:r,cid:t,title:this.extractConversationTitle(e),url:`https://www.kimi.com/chat/${r}`,isActive:e.classList.contains("router-link-active")||e.classList.contains("router-link-exact-active"),isPinned:!!e.querySelector("svg.pinned, .pinned")}}extractConversationTitle(e){const t=e.querySelector(Ah)?.textContent?.trim()||e.querySelector(Mh)?.textContent?.trim()||"";if(t)return t;const n=e.textContent?.replace(/\s+/g," ").trim()||"";return n.length>120?`${n.slice(0,120)}...`:n}extractConversationIdFromHref(e){if(!e)return null;try{const t=new URL(e,window.location.origin).pathname.match(mh);return t?t[1]:null}catch{return null}}buildConversationUrl(e,t){if(t)try{const n=new URL(t,window.location.origin);if(this.extractConversationIdFromHref(n.href)===e)return n.search||n.searchParams.set("chat_enter_method","history"),n.toString()}catch{}return new URL(`/chat/${e}?chat_enter_method=history`,window.location.origin).toString()}findConversationLinkById(e){const t=document.querySelectorAll(Th);for(const n of Array.from(t)){const t=n.getAttribute("href")||"";if(this.extractConversationIdFromHref(t)===e)return n}return null}navigateToKimiConversationRoute(e){let t;try{t=new URL(e,window.location.origin);}catch{return false}if(t.origin!==window.location.origin)return false;if(!this.extractConversationIdFromHref(t.href))return false;const n=`${t.pathname}${t.search}${t.hash}`;if(n===`${window.location.pathname}${window.location.search}${window.location.hash}`)return true;try{window.history.pushState(window.history.state,"",n);const e="function"==typeof PopStateEvent?new PopStateEvent("popstate",{state:window.history.state}):new Event("popstate");return window.dispatchEvent(e),!0}catch{return false}}findScrollableParent(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if(("auto"===e.overflowY||"scroll"===e.overflowY)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}getActiveConversationLink(){const e=document.querySelector(`${kh}.router-link-active, ${kh}.router-link-exact-active`);if(e)return e;if("/"===window.location.pathname||""===window.location.pathname)return null;const t=this.getSessionId();return t?this.findConversationLinkById(t):null}isHistoryPath(e=window.location.pathname){return "/chat/history"===e||e.startsWith("/chat/history/")}async openMoreHistoryView(){if(this.isHistoryPath())return;const e=document.querySelector('a.more-history[href*="/chat/history"], a.nav-item.more-history[href*="/chat/history"]');if(!e)return;const t=window.location.pathname,n=document.querySelectorAll(kh).length;e.click();const r=Date.now()+3e3;for(;Date.now()n)return;await new Promise(e=>setTimeout(e,120));}}async closeMoreHistoryView(){if(!this.isHistoryPath())return;const e=document.querySelector([".header-right .close-button-container",".header-right .close-button",".history .header-right .close-button-container",".history .header-right .close-button"].join(", "));if(!e)return;const t=e.closest(".close-button-container")||e;if(this.simulateClick(t),!(await this.waitForHistoryClosed(900))&&(t.click(),!(await this.waitForHistoryClosed(1200)))){try{window.history.back();}catch{}await this.waitForHistoryClosed(1500);}}async waitForHistoryClosed(e){const t=Date.now()+e;for(;Date.now()setTimeout(e,80));}return !this.isHistoryPath()}cacheFullListSnapshot(e){e.length&&(this.fullListSnapshot=e.map(e=>({...e})),this.fullListSnapshotExpiresAt=Date.now()+15e3,this.fullListSnapshotUsesLeft=6);}getFreshFullListSnapshot(){if(!this.fullListSnapshot.length)return [];const e=Date.now()>this.fullListSnapshotExpiresAt,t=this.fullListSnapshotUsesLeft<=0;return e||t?(this.fullListSnapshot=[],this.fullListSnapshotExpiresAt=0,this.fullListSnapshotUsesLeft=0,[]):this.fullListSnapshot.map(e=>({...e}))}mergeConversationInfos(...e){const t=new Map;return e.forEach(e=>{e.forEach(e=>{const n=t.get(e.id);n?t.set(e.id,{...n,title:n.title||e.title,isActive:n.isActive||e.isActive,isPinned:n.isPinned||e.isPinned}):t.set(e.id,e);});}),Array.from(t.values())}selectEditorAll(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}insertByExecCommand(e,t){try{this.selectEditorAll(e);if(document.execCommand("insertText",!1,t))return !0}catch{}return false}insertByPasteEvent(e,t){try{if("undefined"==typeof DataTransfer)return !1;const n=e.textContent||"",r=new DataTransfer;r.setData("text/plain",t);if(!e.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:!0,cancelable:!0,composed:!0})))return !0;return (e.textContent||"")!==n||0===t.length}catch{return false}}clearByExecCommand(e){try{return this.selectEditorAll(e),document.execCommand("delete",!1,void 0)}catch{return false}}extractKimiExportMessages(e){const t=document.querySelector(Lh);if(!t)return [];const n=[],r=this.getChatItems(t);for(const o of r){const t=this.findKimiUserMessageRoot(o);if(t){const r=this.extractKimiUserQueryExportContent(t,e).trim();r&&n.push({role:"user",content:r});continue}const r=this.findKimiAssistantMessageRoot(o);if(r){const e=this.extractAssistantResponseText(r).trim();e&&n.push({role:"assistant",content:e});}}return n}findKimiUserMessageRoot(e){return e.matches(qh)?e:e.querySelector(qh)}findKimiAssistantMessageRoot(e){if(e.matches(Bh))return e;const t=e.querySelector(Bh);if(t)return t;const n=this.findAssistantBodyMarkdownRoot(e);return n?.closest(Bh)||null}extractKimiUserQueryExportContent(e,t){const n=this.extractKimiUserImageMarkdown(e,t),r=this.extractKimiUserFileMarkdown(e,t),o=this.extractKimiUserBodyMarkdown(e);if(0===n.length&&0===r.length)return o;const i=r.length>0?`${le("exportAttachmentsLabel")}:\n${r.join("\n")}`:"";return [n.join("\n\n"),i,o].filter(Boolean).join("\n\n")}extractKimiUserBodyMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll(".attachment-list").forEach(e=>e.remove()),t.querySelectorAll(Uh).forEach(e=>e.remove());const n=t.querySelector(".segment-content-box");return this.extractTextWithLineBreaks(n||t).trim()}extractKimiUserImageMarkdown(e,t){const n=Array.from(e.querySelectorAll(".attachment-list-image img, .image-thumbnail img.image-main, .image-wrapper img.image-main")).filter(e=>e instanceof HTMLImageElement),r=new Set,o=[];for(const i of n){const e=this.getKimiImageExportSource(i);if(!e||r.has(e))continue;r.add(e);const n=this.extractKimiImageAlt(i,e),a=La({source:e,alt:n,extensionHint:n},t,{siteId:this.getSiteId(),role:"user",category:"image",fallbackAlt:"uploaded image"});a&&o.push(a);}return o}getKimiImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=va(n);if(e&&(!e.startsWith("data:image/svg+xml")&&xa(e)))return e}return ""}extractKimiImageAlt(e,t){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractKimiFilenameFromUrl(t),"uploaded image"].map(e=>e.replace(/\s+/g," ").trim()).find(Boolean)||"uploaded image"}extractKimiUserFileMarkdown(e,t){const n=Array.from(e.querySelectorAll(".attachment-list-file .file-card-container")),r=new Set,o=[];for(const i of n){const e=this.extractKimiFileName(i);if(!e)continue;const n=this.extractKimiFileType(i),a=this.extractKimiFileSize(i),s=this.formatKimiFileLabel(e,n,a),l=Da([{kind:"file",name:e,source:this.extractKimiFileHref(i),type:n,sizeLabel:a}],t,{siteId:this.getSiteId(),getLabel:()=>s})[0];r.has(l)||(r.add(l),o.push(l));}return o}extractKimiFileName(e){const t=[e.querySelector(".file-card-info-name")?.textContent||"",e.getAttribute("download")||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",e.textContent||""].map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=t.find(e=>/[^/\\]+\.[A-Za-z0-9]{1,10}(\s|$)/.test(e));return n?n.match(/[^/\\]+?\.[A-Za-z0-9]{1,10}/)?.[0]||"":t[0]||""}extractKimiFileType(e){return e.querySelector(".file-ext")?.textContent?.replace(/\s+/g," ").trim()||""}extractKimiFileSize(e){return e.querySelector(".file-size")?.textContent?.replace(/\s+/g," ").trim()||""}formatKimiFileLabel(e,t,n){const r=[t&&!this.fileNameEndsWithExtension(e,t)?t:"",n].filter(Boolean);return r.length>0?`${e} (${r.join(", ")})`:e}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}extractKimiFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")),n=e.closest("a[href]");n&&t.unshift(n);for(const r of t){if(!(r instanceof HTMLAnchorElement))continue;const e=va(r.getAttribute("href")||r.href||"");if(xa(e))return e}return ""}extractKimiFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename");if(n?.trim())return n.trim();const r=decodeURIComponent(t.pathname);return r.split("/").pop()?.trim()||""}catch{return ""}}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}findAssistantBodyMarkdownRoot(e){if(e.matches(".markdown")&&!this.isInsideAssistantToolcall(e))return e;const t=e.querySelector(zh);return t&&!this.isInsideAssistantToolcall(t)?t:Array.from(e.querySelectorAll(".markdown")).find(e=>!this.isInsideAssistantToolcall(e))||null}isInsideAssistantToolcall(e){return null!==e.closest(Fh)||null!==e.closest(".markdown-container.toolcall-content-text")}extractThoughtBlockquotes(e){const t=this.collectTopLevelBlocks(Array.from(e.querySelectorAll(".toolcall-container.thinking-container, .thinking-container"))),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(Uh).forEach(e=>e.remove());const t=Array.from(e.querySelectorAll(".markdown")),o=(t.length>0?t.map(e=>Hi(e)||this.extractTextWithLineBreaks(e)).join("\n\n"):Hi(e)||this.extractTextWithLineBreaks(e)).trim();o&&n.push(this.formatAsThoughtBlockquote(o));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}getChatItems(e){const t=Array.from(e.querySelectorAll(Rh)).filter(e=>!e.parentElement?.closest(Rh));return t.length>0?t:Array.from(e.children).filter(e=>e.matches(Dh)||e.matches(Ph)||e.matches(qh)||e.matches(Bh)||null!==e.querySelector(qh)||null!==e.querySelector(zh))}findNextAssistantMarkdown(e,t){for(let n=t+1;nt.id===e);if(t?.title)return t.title;this.refreshConversationSnapshot();}return this.getSessionName()}getConversationList(){const e=this.collectConversationListFromDom(),t=this.getFreshConversationSnapshot();return 0===e.length?(0===t.length&&this.refreshConversationSnapshot(),t):0===t.length?(this.refreshConversationSnapshot(),e):this.mergeConversationInfos(t,e)}getConversationObserverConfig(){return {selector:Cg,shadow:false,extractInfo:e=>this.extractSidebarConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(kg)||e}}getSidebarScrollContainer(){return document.querySelector(`${wg} ${Sg}`)||document.querySelector(Sg)||document.querySelector(wg)}async loadAllConversations(){await this.refreshConversationSnapshot({force:true,fetchAllPages:true});}navigateToConversation(e,t){const n=this.getCurrentCid()||void 0,r=document.querySelectorAll(Cg);for(const o of Array.from(r)){const t=this.extractSidebarConversationInfo(o,n);if(!t||t.id!==e)continue;const r=o.querySelector("a, button, [role='button']")||o;return this.simulateClick(r),true}return super.navigateToConversation(e,t||`https://chat.qwen.ai/c/${e}`)}getTextareaSelectors(){return ["textarea.message-input-textarea","textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${Ng}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Ng);return this.isVisibleActionElement(e)?e.hasAttribute("disabled")||this.isStopLikeButton(e)?null:e:null}getNewChatButtonSelectors(){return [".sidebar-entry-fixed-list-content"]}getScrollContainer(){const e=document.querySelector(Tg);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Eg}getAssistantMermaidSupportMode(){return "native"}extractFormulaCopySource(e,t){const n=e.closest(Xg)||t.closest(Xg);if(!n)return null;const r=n.querySelector("math");if(!r)return null;const o=this.extractQwenLatexFromMath(r),i=this.serializeQwenMathml(r);return o||i?{latex:o,mathml:i,isBlock:!!n.closest(".katex-display")||"block"===r.getAttribute("display")}:null}getChatContentSelectors(){return [Ag,Mg]}getUserQuerySelector(){return Ag}getLatestReplyText(){const e=document.querySelectorAll(Mg),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantMarkdown(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=this.shouldIncludeThoughtsInExport(),r=n?this.getThoughtBlocksForElement(e):[],o=t.cloneNode(true);this.normalizeQwenCodeBlocks(o),o.querySelectorAll(`${Fg}, ${Wg}`).forEach(e=>e.remove());const i=(Hi(o)||this.extractTextWithLineBreaks(o)).trim();if(n&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatQwenAssistantImages(this.extractQwenAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}getLastCodeBlockText(){const e=document.querySelectorAll(Mg);for(let t=e.length-1;t>=0;t-=1){const n=this.findAssistantContentRoot(e[t]);if(!n)continue;const r=Array.from(n.querySelectorAll(Dg));for(let e=r.length-1;e>=0;e-=1){const t=this.extractQwenCodeBlockText(r[e]);if(t)return t}}return super.getLastCodeBlockText()}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(Eg)||document.querySelector(Tg);if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${Ag}, ${Mg}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(Ag)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Mg));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest($g)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t!e.closest(".gh-root"));for(const r of n)await this.captureThoughtBlocksForMessage(r);return {shouldCloseThoughtPanel:!t&&null!==this.getVisibleThoughtPanel()}}async restoreConversationAfterExport(e,t){try{this.parseThoughtExportState(t)?.shouldCloseThoughtPanel&&await this.closeThoughtPanelIfNeeded(),await this.restoreMermaidBlocksAfterExport();}finally{this.exportIncludeThoughtsOverride=null,this.clearThoughtExportCache();}}async extractExportMessages(e){const t=this.extractQwenExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractQwenExportMessages(e))}async toggleTheme(e){try{const t=this.resolveThemeMode(e);return !!(await this.updateThemePreference(e))&&(this.syncThemeState(t,e),!0)}catch(RS){return console.error("[QwenAiAdapter] toggleTheme error:",RS),false}}getModelName(){const e=document.querySelector(Vg),t=e?.innerText?.trim()||e?.textContent?.trim()||"";return t?t.split("\n")[0].trim():null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}clickModelSelector(){const e=this.findModelTrigger();return !!e&&(this.simulateClick(e),true)}lockModel(e,t){const n=this.normalizeModelKeyword(e);if(!n)return;let r=0;const o=async()=>{r++;const i=this.findModelTrigger();if(!i)return r>=12?void this.showQwenModelLockFailure(e,"button_not_found"):void window.setTimeout(o,1e3);if(this.normalizeModelKeyword(this.getModelLockCheckText(i)).includes(n))return void t?.();const a=await this.selectQwenModel(n);a.success?t?.():this.showQwenModelLockFailure(e,a.reason||"not_found");};o();}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[Gg,Vg],menuItemSelector:Yg,checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:Zg,subMenuTriggers:["展开更多模型","更多模型","view more","more models"]}}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [...Rg]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/v2/chat/completions"],urlPathEndsWith:["/chat/completions"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:".qwen-chat-message",property:"max-width",extraCss:"width: 100% !important; box-sizing: border-box !important;"},{selector:".message-input-wrapper",property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:".chat-user-message-container .chat-user-message-wrapper .chat-user-message",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:[wg]}}getCleanModeConfig(){return {hide:[".chat-container-statement"]}}getMarkdownFixerConfig(){return {selector:`${Mg} .qwen-markdown-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(Mg);if(!t)return false;const n=document.querySelectorAll(Mg);return t===n[n.length-1]}}}getFreshConversationSnapshot(){return this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4||this.conversationSnapshotPromise||this.refreshConversationSnapshot(),this.conversationSnapshot.map(e=>({...e}))}async refreshConversationSnapshot(e={}){const{force:t=false,fetchAllPages:n=false}=e,r=this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4;return !t&&r?this.conversationSnapshot.map(e=>({...e})):(this.conversationSnapshotPromise||(this.conversationSnapshotPromise=(async()=>{try{const e=await this.fetchConversationSnapshot(n);e.length>0&&(this.conversationSnapshot=e,this.conversationSnapshotFetchedAt=Date.now());}catch(RS){console.warn("[QwenAiAdapter] Failed to refresh conversation snapshot:",RS);}finally{this.conversationSnapshotPromise=null;}return this.conversationSnapshot.map(e=>({...e}))})()),this.conversationSnapshotPromise)}async fetchConversationSnapshot(e){const t=this.getSessionId(),n=e?100:5,r=[],o=new Set;for(let i=1;i<=n;i++){const n=await this.fetchConversationPage(i);if(0===n.length)break;let a=0;for(const e of n)o.has(e.id)||(o.add(e.id),r.push(e),a++);if(0===a)break;if(!e&&t&&o.has(t))break}return r}async fetchConversationPage(e){const t=new URL("/api/v2/chats/",window.location.origin);t.searchParams.set("page",String(e)),t.searchParams.set("exclude_project","true");const n=await fetch(t.toString(),{method:"GET",credentials:"include",cache:"no-store",headers:{Accept:"application/json, text/plain, */*","X-Request-Id":crypto.randomUUID(),source:"web"}});if(!n.ok)throw new Error(`fetch conversations failed: ${n.status}`);const r=await n.json();if(false===r.success)return [];const o=Array.isArray(r.data)?r.data:[],i=this.getCurrentCid()||void 0,a=[];return o.forEach(e=>{const t=this.normalizeConversationApiItem(e,i);t&&a.push(t);}),a}normalizeConversationApiItem(e,t){if(!e||"object"!=typeof e)return null;const n=e,r="string"==typeof n.id?n.id.trim():"",o="string"==typeof n.title?n.title.trim():"";return r&&o?{id:r,cid:t,title:o,url:`https://chat.qwen.ai/c/${r}`,isPinned:Boolean(n.pinned),isActive:r===this.getSessionId()}:null}collectConversationListFromDom(){const e=document.querySelectorAll(Cg);if(0===e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractSidebarConversationInfo(e,t);r&&n.push(r);}),n}extractSidebarConversationInfo(e,t){const n=this.extractConversationIdFromElement(e);if(!n)return null;const r=e.querySelector(kg),o=r?.textContent?.trim()||"";return o?{id:n,cid:t,title:o,url:`https://chat.qwen.ai/c/${n}`,isPinned:!!e.querySelector(".chat-item-title-pined-icon"),isActive:n===this.getSessionId()}:null}extractConversationIdFromElement(e){const t=e.querySelector('a[href*="/c/"]'),n=t?.getAttribute("href"),r=this.extractConversationIdFromText(n);if(r)return r;const o=[e,...Array.from(e.querySelectorAll("*"))];for(const i of o){const e=i.getAttributeNames?.()||[];for(const t of e){const e=i.getAttribute(t),n=this.extractConversationIdFromText(e);if(n)return n}}return null}extractQwenLatexFromMath(e){return Array.from(e.childNodes).filter(e=>e.nodeType===Node.TEXT_NODE).map(e=>e.textContent?.trim()||"").filter(Boolean).join(" ").trim()}serializeQwenMathml(e){const t=e.cloneNode(true);Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.TEXT_NODE&&e.remove();});try{return (new XMLSerializer).serializeToString(t).trim()}catch{return t instanceof HTMLElement?t.outerHTML.trim():""}}extractConversationIdFromText(e){if(!e)return null;const t=e.match(vg);if(t?.[1])return t[1];const n=e.match(/\b[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\b/i);return n?.[0]||null}mergeConversationInfos(...e){const t=new Map;for(const n of e)for(const e of n){const n=t.get(e.id);t.set(e.id,{...n,...e});}return Array.from(t.values())}extractQwenExportMessages(e){const t=this.getQwenExportRoot();return this.getOrderedQwenMessages(t).map(({role:t,element:n})=>({role:t,content:("user"===t?this.extractUserQueryExportContentWithAssets(n,e):this.extractAssistantResponseTextWithAssets(n,e)).trim()})).filter(e=>e.content.length>0)}getQwenExportRoot(){return document.querySelector(Eg)||document.querySelector(Tg)||document.body}getOrderedQwenMessages(e){const t=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,Ag)).filter(e=>!this.shouldSkipExportElement(e)),n=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,Mg)).filter(e=>!this.shouldSkipExportElement(e));return [...t.map(e=>({role:"user",element:e})),...n.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element))}extractUserQueryExportContentWithAssets(e,t){const n=this.extractQwenUserTextParts(e).join("\n\n").trim()||this.extractUserQueryText(e),r=this.extractQwenUserAttachments(e);if(0===r.length)return n;const o=this.formatQwenUserImageAttachments(r,t),i=this.formatQwenUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractQwenUserTextParts(e){const t=this.findUserMessageScope(e),n=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,Ig)),r=[],o=new Set;return n.forEach(e=>{if(e.closest(".gh-user-query-markdown"))return;const t=e.cloneNode(true);t.querySelectorAll(Fg).forEach(e=>e.remove());const n=this.extractTextWithLineBreaks(t).trim();n&&!o.has(n)&&(o.add(n),r.push(n));}),r}extractQwenUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getQwenAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,Ug)).forEach(e=>o(this.extractQwenUserImageAttachment(e))),this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,".fileitem-btn, [class*='file-message-document'], .file-content-info")).forEach(e=>o(this.extractQwenUserFileAttachment(e))),n}extractQwenUserImageAttachment(e){const t=e instanceof HTMLImageElement?e:e.querySelector("img");if(!(t instanceof HTMLImageElement))return null;const n=this.extractQwenImageSource(t);if(!n)return null;const r=t.alt?.trim()||t.getAttribute("title")?.trim()||ga(n)||"uploaded image";return {kind:"image",name:r,source:n,type:pa(r)||ma(n)||"image"}}extractQwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=fa(t),i=this.extractQwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||ga(i)||"attachment";return {kind:"file",name:a,source:i,type:r||pa(a)||ma(i),sizeLabel:o}}formatQwenUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatQwenUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId()})}extractQwenAssistantImages(e){const t=e.closest(Mg)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,Hg).forEach(e=>{if(!(e instanceof HTMLImageElement))return;if(e.closest(".gh-root, .gh-user-query-markdown"))return;if(e.closest(".response-message-footer, .copy-response-button"))return;const t=this.extractQwenImageSource(e);t&&!r.has(t)&&(r.add(t),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`}));}),n}formatQwenAssistantImages(e,t){return Na(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}findUserMessageScope(e){const t=e.closest(".qwen-chat-message-user");return t||(e.matches(Ag)?e:e.closest(Ag)||e)}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractQwenImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeQwenExportSource(n,{allowDataImage:true});if(e)return this.preferOriginalQwenImageUrl(e)}return ""}extractQwenDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractQwenImageSource(e)),jg.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeQwenExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeQwenExportSource(e,t){const n=e.trim();if(!n||n.startsWith("#")||/^javascript:/i.test(n))return "";const r=va(n);if(!r)return "";if(/^data:image\/svg\+xml/i.test(r))return "";if(/^data:image\//i.test(r))return t.allowDataImage?r:"";if(/^data:/i.test(r))return r;if(!xa(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===window.location.hostname&&(vg.test(e.pathname)||/^\/(?:c|s)(?:\/|$)/i.test(e.pathname)))return "";if(/^img\.alicdn\.com$/i.test(e.hostname)&&/\.(?:apng|svg)(?:$|[?#])/i.test(e.pathname))return "";if(/\/(?:static|assets)\//i.test(e.pathname)&&!/\.(png|jpe?g|webp|gif|avif|pdf|docx?|xlsx?|pptx?|json|txt|csv)(?:$|[?#])/i.test(e.pathname))return ""}catch{return ""}return r}preferOriginalQwenImageUrl(e){if(!/^https?:\/\//i.test(e))return e;try{const t=new URL(e);if(t.searchParams.has("x-oss-process"))return t.searchParams.delete("x-oss-process"),t.toString()}catch{return e}return e}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getQwenAttachmentKeys(e){const t=ha(e.source),n=e.name.trim().toLowerCase(),r=e.type.trim().toLowerCase(),o=e.sizeLabel?.trim().toLowerCase()||"";return t?[`${e.kind}:source:${t}`]:[`${e.kind}:meta:${n}:${r}:${o}`]}normalizeQwenCodeBlocks(e){Array.from(e.querySelectorAll(Dg)).forEach(e=>{const t=this.extractQwenCodeBlockText(e);if(!t)return;const n=this.extractQwenCodeLanguage(e),r=document.createElement("pre"),o=document.createElement("code");n&&(o.className=`language-${n}`),o.textContent=t,r.appendChild(o),e.replaceWith(r);});}extractQwenCodeBlockText(e){const t=this.extractQwenMermaidSource(e);if(t)return t;const n=Array.from(e.querySelectorAll(".view-lines .view-line")).map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(n.length>0){const e=n.join("\n").replace(/\n+$/,"");return e.trim()?e:null}const r=e.querySelector(".qwen-markdown-code-body")||e.querySelector("[data-mode-id]")||e,o=this.normalizeQwenCodeLineText(r.textContent||"");return o.trim()?o:null}extractQwenMermaidSource(e){if(!this.isQwenMermaidCodeBlock(e))return null;const t=[],n=e=>{e&&(t.includes(e)||t.push(e));},r=e.querySelector(".qwen-markdown-code-body.mermaid");n(r),Array.from(e.querySelectorAll(".qwen-markdown-code-body.mermaid > div")).forEach(e=>n(e)),Array.from(e.querySelectorAll("[data-mode-id='mermaid']")).forEach(e=>n(e));let o=null;for(const i of t){const e=this.extractQwenCodeLinesFromRoot(i);e&&((!o||e.length>o.length)&&(o=e));}return o}isQwenMermaidCodeBlock(e){if("mermaid"===this.extractQwenCodeHeaderLabel(e).toLowerCase())return true;const t=e.querySelector(".qwen-markdown-code-body");return !!t?.classList.contains("mermaid")||null!==e.querySelector(".qwen-markdown-mermaid-chart-wrapper")}extractQwenCodeLanguage(e){const t=this.extractQwenCodeHeaderLabel(e).toLowerCase();if(t)return t;const n=e.querySelector(".qwen-markdown-code-body");if(!n)return "";const r=Array.from(n.classList).find(e=>"qwen-markdown-code-body"!==e&&!["monaco","editor","body"].includes(e.toLowerCase()));return r?.trim().toLowerCase()||""}extractQwenCodeHeaderLabel(e){const t=e.querySelector(".qwen-markdown-code-header");if(!t)return "";const n=Array.from(t.children);for(const o of n){if(!(o instanceof HTMLElement))continue;if(o.classList.contains("qwen-markdown-code-header-actions"))continue;const e=o.textContent?.trim()||"";if(e)return e}const r=t.firstElementChild;return r?.textContent?.trim()||""}extractQwenCodeLinesFromRoot(e){const t=Array.from(e.querySelectorAll(".view-lines .view-line"));if(0===t.length)return null;const n=t.map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(0===n.length)return null;const r=n.join("\n").replace(/\n+$/,"");return r.trim()?r:null}normalizeQwenCodeLineText(e){return e.replace(/\u00a0/g," ").replace(/\u200b/g,"").replace(/\r\n/g,"\n").replace(/\n/g,"").replace(/\s+$/g,"")}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}getThoughtBlocksForElement(e){const t=e.closest(Mg);return this.exportThoughtBlocks.get(e)||(t?this.exportThoughtBlocks.get(t):void 0)||[]}clearThoughtExportCache(){this.exportThoughtBlocks=new WeakMap;}async prepareMermaidBlocksForExport(){this.clearMermaidExportMarkers();const e=Array.from(document.querySelectorAll(Dg)).filter(e=>this.isQwenMermaidCodeBlock(e));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.getQwenMermaidActiveView(t),n=this.findQwenMermaidViewTab(t,"code"),r=this.findQwenMermaidViewTab(t,"preview");if("code"!==e&&n){try{n.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(n);}let o=await this.waitForMermaidCodeViewReady(t);!o&&"code"===e&&r&&n&&(this.simulateClick(r),await this.sleep(100),this.simulateClick(n),o=await this.waitForMermaidCodeViewReady(t)),o&&"code"!==e&&t.setAttribute(Bg,"true");}}async restoreMermaidBlocksAfterExport(){const e=Array.from(document.querySelectorAll(`${Dg}[${Bg}]`));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.findQwenMermaidViewTab(t,"preview");e&&"preview"!==this.getQwenMermaidActiveView(t)&&(this.simulateClick(e),await this.sleep(80)),t.removeAttribute(Bg);}}clearMermaidExportMarkers(){document.querySelectorAll(`${Dg}[${Bg}]`).forEach(e=>e.removeAttribute(Bg));}getQwenMermaidActiveView(e){const t=e.querySelector(Pg);if(!(t instanceof HTMLElement))return null;const n=Array.from(t.querySelectorAll(qg));for(const r of n){if(!(r instanceof HTMLElement))continue;const e=r.textContent?.trim().toLowerCase()||"";if(e&&r.className.includes("switch-active")){if(e.includes("code"))return "code";if(e.includes("preview"))return "preview"}}return null}findQwenMermaidViewTab(e,t){const n=e.querySelector(Pg);if(!(n instanceof HTMLElement))return null;const r=Array.from(n.querySelectorAll(qg));for(const o of r){if(!(o instanceof HTMLElement))continue;if((o.textContent?.trim().toLowerCase()||"").includes(t))return o}return null}async waitForMermaidCodeViewReady(e,t=2200){const n=Date.now();let r="",o=0;const i=this.getQwenMermaidExpectedLineCount(e);for(;Date.now()-nr.length?(r=t,o=0):t.length>0&&(o+=1);const n=r?r.split("\n").length:0;if((i>1?n>=i:n>0)&&o>=2)return true}await this.sleep(80);}const a=r?r.split("\n").length:0;return i>1?a>=i:r.length>0}getQwenMermaidExpectedLineCount(e){const t=Array.from(e.querySelectorAll(".margin-view-overlays .line-numbers")).map(e=>parseInt(e.textContent?.trim()||"",10)).filter(e=>Number.isFinite(e)&&e>0);return 0===t.length?0:Math.max(...t)}parseThoughtExportState(e){if(!e||"object"!=typeof e)return null;return {shouldCloseThoughtPanel:Boolean(e.shouldCloseThoughtPanel)}}async captureThoughtBlocksForMessage(e){const t=this.findThoughtTriggerForMessage(e);if(!t)return;const n=this.getThoughtPanelSignature();try{t.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(t);const r=await this.waitForThoughtPanelUpdate(n)||this.getVisibleThoughtPanel();if(!r||!this.isThoughtPanelForMessage(r,e))return;const o=this.extractThoughtBlockquotesFromPanel(r);o.length>0&&this.exportThoughtBlocks.set(e,o),await this.sleep(60);}findThoughtTriggerForMessage(e){const t=Array.from(e.querySelectorAll(".qwen-chat-thinking-tool-status-card-wraper .qwen-chat-tool-status-card, .qwen-chat-thinking-tool-status-card-wraper .qwen-chat-thinking-status-card-completed"));for(const n of t){if(!(n instanceof HTMLElement))continue;if(!this.isQwenElementVisible(n))continue;const e=n.querySelector(_g)?.textContent?.trim()||n.textContent?.trim()||"";if(e&&/已.*完成思考|已经完成思考/i.test(e))return n}return null}isThoughtPanelForMessage(e,t){const n=this.extractQwenAssistantMessageId(t);if(!n)return true;const r=Array.from(e.querySelectorAll("[data-phase-id]")).map(e=>e.getAttribute("data-phase-id")?.trim()||"").filter(Boolean);return 0===r.length||r.some(e=>e.includes(n))}extractQwenAssistantMessageId(e){const t=[e.id||"",e.querySelector("[id^='chat-response-message-']")?.id||"",e.querySelector("[id^='qwen-chat-message-assistant-']")?.id||""];for(const n of t){const e=n.match(/(?:qwen-chat-message-assistant|chat-response-message)-(.+)$/);if(e?.[1])return e[1]}return ""}getVisibleThoughtPanel(){const e=document.querySelectorAll(Og);for(const t of Array.from(e))if(this.isQwenElementVisible(t))return t;return null}getThoughtPanelSignature(e){const t=e||this.getVisibleThoughtPanel();if(!t)return null;const n=Array.from(t.querySelectorAll("[data-phase-id]")).map(e=>e.getAttribute("data-phase-id")?.trim()||"").filter(Boolean);if(n.length>0)return n.join("|");const r=this.extractThoughtBlockquotesFromPanel(t);return 0===r.length?null:r.join("\n\n")}async waitForThoughtPanelUpdate(e,t=2200){const n=Date.now();for(;Date.now()-ne.remove());const i=(Hi(n)||this.extractTextWithLineBreaks(n)).trim();i&&r.push(this.formatAsThoughtBlockquote(i,t));}return r}formatAsThoughtBlockquote(e,t){const n=e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">"),r=(t||"").trim();return ["> [Thoughts]",...r&&!/已.*完成思考|已经完成思考/i.test(r)?[`> **${r}**`,">"]:[],...n].join("\n")}async closeThoughtPanelIfNeeded(e=1500){const t=this.getVisibleThoughtPanel();if(!t)return;const n=t.querySelector(".qwen-chat-thinking-and-sources-header .anticon, .qwen-chat-thinking-and-sources-header [role='img']");if(!n||!this.isQwenElementVisible(n))return;this.simulateClick(n);const r=Date.now();for(;Date.now()-r [class*="model-item___"]')).filter(e=>e instanceof HTMLElement&&this.isQwenElementVisible(e))}findBestQwenModelItem(e,t){const n=this.normalizeModelKeyword(t);if(!n)return null;for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r))===n)return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).endsWith(n))return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).includes(n))return r}return null}getQwenModelItemName(e){return ((e.querySelector('[class*="model-item-name"] > span')||e.querySelector('[class*="model-item-name"]')||e).textContent||"").trim()}findQwenMoreTrigger(e){const t=e.querySelector(Zg);return t instanceof HTMLElement&&this.isQwenElementVisible(t)?t:null}async openQwenMoreMenu(e){const t=[e];[e.querySelector('[class*="view-more___"]'),e.querySelector('[class*="view-more-text"]'),e.querySelector('[class*="view-more-icon"]')].forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);});for(const n of t){this.dispatchQwenMoreMenuHover(n);let t=await this.waitForVisibleQwenSecondaryPopup(e,3,100);if(t)return t;if(this.simulateClick(n),t=await this.waitForVisibleQwenSecondaryPopup(e,4,120),t)return t}return this.waitForVisibleQwenSecondaryPopup(e,4,150)}async waitForVisibleQwenSecondaryPopup(e,t=8,n=150){for(let r=0;r{try{if(t.startsWith("pointer")&&"undefined"!=typeof PointerEvent)return void e.dispatchEvent(new PointerEvent(t,{...n,pointerType:"mouse",isPrimary:!0}));e.dispatchEvent(new MouseEvent(t,n));}catch{}});}clickQwenModelItem(e){this.simulateClick(e),window.setTimeout(()=>{document.body.click();},100);}normalizeModelKeyword(e){return (e||"").toLowerCase().replace(/\s+/g," ").trim()}isQwenElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}sleep(e){return new Promise(t=>window.setTimeout(t,e))}async showQwenModelLockFailure(e,t){try{const{showToast:n}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Bi);return {showToast:e}},void 0),{t:r}=await o(async()=>{const{t:e}=await Promise.resolve().then(()=>ue);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=r("modelLockFailedNoButton");break;case "menu_empty":i=r("modelLockFailedMenuEmpty");break;default:i=r("modelLockFailedNotFound").replace("{model}",e);}n(i,3e3);}catch(RS){console.error("[QwenAiAdapter] Failed to show model lock error:",RS);}}readCookieValue(e){const t=new RegExp(`(?:^|; )${e}=([^;]+)`),n=document.cookie.match(t);if(!n?.[1])return null;try{return decodeURIComponent(n[1]).trim()||null}catch{return n[1].trim()||null}}extractUidFromToken(e){if(!e)return null;try{const t=e.split(".")[1];if(!t)return null;const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(n.padEnd(4*Math.ceil(n.length/4),"=")),o=JSON.parse(r).id;return "string"==typeof o&&o.trim()?o.trim():null}catch{return null}}findUserContentRoot(e){return e.matches(Ig)?e:e.querySelector(Ig)||e}findAssistantContentRoot(e){return e.matches(Lg)?e:e.querySelector(Lg)||e}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return this.normalizeQwenCodeBlocks(n),n.querySelectorAll(`${$g}, ${zg}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}findModelTrigger(){const e=document.querySelector(Gg);if(e instanceof HTMLElement&&this.isVisibleActionElement(e))return e;const t=document.querySelector(Vg);if(!t)return null;const n=t.closest(".ant-dropdown-trigger, [role='button'], button, [tabindex]");return n instanceof HTMLElement?n:t}isStopLikeButton(e){if(!e)return false;const t=e.querySelector("use"),n=t?.getAttribute("xlink:href")||t?.getAttribute("href")||"",r=(e.innerText||e.textContent||"").trim().toLowerCase();return /stop/i.test(n)||r.includes("stop")||r.includes("停止")}findStopButton(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());if(e&&!this.isDisabledActionElement(e))return e;const t=document.querySelector(Ng);return this.isVisibleActionElement(t)&&!this.isDisabledActionElement(t)&&this.isStopLikeButton(t)?t:null}isVisibleActionElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isDisabledActionElement(e){return !(e instanceof HTMLElement)||(e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/\bdisabled\b/i.test(e.className||""))}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends vs{exportIncludeThoughts=void 0;match(){const e=window.location.hostname;return "www.qianwen.com"===e||"qianwen.com"===e}getSiteId(){return So}getName(){return "Qianwen"}getThemeColors(){return {primary:"#615ced",secondary:"#4b45c0"}}getNativeThemeCss(){return "\n/* =============================================\n * Qianwen (通义千问) 站点原生主题适配器 (Qianwen Theme Adapter)\n * ============================================= */\nbody {\n /* 主要背景 */\n --color-canvas-default: var(--gh-bg) !important;\n\n /* 次要/浮动层背景 (混入极低浓度主题色) */\n --color-canvas-subtle: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n /* 代码块与表格背景 */\n --color-inline-code-bg: var(--gh-bg-tertiary) !important;\n --color-table-head-th-bg: var(--gh-bg-secondary) !important;\n\n /* 边框体系 */\n --color-border-muted: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-row-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n\n /* 主色调/链接色 */\n --color-link: var(--gh-primary) !important;\n --color-link-border: var(--gh-primary) !important;\n --color-qk-link-border: var(--gh-primary) !important;\n}\n\n.bg-pc-sidebar {\n background-color: var(--color-canvas-subtle) !important;\n}\n\n"}getSessionId(){const e=window.location.pathname.match(Qh);return e?.[1]||super.getSessionId()}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,"")||"/";return "/"===e||"/chat"===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&Qh.test(window.location.pathname)}getCurrentCid(){const e=localStorage.getItem("qianwen-uniq-id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=this.getDocumentConversationTitle()||"";if(!e)return null;const t=e.replace(/\s*[-|]\s*通义千问$/i,"").replace(/\s*[-|]\s*Qwen$/i,"").replace(/\s*[-|]\s*Qianwen$/i,"").trim();return !t||/^(通义千问|Qwen|Qianwen)$/i.test(t)?null:t}getNewTabUrl(){return "https://www.qianwen.com"}getCurrentConversationInfo(){return Kh.test(window.location.pathname)?null:super.getCurrentConversationInfo()}getConversationTitle(){return this.getSessionName()}getTextareaSelectors(){return ['[class*="chatTextarea"]',`${ug} [contenteditable="true"]`,'[data-slate-editor="true"][contenteditable="true"]','div[role="textbox"][contenteditable="true"]',"textarea"]}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!e.closest(mg)&&(!!(e.isContentEditable||e instanceof HTMLTextAreaElement)&&!(!e.closest(ug)&&!e.matches('[data-slate-editor="true"]'))))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),true}try{if(document.execCommand("selectAll",!1),document.execCommand("insertText",!1,e))return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{}return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){if(e.focus(),e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),void e.dispatchEvent(new Event("change",{bubbles:true}))}try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{}e.textContent="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}getSubmitButtonSelectors(){return ['[class*="operateBtn"]','[data-icon-type="qwpcicon-sendChat"]',"button[type='submit']"]}findSubmitButton(e){const t=[e?.closest(ug),e?.parentElement,e?.closest("div"),document.body].filter(Boolean);for(const n of t){const e=n.querySelectorAll('[class*="operateBtn"], [data-icon-type="qwpcicon-sendChat"]');for(const t of Array.from(e)){const e=t.closest('[class*="operateBtn"], button, [role="button"]');if(e&&this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e}}return super.findSubmitButton(e)}getNewChatButtonSelectors(){return ['[class*="newChatButton"]']}getScrollContainer(){const e=[hg,gg];for(const r of e){const e=document.querySelectorAll(r);for(const t of Array.from(e)){const e=t;if(e.scrollHeight>e.clientHeight)return e}}const t=document.querySelector(gg);if(!t)return null;let n=t;for(;n&&n!==document.body;){if(n.scrollHeight>n.clientHeight)return n;n=n.parentElement;}return null}getResponseContainerSelector(){return `${gg}, ${hg}`}getChatContentSelectors(){return [Xh,eg]}getUserQuerySelector(){return Xh}getLatestReplyText(){const e=document.querySelectorAll(eg),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.extractUserTextParts(e);if(t.length>0)return t.join("\n\n");const n=this.findUserQueryContentRoot(e);if(!n)return "";const r=n.cloneNode(true);return r.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.normalizeUserQueryText(this.extractTextWithLineBreaks(r)).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserQueryContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-user-query-markdown-qianwen gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}async prepareConversationExport(e){return this.exportIncludeThoughts=e.includeThoughts,null}async restoreConversationAfterExport(e,t){this.exportIncludeThoughts=void 0;}async extractExportMessages(e){const t=this.extractQianwenExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractQianwenExportMessages(e))}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(gg)||document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${Xh}, ${eg}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(Xh)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(eg));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(mg)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t{r++;const i=this.findModelSelectorTrigger();if(!i)return void(r<10?setTimeout(o,500):console.warn(`Ophel: Qianwen model selector not found for "${e}".`));if(this.normalizeText(this.getModelName()||"").includes(n))t?.();else {try{localStorage.setItem(Yh,"1");}catch{}this.simulateClick(i),setTimeout(async()=>{let i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n);!a&&this.expandMoreModels()&&(await new Promise(e=>setTimeout(e,400)),i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n)),a?(this.simulateClick(a),setTimeout(()=>{document.body.click(),t?.();},150)):r<10?setTimeout(o,500):(document.body.click(),console.warn(`Ophel: Qianwen model "${e}" not found.`));},300);}};o();}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];for(const n of t)e.dispatchEvent(new PointerEvent(n,{bubbles:true,cancelable:true,view:window,pointerId:1}));}getWidthSelectors(){const e=["width: 100% !important;","min-width: 0 !important;","--max-message-list-width: 100% !important;","--min-message-list-width: 0px !important;"].join(" ");return [{selector:'[class*="scrollOutWrapper"]',property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:`${gg}`,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:'[class*="auto-center-wrapper"]',property:"max-width",extraCss:e},{selector:'[class*="inputMotionCarrier"]',property:"max-width",extraCss:"width: 100% !important;"},{selector:'[class*="inputOutWrap"]',property:"max-width",value:"100%",extraCss:"width: 100% !important;"},{selector:'[class*="answerItem"] [class*="containerWrap"]',property:"max-width"},{selector:'[class*="questionItem"], .chat-question-wrap',property:"width",extraCss:"margin-right: 0 !important"},{selector:ng,property:"width",value:"100%",extraCss:"max-width: 100% !important; box-sizing: border-box !important;",noCenter:true}]}getUserQueryWidthSelectors(){const e="margin-left: auto !important; margin-right: 0 !important;";return [{selector:`${Xh} ${tg}`,property:"max-width",extraCss:e,noCenter:true},{selector:Jh,property:"max-width",extraCss:e,noCenter:true}]}getZenModeConfig(){return {hide:[pg]}}getCleanModeConfig(){return {hide:["#ice-container .root-G6nVVr"]}}getMarkdownFixerConfig(){return {selector:`${eg} .qk-md-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(eg);if(!t)return false;const n=document.querySelectorAll(eg);return t===n[n.length-1]}}}extractQianwenExportMessages(e){const t=this.getExportRoot(),n=this.collectQianwenExportTurns(t),r=n.length>0?n:[t],o=[];return r.forEach(t=>{this.getOrderedQianwenMessages(t).forEach(({role:t,element:n})=>{const r=("user"===t?this.extractUserQueryExportContentWithAssets(n,e):this.extractAssistantResponseTextWithAssets(n,e)).trim();r&&o.push({role:t,content:r});});}),o}getExportRoot(){return document.querySelector(gg)||document.querySelector(hg)||document.body}collectQianwenExportTurns(e){const t=this.queryElementsIncludingSelf(e,".chat-round[data-chat], [data-chat-list-key]");return this.collectTopLevelBlocks(t).filter(e=>this.getOrderedQianwenMessages(e).length>0)}getOrderedQianwenMessages(e){const t=[],n=new Set,r=(e,r)=>{!r||n.has(r)||this.shouldSkipExportElement(r)||(n.add(r),t.push({role:e,element:r}));},o=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,`${Xh}, [data-chat-question-wrap]`)),i=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,eg));return [...o.map(e=>({role:"user",element:e})),...i.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element)).forEach(({role:e,element:t})=>r(e,t)),t}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserTextParts(e).join("\n\n").trim(),r=this.extractQianwenUserAttachments(e);if(0===r.length)return n||this.extractUserQueryText(e);const o=this.formatQianwenUserImageAttachments(r,t),i=this.formatQianwenUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatQianwenAssistantImages(this.extractQianwenAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport()?this.extractThoughtBlockquotes(e):[],n=this.findAssistantContentRoot(e).cloneNode(true);n.querySelectorAll([cg,lg,"picture","img"].join(", ")).forEach(e=>e.remove());const r=`${mg}, [class*="thinkingTitle"]`;n.querySelectorAll(r).forEach(e=>e.remove());const o=(Hi(n)||this.extractTextWithLineBreaks(n)).trim();if(t.length>0){const e=t.join("\n\n");return o?`${e}\n\n${o}`:e}return o}extractUserTextParts(e){const t=this.findUserMessageScope(e),n=this.queryElementsIncludingSelf(t,".question-text-card"),r=[],o=new Set;return n.forEach(e=>{if(e.closest(".gh-user-query-markdown"))return;const t=e.cloneNode(true);t.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove());const n=this.normalizeUserQueryText(this.extractTextWithLineBreaks(t)).trim();n&&!o.has(n)&&(o.add(n),r.push(n));}),r}extractQianwenUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=[e.kind,ha(e.source),e.name.trim().toLowerCase(),e.type.trim().toLowerCase(),e.sizeLabel||""].join(":");r.has(t)||(r.add(t),n.push(e));};return this.queryElementsIncludingSelf(t,og).forEach(e=>o(this.extractQianwenUserImageAttachment(e))),this.queryElementsIncludingSelf(t,ig).forEach(e=>o(this.extractQianwenUserFileAttachment(e))),n}extractQianwenUserImageAttachment(e){const t=e.querySelector("img");if(!(t instanceof HTMLImageElement))return null;const n=this.extractQianwenImageSource(t);if(!n)return null;const r=t.alt?.trim()||t.getAttribute("title")?.trim()||ga(n)||"uploaded image";return {kind:"image",name:r,source:n,type:pa(r)||ma(n)}}extractQianwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=fa(t),i=this.extractQianwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||ga(i)||"attachment";return {kind:"file",name:a,source:i,type:r||pa(a)||ma(i),sizeLabel:o}}formatQianwenUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatQianwenUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId()})}extractQianwenAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,sg).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractQianwenImageSource(e);t&&!r.has(t)&&(r.add(t),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`}));}),n}formatQianwenAssistantImages(e,t){return Na(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}findUserMessageScope(e){return e.matches(Xh)||e.matches("[data-chat-question-wrap]")?e:e.closest(Xh)||e.closest("[data-chat-question-wrap]")||e}findAssistantContentRoot(e){return e.matches(ag)?e:e.querySelector(ag)||e}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractQianwenImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeQianwenExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractQianwenDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractQianwenImageSource(e)),dg.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeQianwenExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeQianwenExportSource(e,t){const n=va(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!xa(n))return "";try{const e=new URL(n);if(/^g\.alicdn\.com$/i.test(e.hostname))return "";if(/\/static\//i.test(e.pathname)&&!/\.(png|jpe?g|webp|gif|avif)$/i.test(e.pathname))return ""}catch{return ""}return n}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll('[class*="thinkingContent"]')),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="thinkingTitle"], [class*="thinkingHeader"], .qc-thinking-header, button, svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=(Hi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractAssistantPlainText(e){const t=e.cloneNode(true);return t.querySelectorAll(`${mg}, .qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], button, [role='button'], svg, .qk-md-table-action, .qk-md-copy-icon, [aria-hidden='true'], [class*="answerToolsContent"], [class*="functionArea"]`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findUserQueryContentRoot(e){if(e.matches(".question-text-card"))return e;const t=e.querySelector(".question-text-card");return t instanceof HTMLElement?t:e.matches(tg)?e:e.querySelector(tg)||e}normalizeUserQueryText(e){return e.replace(/\u00a0/g," ")}findModelSelectorTrigger(){return Array.from(document.querySelectorAll('[aria-haspopup="dialog"][aria-controls], [aria-haspopup="dialog"][data-state]')).filter(e=>{const t=e;if(!this.isVisibleElement(t))return false;if(t.closest(pg))return false;if(t.closest(ug))return false;const n=t.getBoundingClientRect(),r=t.innerText?.trim()||t.textContent?.trim()||"";return n.top<180&&n.width>0&&n.height>0&&r.length>0})[0]||null}findVisibleModelDialogItems(){const e=Array.from(document.querySelectorAll(bg)).filter(e=>this.isVisibleElement(e));if(0===e.length)return [];const t=[];return e.forEach(e=>{const n=e.querySelectorAll(yg);for(const r of Array.from(n)){const e=r;this.isVisibleElement(e)&&(e.innerText?.trim()&&t.push(e));}}),t}findBestMatchingDialogItem(e,t){if(0===e.length)return null;const n=this.normalizeText(t);for(const r of e){const e=this.normalizeText(r.innerText||r.textContent||"");if(!e)continue;if(e.split("\n")[0].trim()===n)return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").split("\n")[0].trim().endsWith(n))return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").includes(n))return r}return null}expandMoreModels(){const e=Array.from(document.querySelectorAll(bg)).filter(e=>this.isVisibleElement(e));for(const t of e){const e=t.querySelectorAll("button, div, span");for(const t of Array.from(e)){const e=t;if(!this.isVisibleElement(e))continue;const n=this.normalizeText(e.innerText||e.textContent||"");if(n&&((n.includes(this.normalizeText("查看更多模型"))||n.includes(this.normalizeText("view more models"))||n.includes(this.normalizeText("更多模型")))&&!n.includes(this.normalizeText("收起"))&&!n.includes(this.normalizeText("collapse"))))return this.simulateClick(e),true}}return false}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}normalizeText(e){return (e||"").replace(/\s+/g," ").trim().toLowerCase()}isDisabledActionButton(e){const t=this.getElementClassName(e);return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}getElementClassName(e){return "string"==typeof e.className?e.className:""}},new class extends vs{exportIncludeThoughtsOverride=null;match(){return window.location.hostname===Jg}getSiteId(){return ko}getName(){return "元宝"}getThemeColors(){return {primary:"#1677ff",secondary:"#0b5bd3"}}supportsFormulaCopy(){return false}getTextareaSelectors(){return ['.agent-dialogue__content--common__input .ql-editor[contenteditable="true"], #search-bar .ql-editor[contenteditable="true"], .ql-editor[contenteditable="true"]']}isValidTextarea(e){return !!super.isValidTextarea(e)&&("true"===e.getAttribute("contenteditable")&&!!e.closest(".agent-dialogue__content--common__input"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();try{if(document.execCommand("selectAll",!1),!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false");return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus();try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{e.textContent="";}e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,Math.max(t.width-1,1))),r=t.top+Math.max(1,Math.min(t.height/2,Math.max(t.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r},i=t=>"function"==typeof PointerEvent&&e.dispatchEvent(new PointerEvent(t,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));i("pointerenter"),i("pointerover"),i("pointermove"),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new MouseEvent("mousemove",o)),i("pointerdown"),e.dispatchEvent(new MouseEvent("mousedown",o)),i("pointerup"),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}getSubmitButtonSelectors(){return [np]}findSubmitButton(){const e=document.querySelector("#yuanbao-send-btn");if(this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e;const t=Array.from(document.querySelectorAll(np));for(const n of t){const e=n;if(this.isVisibleElement(e)&&(!this.isDisabledActionButton(e)&&!this.isStopLikeButton(e)))return e}return null}getSessionId(){const e=window.location.pathname.match(ep);return e?.[2]||""}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,""),t=e.match(ep);return t?!t[2]:""===e||"/"===e}isSharePage(){return window.location.pathname.startsWith("/s/")}getNewTabUrl(){const e=this.getAgentId();return e?`https://${Jg}/chat/${e}`:`https://${Jg}/`}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*(腾讯元宝|元宝)$/i,"").trim();return !n||/^(腾讯元宝|元宝)$/i.test(n)?null:n}getCurrentCid(){const e=localStorage.getItem("yb_user_id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getConversationTitle(){const e=document.querySelector(ip);return e?this.extractConversationTitle(e):null}getCurrentConversationInfo(){const e=super.getCurrentConversationInfo();if(!e)return null;const t=document.querySelector(ip),n=t?this.extractConversationInfo(t,this.getCurrentCid()||void 0):null;return n&&n.id===e.id?{...e,title:n.title||e.title,url:n.url||e.url,cid:n.cid??e.cid,isActive:n.isActive??e.isActive,isPinned:n.isPinned??e.isPinned}:e}getConversationList(){const e=this.getCurrentCid()||void 0,t=document.querySelectorAll(op),n=new Map;return t.forEach(t=>{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:op,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(ap)||e}}getSidebarScrollContainer(){return document.querySelector(".yb-nav__content")}navigateToConversation(e,t){const n=this.captureConversationNavigationState(),r=this.findConversationRowById(e);if(r){const o=r.querySelector(ap),i=this.resolveClickableTarget(o)||r.querySelector("a[href]")||this.resolveClickableTarget(r)||r;return this.simulateClick(i),window.setTimeout(()=>{this.hasConversationNavigationChanged(n)||super.navigateToConversation(e,t||this.buildConversationUrl(e));},800),true}return super.navigateToConversation(e,t||this.buildConversationUrl(e))}async deleteConversationOnSite(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Lp}}catch(RS){return console.error(`[YuanbaoAdapter] deleteConversationOnSite error for "${e.id}":`,RS),{id:e.id,success:false,method:"none",reason:Np}}}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt.clientHeight)return t;const e=this.findScrollableParent(t);if(e)return e}return super.getScrollContainer()}getResponseContainerSelector(){return sp}getChatContentSelectors(){return [lp,cp]}getUserQuerySelector(){return lp}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, input, label").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}getLatestReplyText(){const e=document.querySelectorAll(cp),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(sp)||this.getScrollContainer()||document,o=Array.from(r.querySelectorAll(`${lp}, ${cp}`)).filter(e=>!e.closest(".gh-root")),i=[];return o.forEach((r,a)=>{if(r.matches(lp)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=o.slice(a+1).find(e=>e.matches(cp));s=e?this.extractAssistantPlainText(e).length:0;}return void i.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const o=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(o)||o>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractYuanbaoExportMessages(e))}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [rp]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/chat/"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:":root",property:Ep,noCenter:true},{selector:":root",property:"--hunyuan-chat-list-width",value:`min(100%, var(${Ep}))`,noCenter:true}]}async toggleTheme(e){try{return localStorage.setItem(tp,e),window.dispatchEvent(new StorageEvent("storage",{key:tp,newValue:e,storageArea:localStorage})),document.documentElement.style.colorScheme=e,!0}catch(RS){return console.error("[YuanbaoAdapter] toggleTheme error:",RS),false}}getModelName(){const e=document.querySelector(yp);return e?.textContent?.trim()||""||null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".ybc-model-select-button",yp],menuItemSelector:".ybc-model-select-dropdown-popup .t-dropdown__item, .ybc-model-select-dropdown .t-dropdown__item, .t-popup .t-dropdown__item",checkInterval:1e3,maxAttempts:10,menuRenderDelay:200}}getNewChatButtonSelectors(){return ['.yb-common-nav__trigger[data-desc="new-chat"]']}getZenModeConfig(){return {hide:[".yb-nav__content-wrapper",".yb-nav-fixed.yb-nav-fixed--pc-ctx"],styles:[{selector:".agent-dialogue__content--common__input-box",property:"padding-bottom",value:"0"},{selector:".yb-nav--push.yb-nav--open~.yb-layout__content, .yb-nav--push.yb-nav--open~.yb-layout__content-skeleton",property:"margin-left",value:"0"}]}}getCleanModeConfig(){return {hide:[".agent-dialogue__content-copyright",".yb__pc_download",".agent-dialogue__tool"]}}getAgentId(){const e=window.location.pathname.match(ep);if(e?.[1])return e[1];const t=document.querySelector(`${op}[dt-agent-id]`)?.getAttribute("dt-agent-id")||document.querySelector("[dt-agent-id]")?.getAttribute("dt-agent-id");return t?.trim()||null}buildConversationUrl(e){const t=this.getAgentId();return t?`https://${Jg}/chat/${t}/${e}`:`https://${Jg}/`}extractConversationInfo(e,t){const n=e.closest(op)||(e.matches(op)?e:null);if(!n)return null;const r=n.getAttribute("dt-cid")||n.querySelector("[data-item-id]")?.getAttribute("data-item-id")||"";if(!r)return null;return {id:r,title:this.extractConversationTitle(n),url:this.buildConversationUrl(r),cid:t,isActive:n.classList.contains("active"),isPinned:this.isPinnedConversation(n)}}extractConversationTitle(e){const t=e.querySelector(ap);return (t?.getAttribute("data-item-name")||t?.dataset?.itemName||t?.textContent||"").trim()}isPinnedConversation(e){return null!==e.querySelector(".yb-recent-conv-list__item-name.isTop, .yb-recent-conv-list__chat-top .icon-yb-ic_pin_16")}findScrollableParent(e){let t=e?.parentElement||null;for(;t;){const e=window.getComputedStyle(t);if(/(auto|scroll)/i.test(e.overflowY)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}findUserContentRoot(e){return e.querySelector(".agent-chat__bubble--human .hyc-content-text, .agent-chat__bubble--human .agent-chat__bubble__content")||e.querySelector(".agent-chat__bubble__content")||e}findAssistantContentRoot(e){const t=this.findAssistantBodyRoot(e);if(t)return t;const n=this.findAssistantMarkdownRoot(e);return n||(e.querySelector(".agent-chat__speech-text")||e.querySelector(".agent-chat__bubble__content")||e)}findAssistantMarkdownRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,wp.slice(0,2));if(t)return t;if(e.matches(dp)&&!this.isThoughtElement(e))return e;const n=Array.from(e.querySelectorAll(dp));return n.find(e=>!this.isThoughtElement(e))||n[0]||null}extractYuanbaoExportMessages(e){const t=document.querySelector(sp)||this.getScrollContainer()||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${lp}, ${cp}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches(lp)?"user":"assistant";return {role:n,content:("user"===n?this.extractUserQueryExportContentWithAssets(t,e):this.extractAssistantResponseTextWithAssets(t,e)).trim()}}).filter(e=>e.content.length>0)}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserQueryText(e),r=this.extractYuanbaoUserAttachments(e);if(0===r.length)return n;const o=this.formatYuanbaoUserImageAttachments(r,t),i=this.formatYuanbaoUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatYuanbaoAssistantImages(this.extractYuanbaoAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport(),n=e.cloneNode(true);n.querySelectorAll([hp,up,fp].join(", ")).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove());const r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(xp).forEach(e=>e.remove());const o=this.findAssistantBodyRoot(n)||n,i=Hi(o).trim()||this.extractTextWithLineBreaks(o).trim();if(t&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}extractYuanbaoUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getYuanbaoAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return t.querySelectorAll(gp).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractYuanbaoUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,pp).forEach(e=>{o(this.extractYuanbaoUserFileAttachment(e));}),n}extractYuanbaoUserImageAttachment(e){const t=this.extractYuanbaoImageSource(e);if(!t)return null;const n=e.alt?.trim()||e.getAttribute("title")?.trim()||ga(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:pa(n)||ma(t)||"image"}}extractYuanbaoUserFileAttachment(e){if(e.closest(".hyc-component-multi-modal__image, .hyc-content-img"))return null;const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=fa(t),i=this.extractYuanbaoDownloadableSource(e,{allowDataImage:false,includeImages:false});if(!n&&!i)return null;const a=n||ga(i,{ignoreGenericDownload:true})||this.extractResourceIdFilename(i)||"attachment";return {kind:"file",name:a,source:i,type:r||pa(a)||ma(i),sizeLabel:o}}formatYuanbaoUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatYuanbaoUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId()})}extractYuanbaoAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,mp).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractYuanbaoImageSource(e),o=ha(t);t&&!r.has(o)&&(r.add(o),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`,extensionHint:this.extractYuanbaoImageExtensionHint(e)}));}),n}formatYuanbaoAssistantImages(e,t){return Na(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractYuanbaoImageSource(e){const t=[e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeYuanbaoExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractYuanbaoDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractYuanbaoImageSource(e)),bp.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeYuanbaoExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeYuanbaoExportSource(e,t){const n=va(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!xa(n))return "";try{const e=new URL(n,window.location.href);if(e.hostname===Jg&&/\/(?:static|assets)\//i.test(e.pathname))return "";if(/\.(?:svg|ico)$/i.test(e.pathname)&&/(?:icon|logo|sprite)/i.test(e.pathname))return ""}catch{return ""}return n}extractYuanbaoImageExtensionHint(e){return [e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.alt||""].map(e=>ma(e)||pa(e)).find(Boolean)||""}findUserMessageScope(e){return e.matches(lp)?e:e.closest(lp)||e}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getYuanbaoAttachmentKeys(e){const t=[],n=ha(e.source),r=e.name.trim().toLowerCase(),o=e.type.trim().toLowerCase(),i=e.sizeLabel?.trim().toLowerCase()||"";return n&&t.push(`${e.kind}:source:${n}`),r&&o&&t.push(`${e.kind}:name-type:${r}:${o}`),r&&i&&t.push(`${e.kind}:name-size:${r}:${i}`),t.length>0?t:[`${e.kind}:fallback:${r}:${o}`]}extractResourceIdFilename(e){if(!e)return "";try{const t=new URL(e,window.location.href).searchParams.get("resourceId");return t?`attachment-${t.slice(0,12)}`:""}catch{return ""}}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(`${hp}, ${up}`).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findAssistantBodyRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,wp);if(t)return t;const n=this.findAssistantMarkdownRoot(e);if(n instanceof HTMLElement)return n;const r=e.querySelector(".agent-chat__speech-text");if(r&&!this.isThoughtElement(r))return r;const o=e.querySelector(".agent-chat__bubble__content");return o&&!this.isThoughtElement(o)?o:e instanceof HTMLElement?e:null}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(vp)).filter(e=>!e.parentElement?.closest(vp)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(`${up}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const t=(Hi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}findFirstAssistantNodeOutsideThoughts(e,t){for(const n of t){if(e.matches(n)&&!this.isThoughtElement(e))return e;const t=Array.from(e.querySelectorAll(n)).find(e=>e instanceof HTMLElement&&!this.isThoughtElement(e));if(t)return t}return null}isThoughtElement(e){return null!==e.closest(xp)}findConversationRowById(e){const t=document.querySelector(`${op}[dt-cid="${e}"]`);if(t)return t;const n=Array.from(document.querySelectorAll(op));for(const r of n){const t=this.extractConversationInfo(r,this.getCurrentCid()||void 0);if(t?.id===e)return r}return null}async deleteConversationViaUi(e){let t=this.findConversationRowById(e);if(t||(await this.loadAllConversations(),t=this.findConversationRowById(e)),!t)return false;const n=this.captureConversationNavigationState();t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let r=this.findConversationMenuTrigger(t);if(!r)return false;const o=await this.openConversationAction(t,r);if(!o)return false;let i="dialog"===o.kind?o.dialog:null;if("menu"===o.kind){const e=await this.waitForDeleteMenuItem(o.menu,2e3);if(!e)return document.body.click(),false;this.simulateClick(e),i=await this.waitForDialogOpen(1200);}if(i){const e=await this.waitForDeleteConfirmButton(i,2e3);if(!e)return false;this.simulateClick(e);}return !!(await this.waitForConversationDeleteResult(e,n,4500))||!!i&&(await this.waitForDialogClosed(1200),this.waitForConversationDeleteResult(e,n,800))}revealConversationActions(e){const t=e.querySelector(ap),n=[e,t].filter(e=>e instanceof HTMLElement);for(const r of n){const e=r.getBoundingClientRect(),t=e.left+Math.max(1,Math.min(e.width/2,Math.max(e.width-1,1))),n=e.top+Math.max(1,Math.min(e.height/2,Math.max(e.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,clientX:t,clientY:n};if("function"==typeof PointerEvent)for(const i of ["pointerenter","pointerover","pointermove"])r.dispatchEvent(new PointerEvent(i,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));for(const i of ["mouseenter","mouseover","mousemove"])r.dispatchEvent(new MouseEvent(i,o));}}findConversationMenuTrigger(e){return this.getConversationActionCandidates(e)[0]||null}getConversationActionCandidates(e,t){const n=Array.from(e.querySelectorAll(kp)),r=[],o=new Set,i=(e,t=0)=>{if(!(e instanceof HTMLElement)||o.has(e))return;o.add(e);const n=this.getConversationActionScore(e);Number.isFinite(n)&&r.push({element:e,score:n+t});};i(t,25);for(const a of n)i(a);return r.sort((e,t)=>t.score-e.score),r.map(({element:e})=>e)}getConversationActionScore(e){if(e.closest(ap))return Number.NEGATIVE_INFINITY;if(e.closest(".t-checkbox, [role='checkbox']"))return Number.NEGATIVE_INFINITY;if(e.matches("input, label"))return Number.NEGATIVE_INFINITY;const t=this.getConversationActionSignal(e),n=window.getComputedStyle(e);let r=0;return e.matches('[aria-haspopup="menu"], [aria-haspopup="listbox"]')&&(r+=120),/(ellipsis|more[_-]?vert|icon-more|icon-menu|menu)/i.test(t)&&(r+=70),/(delete|删除)/i.test(t)&&(r+=45),/(action|operate|dropdown|popup)/i.test(t)&&(r+=15),e.matches("button, [role='button']")&&(r+=10),e.querySelector(".iconfont-yb, .yb-icon, svg")&&(r+=5),"none"!==n.pointerEvents&&(r+=5),this.isVisibleElement(e)&&(r+=30),r}async openConversationAction(e,t){let n=t;for(let r=0;r<4;r+=1){document.body.click(),await this.sleep(80),this.revealConversationActions(e);const t=this.getConversationActionCandidates(e,n);if(0===t.length)return null;n=t[0]||null;for(const e of t){if(!e.isConnected)continue;this.simulateClick(e);const t=await this.waitForConversationActionOpen(e,1e3);if(t)return t}}return null}async waitForConversationActionOpen(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)&&this.isDropdownMenuContainer(e));return n.length>0?n[n.length-1]:null}isDropdownMenuContainer(e){return !!e.matches(Cp)||!!e.querySelector(Cp)}async waitForDeleteMenuItem(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>e.className.includes("theme-error"))||t.find(e=>Ap.test(this.getElementText(e)));if(n)return n;await this.sleep(80);}return null}async waitForDialogOpen(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e))||null}async waitForDeleteConfirmButton(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>{const t=this.getElementText(e);return Mp.test(t)&&!Ip.test(t)})||t.find(e=>/primary|danger/i.test(e.className));if(n)return n;await this.sleep(80);}return null}async waitForDialogClosed(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e)))return true;await this.sleep(80);}return false}async waitForConversationDeleteResult(e,t,n){const r=Date.now(),o=t.sessionId===e;for(;Date.now()-rwindow.setTimeout(t,e))}findStopButton(){const e=Array.from(document.querySelectorAll(rp));for(const t of e){const e=t;if(this.isVisibleElement(e)&&this.isStopLikeButton(e))return e}return null}isDisabledActionButton(e){if(!(e instanceof HTMLElement))return true;const t="string"==typeof e.className?e.className:"";return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isStopLikeButton(e){if(!(e instanceof HTMLElement))return false;if(e.querySelector("span.icon-send, .icon-send"))return false;if(e.querySelector("rect"))return true;const t=e.innerText?.trim()||e.textContent?.trim()||"";return /停止|stop/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends vs{exportIncludeThoughtsOverride=null;exportUserAttachmentsByMessageId=new Map;exportShareTitle=null;match(){return window.location.hostname===Dp}getSiteId(){return To}getName(){return "Z.ai"}getThemeColors(){return {primary:"#0881F0",secondary:"#0B6ED8"}}getTextareaSelectors(){return [...Bp]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${$p}:not([disabled])`]}findSubmitButton(){const e=document.querySelector($p);return !e||e.hasAttribute("disabled")||null===e.offsetParent?null:e}getResponseContainerSelector(){return Fp}getConversationContentContainer(e){const t=document.querySelector(this.getResponseContainerSelector())||document.querySelector(zp);if(t)return t;const n=this.getScrollContainer();if(n)return n;return Boolean(document.body.querySelector(`${Up}, ${Wp}`))&&(this.isSharePage()||e?.allowBodyFallback)||e?.allowBodyFallback?document.body:null}getChatContentSelectors(){return [Up,Wp]}getUserQuerySelector(){return Up}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractZaiUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}getExportConfig(){return {userQuerySelector:Gp,assistantResponseSelector:Vp,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportMarkers(),this.clearExportAttachmentCache();const t=this.getConversationContentContainer({allowBodyFallback:true})||document.body;return this.markExportMessages(t),await this.prepareExportAttachmentCache(t),null}async restoreConversationAfterExport(e,t){this.clearExportMarkers(),this.exportIncludeThoughtsOverride=null,this.clearExportAttachmentCache();}async extractExportMessages(e){const t=this.extractZaiExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractZaiExportMessages(e))}clearExportMarkers(){document.querySelectorAll(`[${jp}]`).forEach(e=>e.removeAttribute(jp));}shouldSkipExportElement(e){return !!e.closest(".gh-root")||(!!e.closest(".gh-user-query-markdown")||!!e.closest(Qp))}collectExportMessages(e){const t=Array.from(e.querySelectorAll(Up)),n=this.collectTopLevelBlocks(t).filter(e=>!this.shouldSkipExportElement(e)),r=Array.from(e.querySelectorAll(Wp));return {users:n,assistants:this.collectTopLevelBlocks(r).filter(e=>!this.shouldSkipExportElement(e)&&!e.closest(Up))}}markExportMessages(e){const{users:t,assistants:n}=this.collectExportMessages(e);t.forEach(e=>e.setAttribute(jp,"user")),n.forEach(e=>e.setAttribute(jp,"assistant"));}extractZaiExportMessages(e){const t=this.getConversationContentContainer({allowBodyFallback:true})||document.body,{users:n,assistants:r}=this.collectExportMessages(t);return [...n.map(e=>({role:"user",element:e})),...r.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element)).map(({role:t,element:n})=>({role:t,content:("user"===t?this.extractZaiUserQueryExportContent(n,e):this.extractAssistantResponseText(n)).trim()})).filter(e=>e.content.length>0)}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}shouldIncludeThoughtsInExport(){return "boolean"!=typeof this.exportIncludeThoughtsOverride||this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> **💭 思考过程**",">",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractThoughtBlockquotesFromElement(e){const t=[],n=[],r=e=>{const t=document.createElement("div");return Array.from(e.childNodes).forEach(e=>t.appendChild(e.cloneNode(true))),Hi(t)||this.extractTextWithLineBreaks(e)},o=Array.from(e.querySelectorAll("blockquote[slot='content'], .thinking-block blockquote, .thinking-chain-container blockquote"));if(o.length>0){const e=this.collectTopLevelBlocks(o);for(const o of e){const e=r(o).trim();e&&t.push(this.formatAsThoughtBlockquote(e));const i=o.closest(".thinking-chain-container")||o.closest(".thinking-block")||o;n.push(i);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}const i=Array.from(e.querySelectorAll(Qp)),a=this.collectTopLevelBlocks(i);for(const s of a){const e=r(s.querySelector("blockquote[slot='content']")||s.querySelector("blockquote")||s).trim();e&&t.push(this.formatAsThoughtBlockquote(e)),n.push(s);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}extractAssistantResponseText(e){const t=e.cloneNode(true),n=this.shouldIncludeThoughtsInExport(),r=this.extractThoughtBlockquotesFromElement(t),o=n?r.blocks:[];r.removalNodes.length>0&&r.removalNodes.forEach(e=>e.remove()),t.querySelectorAll(Qp).forEach(e=>e.remove());const i=this.findAssistantBodyRoot(t).cloneNode(true);i.querySelectorAll(Zp).forEach(e=>e.remove());const a=(Hi(i)||this.extractTextWithLineBreaks(i)).trim();if(o.length>0){const e=o.join("\n\n");return a?`${e}\n\n${a}`:e}return a}findAssistantBodyRoot(e){if(this.isAssistantBodyElement(e))return e;const t=Array.from(e.querySelectorAll(Hp)).filter(e=>!e.closest(Up)&&!e.closest(Qp)&&!e.closest(".gh-root"));return this.collectTopLevelBlocks(t)[0]||e}isAssistantBodyElement(e){return e.matches(Hp)&&!e.closest(Up)&&!e.closest(Qp)}extractOutline(e=6,t=false,n=false){const r=[],o=this.getConversationContentContainer();if(!o)return r;const i=this.getUserQuerySelector();if(!i)return r;const a=[];for(let g=1;g<=e;g++)a.push(`h${g}`);const s=`${i}, ${a.join(", ")}`,l=Array.from(o.querySelectorAll(i)),c=this.collectTopLevelBlocks(l).filter(e=>!this.shouldSkipOutlineElement(e)),d=new Set(c),u=Array.from(o.querySelectorAll(s)).filter(e=>e.matches(i)?d.has(e):!this.shouldSkipOutlineElement(e)),h=(e,t,n)=>{if(!e)return 0;try{if(n){const n=o.querySelectorAll(Wp);let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.cloneNode(!0);i.querySelectorAll(`${Qp}, .gh-user-query-markdown`).forEach(e=>e.remove()),r+=i.textContent||"";}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(i);let a=!1,s=null;for(const t of Array.from(r)){if(a){s=t;break}(t===e||t.contains(e)||e.contains(t))&&(a=!0);}if(s)return this.calculateRangeWordCount(e,s,o);const l=o.querySelectorAll(Wp);if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}};return u.forEach((o,a)=>{const s=o.tagName.toLowerCase(),l=o.matches(i),c=/^h[1-6]$/.test(s);let d,g=false;if(t&&l&&(g=true),c&&!this.shouldSkipOutlineElement(o)){const t=parseInt(s.charAt(1),10);!Number.isNaN(t)&&t<=e&&(g=true);}if(g){if(l){let e=this.extractUserQueryText(o),t=false;e.length>200&&(e=e.substring(0,200),t=true),d={level:0,text:e,element:o,isUserQuery:true,isTruncated:t};}else {d={level:parseInt(s.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}if(n){let e=null;for(let t=a+1;tt.id===e);return t?.title||null}getConversationList(){const e=document.querySelectorAll(Jp);if(!e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractConversationId(e);if(!r)return;const o=this.extractConversationTitle(e);o&&n.push({id:r,cid:t,title:o,url:`https://chat.z.ai/c/${r}`,isActive:r===this.getSessionId()});}),n}getConversationObserverConfig(){return {selector:Jp,shadow:false,extractInfo:e=>{const t=this.extractConversationId(e);if(!t)return null;const n=this.extractConversationTitle(e);return n?{id:t,title:n,url:`https://chat.z.ai/c/${t}`,cid:this.getCurrentCid()||void 0,isActive:t===this.getSessionId()}:null},getTitleElement:e=>e.querySelector(em)||e}}getSidebarScrollContainer(){return document.querySelector("#sidebar .overflow-y-auto")}getScrollContainer(){const e=this.collectScrollAnchorRoots(),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll("[data-pane-id]"));return this.pickBestScrollableAncestor(n)}navigateToConversation(e,t){const n=document.querySelectorAll(Jp);for(const r of Array.from(n)){if(this.extractConversationId(r)!==e)continue;const t=r.querySelector("button");if(t)return t.click(),true}return super.navigateToConversation(e,t||`https://chat.z.ai/c/${e}`)}getModelName(){const e=this.getSelectedModelFromStorage();if(e)return e;const t=this.findElementBySelectors(Op),n=t?.textContent?.trim();return n||null}lockModel(e,t){this.isNewConversation()&&super.lockModel(e,t);}getModelSwitcherConfig(e){return this.isNewConversation()?{targetModelKeyword:e,selectorButtonSelectors:[...Op],menuItemSelector:'button[aria-label="model-item"], button[data-melt-collapsible-trigger]',checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:"button[data-melt-collapsible-trigger]",subMenuTriggers:["更多模型","more"]}:null}async toggleTheme(e){try{const t="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,n="system"===e?t?"dark":"light":e;localStorage.setItem(tm,e),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(n),document.documentElement.style.colorScheme=n,document.body.style.colorScheme=n;const r=document.querySelector('meta[name="theme-color"]');return r&&r.setAttribute("content",nm[n]),window.dispatchEvent(new StorageEvent("storage",{key:tm,newValue:e,storageArea:localStorage})),!0}catch(RS){return console.error("[ZaiAdapter] toggleTheme error:",RS),false}}getWidthSelectors(){return [{selector:`${zp} [class*="max-w-[1000px]"]`,property:"max-width"},{selector:`${zp} [class*="max-w-[960px]"]`,property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${zp} .chat-user [class*="max-w-[90%]"]`,property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["#sidebar"]}}extractConversationTitle(e){const t=e.querySelector(em);return t?.textContent?.trim()||""}getSharePageTitle(){const e=this.getDocumentConversationTitle()||"";if(!e)return this.getSessionName();const t=e.split(" | ")[0]?.trim();return t||this.getSessionName()}collectScrollAnchorRoots(){const e=Array.from(document.querySelectorAll(`${Up}, ${Wp}`));return this.collectTopLevelBlocks(e).filter(e=>!e.closest(".gh-root, .gh-table-container"))}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(Up).length,i=e.querySelectorAll(Wp).length;let a=0;return a+=160*Math.min(o,60),a+=160*Math.min(i,60),o>0&&i>0&&(a+=700),e.scrollTop>0&&(a+=900),r.height>=.35*t&&(a+=500),r.width>=.45*n&&(a+=350),e.closest("[data-pane-id]")&&(a+=300),e.querySelector("textarea, #chat-input")&&(a-=700),e.matches(".scrollbar-none")&&e.scrollWidth>e.clientWidth&&(a-=400),a}shouldSkipOutlineElement(e){return !this.isOutlineElementVisible(e)||(!!e.closest(".gh-root")||(!!this.isInRenderedMarkdownContainer(e)||!!e.closest(Qp)))}isOutlineElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;if(e.closest("[hidden], [aria-hidden='true']"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}clearExportAttachmentCache(){this.exportUserAttachmentsByMessageId.clear(),this.exportShareTitle=null;}async prepareExportAttachmentCache(e){const t=this.getSessionId();if(t)try{const n=await this.collectExportMessageIds(e);if(0===n.length)return;const r=await fetch(`/api/v1/chats/${encodeURIComponent(t)}/messages/batch`,{method:"POST",credentials:"include",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({ids:n})});if(!r.ok)throw new Error(`messages/batch failed with ${r.status}`);const o=await r.json(),i=o?.data||{};Object.values(i).forEach(e=>{if(!e?.id||"user"!==e.role)return;const t=this.extractZaiApiUserAttachments(e.files||[]);t.length>0&&this.exportUserAttachmentsByMessageId.set(e.id,t);});}catch(RS){console.warn("[ZaiAdapter] Failed to load export attachment metadata:",RS);}}async collectExportMessageIds(e){const t=this.isSharePage()?await this.fetchShareMessageIds():[],n=this.collectDomMessageIds(e);return Array.from(new Set([...t,...n]))}async fetchShareMessageIds(){const e=this.getSessionId();if(!e)return [];const t=await fetch(`/api/v1/chats/share/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`share metadata failed with ${t.status}`);const n=await t.json();this.exportShareTitle=n?.title||null;const r=n?.chat?.history?.messages||{};return Object.keys(r)}collectDomMessageIds(e){const t=[];return Array.from(e.querySelectorAll('[id^="message-"]')).forEach(e=>{const n=this.extractZaiMessageId(e);n&&t.push(n);}),t}extractZaiMessageId(e){const t=e.id?.startsWith("message-")?e:e.closest('[id^="message-"]'),n=(t?.id||"").match(om);return n?.[1]||""}extractZaiApiUserAttachments(e){return e.map(e=>this.extractZaiApiUserAttachment(e)).filter(e=>Boolean(e))}extractZaiApiUserAttachment(e){const t=e.file?.meta,n=t?.name||e.file?.filename||e.name||e.id||"attachment",r=this.decodeZaiAttachmentName(n)||"attachment",o=t?.content_type||e.media||e.type||"",i=va(t?.cdn_url||e.url||"");return {kind:this.isZaiImageAttachment(r,o,i)?"image":"file",name:r,source:xa(i)?i:"",type:o,size:t?.size||e.size}}extractZaiUserQueryExportContent(e,t){const n=this.extractUserQueryText(e),r=this.extractZaiUserAttachments(e);if(0===r.length)return n;const o=this.formatZaiUserImageAttachments(r,t),i=this.formatZaiUserFileAttachments(r,t),a=i.length>0?`${le("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractZaiUserAttachments(e){const t=this.extractZaiMessageId(e),n=t&&this.exportUserAttachmentsByMessageId.get(t)||[],r=this.extractZaiUserAttachmentsFromDom(e),o=[],i=new Set,a=e=>{const t=this.getZaiAttachmentKeys(e);t.some(e=>i.has(e))||(t.forEach(e=>i.add(e)),o.push(e));};return n.forEach(a),r.forEach(a),o}getZaiAttachmentKeys(e){const t=[],n=e.kind,r=e.name.trim().toLowerCase(),o=this.getZaiAttachmentTypeKey(e),i=e.size?this.formatZaiFileSize(e.size).toLowerCase():"",a=this.getZaiAttachmentSourceKey(e.source);return a&&t.push(`${n}:source:${a}`),r&&o&&t.push(`${n}:name-type:${r}:${o}`),r&&i&&t.push(`${n}:name-size:${r}:${i}`),t.length>0?t:[`${n}:fallback:${r}:${o}`]}getZaiAttachmentTypeKey(e){const t=e.name.match(/\.([a-z0-9]{1,10})$/i)?.[1];if(t)return t.toLowerCase();const n=e.type.trim().toLowerCase(),r=n.match(/\/([a-z0-9.+-]+)$/i)?.[1];return r?r.replace(/^plain$/,"txt").replace(/^jpeg$/,"jpg"):n}getZaiAttachmentSourceKey(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.hostname}${t.pathname}`.toLowerCase()}catch{return e.split("?")[0].toLowerCase()}}extractZaiUserAttachmentsFromDom(e){const t=e.matches(Up)?e:e.closest(Up);if(!t)return [];const n=Array.from(t.querySelectorAll("button")).filter(e=>{const t=e.textContent?.replace(/\s+/g," ").trim()||"";return !!t&&(!!this.looksLikeZaiAttachmentCard(e,t)&&!e.closest(".gh-root, .gh-user-query-markdown"))}),r=[],o=new Set;return n.forEach(e=>{const t=this.extractZaiDomUserAttachment(e);if(!t)return;const n=this.getZaiAttachmentKeys(t);n.some(e=>o.has(e))||(n.forEach(e=>o.add(e)),r.push(t));}),r}looksLikeZaiAttachmentCard(e,t){return !!e.querySelector("img[data-cy='image'], img.not-prose")||!!/\.[A-Za-z0-9]{1,10}\b/.test(t)&&(/\b(?:B|KB|MB|GB|TB)\b/i.test(t)||Boolean(e.querySelector("img[src*='/icons/']")))}extractZaiDomUserAttachment(e){const t=this.extractZaiCleanTextParts(e),{name:n,type:r,sizeLabel:o}=this.parseZaiAttachmentLabel(t),i=this.extractZaiDownloadableSource(e),a=n||this.extractZaiFilenameFromUrl(i)||"attachment";return {kind:this.isZaiImageAttachment(a,r,i)?"image":"file",name:a,source:i,type:r,size:this.parseZaiSizeLabel(o)}}parseZaiAttachmentLabel(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=t.find(e=>/\.[A-Za-z0-9]{1,10}$/.test(e))||t[0]||"",r=t.find(e=>/^[A-Za-z0-9.+-]{1,16}$/.test(e)&&!/\d/.test(e))||n.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"";return {name:n,type:r,sizeLabel:t.find(e=>/^\d+(?:\.\d+)?\s*(?:B|KB|MB|GB|TB)$/i.test(e))||""}}extractZaiCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}extractZaiDownloadableSource(e){const t=Array.from(e.querySelectorAll("img")).find(e=>e instanceof HTMLImageElement&&Boolean(this.normalizeZaiAttachmentSource(e.currentSrc||e.src||e.getAttribute("src")||"")));if(t){const e=this.normalizeZaiAttachmentSource(t.currentSrc||t.src||t.getAttribute("src")||"");if(e)return e}const n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of Yp){const t=this.normalizeZaiAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeZaiAttachmentSource(e){const t=va(e);if(!t||!xa(t))return "";try{const e=new URL(t,window.location.href);if(e.hostname===Dp&&/^\/icons\//i.test(e.pathname))return "";if("z-cdn.chatglm.cn"===e.hostname&&/\/z-ai\/static\/logo\.svg$/i.test(e.pathname))return ""}catch{return ""}return t}isZaiImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}formatZaiUserImageAttachments(e,t){return Ra(e,t,{siteId:this.getSiteId()})}formatZaiUserFileAttachments(e,t){return Da(e,t,{siteId:this.getSiteId(),getLabel:e=>{const t=e.size?`, ${this.formatZaiFileSize(e.size)}`:"";return e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?`${e.name}${t}`:`${e.name} (${e.type}${t})`:`${e.name}${t}`}})}parseZaiSizeLabel(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)$/i);if(!t)return;const n=Number(t[1]);if(!Number.isFinite(n))return;const r=t[2].toUpperCase(),o="TB"===r?1024**4:"GB"===r?1024**3:"MB"===r?1048576:"KB"===r?1024:1;return Math.round(n*o)}formatZaiFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?Math.round(n).toString():n.toFixed(1)} ${t[r]}`}extractZaiFilenameFromUrl(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname;return decodeURIComponent(t.split("/").pop()||"")}catch{return ""}}decodeZaiAttachmentName(e){try{return decodeURIComponent(e)}catch{return e}}findUserContentRoot(e){const t=(e.matches(Up)?e:e.closest(Up))||e;for(const n of Kp){const e=t.querySelector(n);if(!e)continue;if(e.closest(".gh-user-query-markdown"))continue;if(e.closest("button, [role=button]"))continue;const r=e.textContent?.trim();if(r)return e}return t}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}extractConversationId(e){const t=["data-conversation-id","data-chat-id","data-session-id","data-cid","data-id"];for(const o of t){const t=this.matchConversationId(e.getAttribute(o));if(t)return t;const n=e.querySelector(`[${o}]`),r=this.matchConversationId(n?.getAttribute(o));if(r)return r}const n=e.getAttribute("aria-controls"),r=this.matchConversationId(n);return r||""}matchConversationId(e){if(!e)return "";const t=e.match(rm);return t?.[0]||""}getSelectedModelFromStorage(){try{const e=localStorage.getItem("selectedModels");if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)&&"string"==typeof t[0]?t[0]:"string"==typeof t?t:null}catch{return null}}}];function am(){for(const e of im)if(e.match())return e;return null}const sm=Object.freeze(Object.defineProperty({__proto__:null,SiteAdapter:vs,getAdapter:am,getAllAdapters:function(){return [...im]}},Symbol.toStringTag,{value:"Module"}));let lm=null;const cm=Fo()(Wo((e,t)=>(lm=()=>e({_hasHydrated:true}),{conversations:{},lastUsedFolderId:"inbox",_hasHydrated:false,addConversation:t=>e(e=>({conversations:{...e.conversations,[t.id]:t}})),updateConversation:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],...n,updatedAt:Date.now()}}}:e),deleteConversation:t=>e(e=>{const{[t]:n,...r}=e.conversations;return {conversations:r}}),moveToFolder:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],folderId:n,updatedAt:Date.now()}}}:e),togglePin:n=>{const r=t();if(!r.conversations[n])return false;const o=!r.conversations[n].pinned;return e(e=>({conversations:{...e.conversations,[n]:{...e.conversations[n],pinned:o,updatedAt:Date.now()}}})),o},setConversationTags:(t,n)=>e(e=>{if(!e.conversations[t])return e;const r={...e.conversations[t]};return n.length>0?r.tagIds=n:delete r.tagIds,{conversations:{...e.conversations,[t]:r}}}),removeTagFromAll:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))if(i.tagIds?.includes(t)){const e=i.tagIds.filter(e=>e!==t);n[o]={...i,tagIds:e.length>0?e:void 0},r=true;}else n[o]=i;return r?{conversations:n}:e}),moveConversationsToInbox:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))i.folderId===t?(n[o]={...i,folderId:"inbox"},r=true):n[o]=i;return r?{conversations:n}:e}),setLastUsedFolderId:t=>e({lastUsedFolderId:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"conversations",storage:Uo(()=>gi),partialize:e=>({conversations:e.conversations,lastUsedFolderId:e.lastUsedFolderId}),onRehydrateStorage:()=>()=>{lm?.();}})),dm=()=>cm.getState(),um=Object.freeze(Object.defineProperty({__proto__:null,getConversationsStore:dm,useConversationsStore:cm},Symbol.toStringTag,{value:"Module"})),hm=(e,t)=>{const n=(e||"").trim(),r=(t||"").trim();return r&&n.startsWith(r)?n.slice(r.length).trim():n},gm=e=>({...e,name:hm(e.name,e.icon)});let pm=null;const mm=Fo()(Wo((e,t)=>(pm=()=>e({_hasHydrated:true}),{folders:ao,_hasHydrated:false,addFolder:(t,n)=>{const r={id:"folder_"+Date.now(),name:hm(t,n),icon:n};return e(e=>({folders:[...e.folders,r]})),r},updateFolder:(t,n)=>e(e=>({folders:e.folders.map(e=>{if(e.id!==t)return e;const r={...e,...n};return {...r,name:hm(r.name,r.icon)}})})),deleteFolder:t=>{"inbox"!==t&&e(e=>({folders:e.folders.filter(e=>e.id!==t)}));},moveFolder:(t,n)=>e(e=>{const r=e.folders.findIndex(e=>e.id===t);if(-1===r||0===r)return e;const o="up"===n?r-1:r+1;if(o<=0||o>=e.folders.length)return e;const i=[...e.folders];return [i[r],i[o]]=[i[o],i[r]],{folders:i}}),reorderFolders:t=>e(e=>{const n=e.folders.find(e=>"inbox"===e.id||!!e.isDefault),r=e.folders.filter(e=>"inbox"!==e.id&&!e.isDefault);return {folders:[...n?[n]:[],...t.map(e=>r.find(t=>t.id===e)).filter(Boolean),...r.filter(e=>!t.includes(e.id))]}}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"folders",storage:Uo(()=>gi),partialize:e=>({folders:e.folders}),merge:(e,t)=>{const n=e;return n?.folders?{...t,...n,folders:(r=n.folders,r.map(gm))}:t;var r;},onRehydrateStorage:()=>()=>{pm?.();}})),fm=()=>mm.getState(),bm=Object.freeze(Object.defineProperty({__proto__:null,getFoldersStore:fm,useFoldersStore:mm},Symbol.toStringTag,{value:"Module"}));let ym=null;const vm=Fo()(Wo((e,t)=>(ym=()=>e({_hasHydrated:true}),{tags:[],_hasHydrated:false,addTag:(n,r)=>{if(t().tags.some(e=>e.name.toLowerCase()===n.toLowerCase()))return null;const o={id:"tag_"+Date.now()+"_"+Math.random().toString(36).substr(2,5),name:n,color:r};return e(e=>({tags:[...e.tags,o]})),o},updateTag:(n,r,o)=>{if(t().tags.some(e=>e.id!==n&&e.name.toLowerCase()===r.toLowerCase()))return null;let i=null;return e(e=>({tags:e.tags.map(e=>e.id===n?(i={...e,name:r,color:o},i):e)})),i},deleteTag:t=>e(e=>({tags:e.tags.filter(e=>e.id!==t)})),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"tags",storage:Uo(()=>gi),partialize:e=>({tags:e.tags}),onRehydrateStorage:()=>()=>{ym?.();}})),xm=()=>vm.getState(),wm=Object.freeze(Object.defineProperty({__proto__:null,getTagsStore:xm,useTagsStore:vm},Symbol.toStringTag,{value:"Module"}));class Sm{siteAdapter;observerConfig=null;sidebarObserverStop=null;observerContainer=null;titleWatcher=null;pollInterval=null;geminiMigrationTimer=null;geminiMigrationRetryCount=0;syncUnpin=false;syncDelete=true;onChangeCallbacks=[];onExportProgressCallbacks=[];constructor(e){this.siteAdapter=e;}get folders(){return fm().folders}get conversations(){return dm().conversations}get lastUsedFolderId(){return dm().lastUsedFolderId}get tags(){return xm().tags}onDataChange(e){return this.onChangeCallbacks.push(e),()=>{this.onChangeCallbacks=this.onChangeCallbacks.filter(t=>t!==e);}}onExportProgress(e){return this.onExportProgressCallbacks.push(e),()=>{this.onExportProgressCallbacks=this.onExportProgressCallbacks.filter(t=>t!==e);}}notifyDataChange(){this.onChangeCallbacks.forEach(e=>e());}notifyExportProgress(e){this.onExportProgressCallbacks.forEach(t=>t(e));}async init(){await this.waitForHydration();"pending_email"===this.tryMigrateGeminiLegacyCidToEmail()&&this.startGeminiMigrationRetry();const e=await(di||(di=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(ci,t=>{const n=t?.[ci];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=1e4?e(true):chrome.storage.local.remove(ci,()=>e(false)):e(true);}):e(false);}),di));if(0===Object.keys(this.getAllConversations()).length&&this.siteAdapter.loadAllConversations&&!e)try{await this.waitForSidebarReady()&&await this.autoFullSync();}catch{}this.startSidebarObserver();}tryMigrateGeminiLegacyCidToEmail(){if(this.siteAdapter.getSiteId()!==ho)return "noop";const e=this.conversations,t=Object.entries(e).filter(([e,t])=>this.isGeminiConversation(t));if(0===t.length)return "noop";const n=t.filter(([e,t])=>this.isLegacyGeminiCid(t.cid));if(0===n.length)return "noop";const r=this.siteAdapter.getCurrentCid?.();if(!this.isEmailCid(r))return "pending_email";const o=this.getGeminiUserIndexFromPath(),i=n.some(([e,t])=>(t.cid||"0")===o),a=t.some(([e,t])=>t.cid===r),s=new Set(n.map(([e,t])=>t.cid||"0"));let l=null;if(i?l=o:a||1!==s.size||(l=Array.from(s)[0]),!l)return "noop";const c=n.filter(([e,t])=>(t.cid||"0")===l);if(0===c.length)return "noop";const d={...e},u=this.getGeminiUserPathPrefix();return c.forEach(([e,t])=>{d[e]={...t,cid:r,url:this.buildGeminiConversationUrl(e,u)};}),cm.setState({conversations:d}),this.notifyDataChange(),console.warn(`[ConversationManager] Gemini legacy cid migrated: ${l} -> ${r}, updated ${c.length} conversations.`),"migrated"}startGeminiMigrationRetry(){if(this.siteAdapter.getSiteId()!==ho)return;if(this.geminiMigrationTimer)return;this.geminiMigrationRetryCount=0,this.geminiMigrationTimer=setInterval(()=>{const e=this.tryMigrateGeminiLegacyCidToEmail();this.geminiMigrationRetryCount+=1,("pending_email"!==e||this.geminiMigrationRetryCount>=120)&&this.stopGeminiMigrationRetry();},1500);}stopGeminiMigrationRetry(){this.geminiMigrationTimer&&(clearInterval(this.geminiMigrationTimer),this.geminiMigrationTimer=null),this.geminiMigrationRetryCount=0;}isEmailCid(e){return "string"==typeof e&&e.includes("@")}isLegacyGeminiCid(e){return !e||/^\d+$/.test(e)}getGeminiUserIndexFromPath(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?e[1]:"0"}getGeminiUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?`/u/${e[1]}`:""}isGeminiConversation(e){return e.siteId===ho||(!e.siteId||e.siteId===ho)&&("string"==typeof e.url&&e.url.includes("gemini.google.com"))}buildGeminiConversationUrl(e,t){return `https://gemini.google.com${t}/app/${e}`}async waitForHydration(){const e=[mm,vm,cm];await Promise.all(e.map(e=>new Promise(t=>{if(e.getState()._hasHydrated)return void t();const n=e.subscribe(e=>{e._hasHydrated&&(n(),t());});})));}async waitForSidebarReady(e=1e4){const t=Date.now();for(;Date.now()-tsetTimeout(e,250));}return false}async autoFullSync(){await this.siteAdapter.loadAllConversations(),await new Promise(e=>setTimeout(e,400));let e=0,t=this.siteAdapter.getConversationList().length;for(let n=0;n<10;n++){if(n>0){const e=this.siteAdapter.getSidebarScrollContainer();if(!e)break;const t=e;t.scrollTop=t.scrollHeight,await new Promise(e=>setTimeout(e,400));}const{newCount:r,updatedCount:o}=this.syncConversations(null,true);(r>0||o>0)&&this.notifyDataChange(),await new Promise(e=>setTimeout(e,300));const i=this.siteAdapter.getConversationList().length;if(r>0||i>t?(t=Math.max(t,i),e=0):e++,e>=2)break}}destroy(){this.stopGeminiMigrationRetry(),this.stopSidebarObserver();}updateSettings(e){this.syncUnpin=e.syncUnpin,"boolean"==typeof e.syncDelete&&(this.syncDelete=e.syncDelete);}startSidebarObserver(){if(this.sidebarObserverStop)return;const e=this.siteAdapter.getConversationObserverConfig();if(!e)return;this.observerConfig=e;const t=(n=0)=>{const r=this.siteAdapter.getSidebarScrollContainer()||document;if(e.shadow&&n<5){if(!this.siteAdapter.getSidebarScrollContainer())return void setTimeout(()=>t(n+1),1e3)}this.observerContainer=r,this.sidebarObserverStop=ds.each(e.selector,(t,n)=>{this.handleObservedElement(t,n,e);},{parent:r,shadow:e.shadow});};t(),e.shadow&&this.startPolling();}stopSidebarObserver(){this.sidebarObserverStop&&(this.sidebarObserverStop(),this.sidebarObserverStop=null),this.observerContainer=null,this.titleWatcher&&("function"==typeof this.titleWatcher.stop&&this.titleWatcher.stop(),this.titleWatcher=null),this.stopPolling();}handleObservedElement(e,t,n){const r=(o=5)=>{const i=n.extractInfo(e);i?.id?(this.updateConversationFromObservation(i,t),this.monitorConversationTitle(e,i.id)):o>0&&setTimeout(()=>r(o-1),500);};r();}updateConversationFromObservation(e,t){const n=this.conversations[e.id];if(t&&!n)dm().addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:this.lastUsedFolderId,pinned:e.isPinned||false,createdAt:Date.now(),updatedAt:Date.now()}),this.notifyDataChange();else if(n){let t=false;const r={};e.title&&e.title!==n.title&&(r.title=e.title,t=true),e.url&&e.url!==n.url&&(r.url=e.url,t=true),void 0!==e.cid&&e.cid!==n.cid&&(r.cid=e.cid,t=true),void 0!==e.isPinned&&e.isPinned!==n.pinned&&(e.isPinned?(r.pinned=true,t=true):!e.isPinned&&this.syncUnpin&&(r.pinned=false,t=true)),t&&(dm().updateConversation(e.id,r),this.notifyDataChange());}}startPolling(){this.pollInterval||(this.pollInterval=setInterval(()=>{if(!this.observerConfig)return;const e=this.observerConfig,t=ds.query(e.selector,{all:true,shadow:e.shadow});Array.isArray(t)&&t.forEach(t=>{const n=e.extractInfo(t);if(!n?.id)return;const r=this.conversations[n.id];r?n.title&&n.title!==r.title&&(dm().updateConversation(n.id,{title:n.title}),this.notifyDataChange()):(this.updateConversationFromObservation(n,true),this.monitorConversationTitle(t,n.id));});},3e3));}stopPolling(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);}monitorConversationTitle(e,t){if(!e.dataset.ghTitleObserver){if(e.dataset.ghTitleObserver="true",!this.titleWatcher){const e=this.siteAdapter.getSidebarScrollContainer()||document.body;this.titleWatcher=ds.watchMultiple(e,{debounce:500});}this.titleWatcher.add(e,()=>{const n=this.observerConfig;if(!n)return;const r=n.extractInfo(e),o=r?.id;if(!o||o!==t)return;const i=this.conversations[t];if(!i)return;let a=false;const s={};r.title&&r.title!==i.title&&(s.title=r.title,a=true),void 0!==r.isPinned&&r.isPinned!==i.pinned&&(r.isPinned?(s.pinned=true,a=true):!r.isPinned&&this.syncUnpin&&(s.pinned=false,a=true)),a&&(dm().updateConversation(t,s),this.notifyDataChange());});}}getFolders(){return this.folders}getConversations(e){const t=this.siteAdapter.getCurrentCid?.()||null;let n=Object.values(this.conversations).filter(e=>this.matchesCid(e,t));return e&&(n=n.filter(t=>t.folderId===e)),n}createFolder(e,t){return fm().addFolder(e,t)}updateFolder(e,t){fm().updateFolder(e,t);}deleteFolder(e){"inbox"!==e&&(dm().moveConversationsToInbox(e),fm().deleteFolder(e));}moveFolder(e,t){fm().moveFolder(e,t);}reorderFolders(e){fm().reorderFolders(e);}async deleteConversation(e){const t=await this.deleteConversations([e]);return t.results.length>0?t.results[0]:{id:e,localDeleted:false,remoteEnabled:this.syncDelete,remoteAttempted:false,remoteSuccess:false,remoteMethod:"none",reason:"not_found"}}async deleteConversations(e){const t=Array.from(new Set(e.filter(Boolean)));if(0===t.length)return {total:0,localDeletedCount:0,remoteAttemptedCount:0,remoteSuccessCount:0,remoteFailedCount:0,failedIds:[],results:[]};const n=t.map(e=>{const t=this.conversations[e];return t?t.siteId&&t.siteId!==this.siteAdapter.getSiteId()?null:{id:t.id,title:t.title,url:t.url}:null}).filter(e=>Boolean(e)),r=new Map;if(this.syncDelete&&n.length>0)try{(await this.siteAdapter.deleteConversationsOnSite(n)).forEach(e=>{r.set(e.id,e);});}catch(RS){console.error(`[ConversationManager] deleteConversationsOnSite failed on ${this.siteAdapter.getName()}:`,RS);const t=RS instanceof Error&&RS.message||"remote_delete_failed";n.forEach(e=>{r.set(e.id,{id:e.id,success:false,method:"api",reason:t});});}let o=0,i=0,a=0,s=0;const l=[];return t.forEach(e=>{const t=Boolean(this.conversations[e]),n=this.syncDelete,c=r.get(e),d=c?.method||"none",u=n&&r.has(e)&&"none"!==d,h=u&&(c?.success||false);u&&(i++,h?a++:s++),t&&(dm().deleteConversation(e),o++),l.push({id:e,localDeleted:t,remoteEnabled:n,remoteAttempted:u,remoteSuccess:h,remoteMethod:d,reason:c?.reason||(t?void 0:"not_found")});}),o>0&&this.notifyDataChange(),{total:t.length,localDeletedCount:o,remoteAttemptedCount:i,remoteSuccessCount:a,remoteFailedCount:s,failedIds:l.filter(e=>!e.localDeleted).map(e=>e.id),results:l}}moveConversation(e,t){dm().moveToFolder(e,t);}setLastUsedFolder(e){dm().setLastUsedFolderId(e);}getTags(){return this.tags}createTag(e,t){return xm().addTag(e,t)}updateTag(e,t,n){return xm().updateTag(e,t,n)}deleteTag(e){xm().deleteTag(e),dm().removeTagFromAll(e);}setConversationTags(e,t){dm().setConversationTags(e,t);}togglePin(e){return dm().togglePin(e)}renameConversation(e,t){t&&dm().updateConversation(e,{title:t});}updateConversation(e,t){dm().updateConversation(e,t);}getConversation(e){return this.conversations[e]}getLastUsedFolderId(){return this.lastUsedFolderId}getAllConversations(){const e=this.siteAdapter.getCurrentCid?.()||null,t={};for(const[n,r]of Object.entries(this.conversations))this.matchesCid(r,e)&&(t[n]=r);return t}syncConversations(e=null,t=false,n={}){const r=this.siteAdapter.getConversationList();if(!r||0===r.length)return {newCount:0,updatedCount:0,deletedCount:0};const o=this.conversations;let i=0,a=0,s=0;const l=Date.now(),c=e||this.lastUsedFolderId||"inbox",d=dm(),u=new Set(r.map(e=>e.id));if(r.forEach(e=>{const t=e.id,n=o[t];if(n){const r={};let o=false;n.title!==e.title&&(r.title=e.title,o=true),e.isPinned&&!n.pinned?(r.pinned=true,o=true):!e.isPinned&&n.pinned&&this.syncUnpin&&(r.pinned=false,o=true),n.siteId||(r.siteId=this.siteAdapter.getSiteId(),o=true),e.cid&&!n.cid&&(r.cid=e.cid,o=true),o&&(d.updateConversation(t,r),a++);}else d.addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:c,pinned:e.isPinned||false,createdAt:l,updatedAt:l}),i++;}),n.syncDeleted){const e=this.siteAdapter.getSiteId(),t=this.siteAdapter.getCurrentCid?.()||null;Object.entries(o).forEach(([n,r])=>{r.siteId===e&&this.matchesCid(r,t)&&(u.has(n)||(d.deleteConversation(n),s++));});}return e&&d.setLastUsedFolderId(e),{newCount:i,updatedCount:a,deletedCount:s}}matchesCid(e,t){const n=this.siteAdapter.getSiteId();return (!e.siteId||e.siteId===n)&&(t?!e.cid||e.cid===t:!e.cid)}getSidebarConversationOrder(){const e=this.siteAdapter.getConversationObserverConfig?.();if(!e)return [];const t=ds.query(e.selector,{all:true,shadow:e.shadow});return Array.from(t||[]).map(t=>e.extractInfo?.(t)?.id).filter(e=>Boolean(e))}sanitizeConversationTitleForUse(e,t={}){const n=Mi.getState().settings,r={privacyTitle:n.tab?.privacyTitle||"Google",siteName:this.siteAdapter.getName(),titleFormat:n.tab?.titleFormat};let o=Wa(e,r);const i=Wa(t.managedTitleReference,r);if(i){const t=Wa(e,{...r,hasManagedTitleSignal:true});t&&t!==o&&t===i&&(o=t);}return t.dropLocalizedFallback&&this.isLocalizedFallbackConversationTitle(o)?null:o}isLocalizedFallbackConversationTitle(e){const t=e?.replace(/\s+/g," ").trim();if(!t)return false;return ce("untitledConversation").map(e=>e.replace(/\s+/g," ").trim()).includes(t)}formatTime(e){if(!e)return "";const t=new Date(e),n=(new Date).getTime()-t.getTime();return n<6e4?le("justNow"):n<36e5?Math.floor(n/6e4)+le("minutesAgo"):n<864e5?Math.floor(n/36e5)+le("hoursAgo"):n<6048e5?Math.floor(n/864e5)+le("daysAgo"):t.toLocaleDateString()}resolveConversationForExport(e){const t=this.conversations[e],n=this.siteAdapter.getCurrentConversationInfo();if(!n||n.id!==e)return t||null;const r=this.sanitizeConversationTitleForUse(t?.title,{dropLocalizedFallback:true,managedTitleReference:n.title})||this.sanitizeConversationTitleForUse(n.title)||le("untitledConversation"),o=n.url||t?.url||window.location.href,i=n.cid??t?.cid,a=n.isPinned??t?.pinned??false;if(t){const n={};let s=false;if(t.title?.trim()||r===t.title||(n.title=r,s=true),o!==t.url&&(n.url=o,s=true),void 0!==i&&i!==t.cid&&(n.cid=i,s=true),a!==t.pinned&&(n.pinned=a,s=true),s){dm().updateConversation(e,n),this.notifyDataChange();const o={...t,...n,updatedAt:Date.now()};return o.title===r?o:{...o,title:r}}return t.title===r?t:{...t,title:r}}const s=Date.now(),l={id:e,siteId:this.siteAdapter.getSiteId(),cid:i,title:r,url:o,folderId:this.lastUsedFolderId||"inbox",pinned:a,createdAt:s,updatedAt:s};return this.siteAdapter.isSharePage()||(dm().addConversation(l),this.notifyDataChange()),l}async withConversationExportData(e,t,n,r="export"){if(this.siteAdapter.getSessionId()!==e)return Pi(le("exportNeedOpenFirst")),null;const o=this.resolveConversationForExport(e);if(!o)return console.error("[ConversationManager] Conversation not found:",e),null;const i=this.siteAdapter.getScrollContainer?.()||null,a=i?.scrollTop??null,s=window.scrollY,l=Mi.getState().settings,c="zip"===l.export?.packaging?"zip":"markdown",d={conversationId:e,format:t,includeThoughts:l.export?.includeThoughts??true,packaging:c};let u=false,h=null;const g=n=>{this.notifyExportProgress({conversationId:e,format:t,stage:n,operation:r});};try{if(g("loading-history"),i){let e=0,t=0;const n=50;for(;tsetTimeout(e,500));const n=i.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}g("preparing"),u=!0,h=await this.siteAdapter.prepareConversationExport(d),g("extracting");const e="markdown"===t&&"zip"===c?await this.siteAdapter.extractExportBundle(d):null,r=e?.messages||await this.extractConversationMessages(d);return 0===r.length?(console.error("[ConversationManager] No messages found"),null):await n({conv:o,messages:r,exportBundle:e,exportPackaging:c,notifyProgress:g})}catch(RS){return console.error("[ConversationManager] Export failed:",RS),null}finally{if(g("restoring"),u)try{await this.siteAdapter.restoreConversationAfterExport(d,h);}catch(p){console.warn("[ConversationManager] Export state restore failed:",p);}i&&null!==a?i.scrollTop=a:window.scrollTo({top:s,behavior:"auto"}),this.notifyExportProgress(null);}}async collectCurrentConversationExportMessages(e="clipboard"){const t=this.siteAdapter.getSessionId();return t?this.withConversationExportData(t,e,({messages:e})=>e,"outline-copy"):(Pi(le("exportNeedOpenFirst")),null)}async exportConversation(e,t){return true===await this.withConversationExportData(e,t,async({conv:e,messages:n,exportBundle:r,exportPackaging:o,notifyProgress:i})=>{const a=Mi.getState().settings,s=le("untitledConversation"),l=this.sanitizeConversationTitleForUse(e.title)||s,c=l.replace(/[<>:"/\\|?*]/g,"_").substring(0,50),d=(u=l,h=this.siteAdapter.getName(),g=e.id,p={customUserName:a.export?.customUserName,customModelName:a.export?.customModelName},{title:u||le("exportUntitled"),id:g,url:window.location.href,exportTime:(new Date).toLocaleString(),source:h,customUserName:p?.customUserName,customModelName:p?.customModelName});var u,h,g,p;let m,f,b,y="";if(a.export?.exportFilenameTimestamp){const e=new Date;y=`_${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}_${String(e.getHours()).padStart(2,"0")}-${String(e.getMinutes()).padStart(2,"0")}-${String(e.getSeconds()).padStart(2,"0")}`;}const v=`${this.siteAdapter.getName().replace(/[<>:"/\\|?*]/g,"_")} - `;if("clipboard"===t)return i("copying"),m=Wi(d,n),await navigator.clipboard.writeText(m),Pi(le("copySuccess")),true;if("markdown"===t){m=Wi(d,n),f=`${v}${c}${y}.md`,b="text/markdown;charset=utf-8";if("zip"===o){i("packaging");return !!(await async function(e){const t=new Set,n=ea(Ji(e.markdownFilename,"conversation.md"),t),r=[{path:n,data:e.markdownContent,mimeType:"text/markdown;charset=utf-8"}],o=[];for(const i of e.assets){const e=ta(i.relativePath||na(i),t);try{const t=await ra(i);r.push({path:e,data:t,mimeType:i.mimeType}),o.push({name:i.name,path:e,kind:i.kind,mimeType:i.mimeType,sourceUrl:i.sourceUrl,description:i.description,included:!0});}catch(RS){console.warn("[Exporter] Failed to include export asset:",i.name,RS),o.push({name:i.name,path:e,kind:i.kind,mimeType:i.mimeType,sourceUrl:i.sourceUrl,description:i.description,included:false,error:oa(RS)});}}r.push({path:ea("manifest.json",t),data:JSON.stringify({version:1,metadata:{title:e.metadata.title,id:e.metadata.id,url:e.metadata.url,exportTime:e.metadata.exportTime,source:e.metadata.source},markdown:n,assets:o},null,2),mimeType:"application/json;charset=utf-8"});try{const t=await ia(r);return await sa(t,e.packageFilename)}catch(RS){return console.error("[Exporter] Package download failed:",RS),Pi(le("exportFailed")),false}}({markdownFilename:f,markdownContent:m,assets:this.normalizeExportAssets(r),packageFilename:`${v}${c}${y}.zip`,metadata:d}))&&(Pi(le("exportSuccess")),true)}}else "json"===t?(m=function(e,t){const n={metadata:{title:e.title,id:e.id,url:e.url,exportTime:e.exportTime,source:e.source},messages:t.map(e=>({role:e.role,content:e.content}))};return JSON.stringify(n,null,2)}(d,n),f=`${v}${c}${y}.json`,b="application/json;charset=utf-8"):(m=function(e,t){const n=[];return n.push(`${le("exportMetaConvTitle")}: ${e.title}`),n.push(`${le("exportMetaTime")}: ${e.exportTime}`),n.push(`${le("exportMetaSource")}: ${e.source}`),n.push(`${le("exportMetaUrl")}: ${e.url}`),n.push(""),n.push("=".repeat(50)),n.push(""),t.forEach(t=>{if("user"===t.role){const t=e.customUserName||le("exportUserLabel");n.push(`[${t}]`);}else {const t=e.customModelName||e.source;n.push(`[${t}]`);}n.push(t.content),n.push(""),n.push("-".repeat(50)),n.push("");}),n.join("\n")}(d,n),f=`${v}${c}${y}.txt`,b="text/plain;charset=utf-8");i("downloading");return !!(await aa(m,f,b))&&(Pi(le("exportSuccess")),true)})}async extractConversationMessages(e){const t=await this.siteAdapter.extractExportMessages(e);if(null!==t)return t;const n=[],r=this.siteAdapter.getExportConfig?.();if(!r)return console.warn("[ConversationManager] Export config not available"),n;const{userQuerySelector:o,assistantResponseSelector:i,turnSelector:a,useShadowDOM:s}=r;if(a){const e=ds.query(a,{all:true,shadow:s})||[];if(e.length>0){const t=(e,t)=>{const n=[];e.matches?.(t)&&n.push(e);return (ds.query(t,{parent:e,all:true,shadow:s})||[]).forEach(e=>{n.includes(e)||n.push(e);}),n},r=(e,t)=>{if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0},a=(e,t)=>{if("user"===e){const r=this.siteAdapter.extractUserQueryExportContent(t);return void n.push({role:e,content:r})}const r=this.siteAdapter.extractAssistantResponseText,o=vs.prototype.extractAssistantResponseText;let i="";r&&r!==o&&(i=r.call(this.siteAdapter,t)),i||(i=Hi(t)||t.textContent?.trim()||""),n.push({role:e,content:i});};return e.forEach(e=>{[...t(e,o).map(e=>({role:"user",element:e})),...t(e,i).map(e=>({role:"assistant",element:e}))].sort((e,t)=>r(e.element,t.element)).forEach(({role:e,element:t})=>{a(e,t);});}),n}}const l=ds.query(o,{all:true,shadow:s})||[],c=ds.query(i,{all:true,shadow:s})||[],d=Math.max(l.length,c.length);for(let u=0;u!!e.name?.trim()&&(void 0!==e.content||Boolean(e.sourceUrl))):[]}}const Cm={getItem:async e=>{const t=await gi.getItem("bookmarks");return t?JSON.stringify({state:{bookmarks:JSON.parse(t)},version:0}):null},setItem:async(e,t)=>{const n=JSON.parse(t),r=n.state?.bookmarks||[];await gi.setItem("bookmarks",JSON.stringify(r));},removeItem:async e=>{await gi.removeItem("bookmarks");}},km=Fo()(Wo((e,t)=>({bookmarks:[],addBookmark:(t,n,r,o,i,a)=>{const s={id:crypto.randomUUID(),sessionId:t,siteId:n,cid:r,title:o.text,level:o.level,signature:i,scrollTop:a,timestamp:Date.now()};e(e=>({bookmarks:[...e.bookmarks,s]}));},removeBookmark:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.id!==t)}));},updateBookmark:(t,n)=>{e(e=>({bookmarks:e.bookmarks.map(e=>e.id===t?{...e,...n}:e)}));},toggleBookmark:(e,n,r,o,i,a)=>{const s=t(),l=s.getBookmarkId(e,i);l?s.removeBookmark(l):s.addBookmark(e,n,r,o,i,a);},getBookmarksBySession:e=>t().bookmarks.filter(t=>t.sessionId===e),getBookmarkId:(e,n)=>{const r=t().bookmarks.find(t=>t.sessionId===e&&t.signature===n);return r?r.id:null},clearSessionBookmarks:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.sessionId!==t)}));},clearAllBookmarks:()=>{e({bookmarks:[]});}}),{name:"bookmarks",storage:Uo(()=>Cm)})),Tm="gh-inline-bookmark",Em="gh-inline-bookmark--bookmarked",Am="gh-inline-bookmark-global-styles",Mm="gh-inline-bookmark-scoped-styles";class Im{outlineManager;adapter;displayMode="always";unsubscribe=null;unsubscribeBookmarks=null;observer=null;injectDebounceTimer=null;injectedSignatures=new WeakMap;injectedRoots=new WeakSet;constructor(e,t,n="always"){this.outlineManager=e,this.adapter=t,this.displayMode=n,this.injectGlobalStyles(),this.setDisplayMode(n),this.unsubscribe=e.subscribe(()=>{this.injectBookmarkIcons();}),this.unsubscribeBookmarks=km.subscribe(()=>{this.updateAllIconStates();}),this.startDomObserver(),this.injectBookmarkIcons();}injectGlobalStyles(){if(document.getElementById(Am))return;const e=document.createElement("style");e.id=Am,e.textContent="\n :root {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.5;\n }\n\n body.gh-inline-bookmark-mode-always {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.3;\n }\n\n body.gh-inline-bookmark-mode-hover {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0; /* 默认隐藏 */\n --gh-icon-opacity-parent-hover: 0.5; /* 父元素悬停时显示 */\n }\n\n body.gh-inline-bookmark-mode-hidden {\n --gh-icon-display: none;\n --gh-icon-opacity-default: 0;\n }\n ",document.head.appendChild(e);}injectScopedStyles(e){if(this.injectedRoots.has(e))return;if(e instanceof Document){if(document.getElementById(Mm))return void this.injectedRoots.add(e)}else if(e.querySelector(`#${Mm}`))return void this.injectedRoots.add(e);const t=document.createElement("style");t.id=Mm,t.textContent=`\n .${Tm} {\n position: absolute;\n left: var(--gh-icon-left, -24px); /* 支持通过 CSS 变量调整位置 */\n top: 50%;\n transform: translateY(-50%);\n cursor: pointer;\n transition: opacity 0.2s, transform 0.2s;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n z-index: 10;\n color: var(--gh-primary, #f59e0b);\n\n /* 使用 CSS 变量控制显示 */\n display: var(--gh-icon-display, flex);\n opacity: var(--gh-icon-opacity-default, 0.3);\n }\n\n /* Hover Effects depend on local structure, so must be in scoped css */\n .${Tm}:hover {\n opacity: 1 !important;\n transform: translateY(-50%) scale(1.1);\n }\n\n .${Tm}.${Em} {\n opacity: 1 !important;\n }\n\n /* Parent Hover Effect */\n .gh-has-inline-bookmark:hover .${Tm}:not(.${Em}) {\n opacity: var(--gh-icon-opacity-parent-hover, 0.5);\n }\n\n /* Ensure parent relative positioning */\n .gh-has-inline-bookmark {\n position: relative !important;\n }\n `,e instanceof Document?document.head.appendChild(t):e.appendChild(t),this.injectedRoots.add(e);}setDisplayMode(e){this.displayMode=e,document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden"),document.body.classList.add(`gh-inline-bookmark-mode-${e}`),"hidden"===e&&this.removeInjectedIcons();}injectBookmarkIcons(){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const e=this.getInlineBookmarkItems(),t=this.adapter.getSessionId(),n=km.getState();for(let r=0;r{e.stopPropagation(),e.preventDefault(),this.handleBookmarkClick(o,s,d);}),i.insertBefore(d,i.firstChild),this.injectedSignatures.set(i,s);}}startDomObserver(){const e=this.adapter.getObserveTarget()??document.body;e&&(this.observer=new MutationObserver(()=>{this.scheduleInjectBookmarkIcons();}),this.observer.observe(e,{childList:true,subtree:true}));}scheduleInjectBookmarkIcons(){"hidden"!==this.displayMode&&(this.injectDebounceTimer&&clearTimeout(this.injectDebounceTimer),this.injectDebounceTimer=setTimeout(()=>{this.injectDebounceTimer=null,this.injectBookmarkIcons();},120));}getInlineBookmarkItems(){const e=[],t=new Set,n=n=>{n.forEach(n=>{const r=n.element;r&&!t.has(r)&&(t.add(r),e.push(n));});};return n(this.adapter.getInlineBookmarkItems()),n(this.outlineManager.getFlatItems()),e}createStarSvgElement(e){const t=ad("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:e?"#f59e0b":"none",stroke:e?"#f59e0b":"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),n=ad("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"});return t.appendChild(n),t}handleBookmarkClick(e,t,n){const r=km.getState(),o=this.adapter.getSessionId(),i=this.adapter.getSiteId(),a=this.adapter.getCurrentCid()||"",s=this.outlineManager.getScrollContainer(),l=e.element.offsetTop+(s?.scrollTop||0);r.toggleBookmark(o,i,a,e,t,l);}updateAllIconStates(){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const e=km.getState(),t=this.adapter.getSessionId();ds.query(`.${Tm}`,{all:true,shadow:true}).forEach(n=>{const r=n,o=r.dataset.signature;if(!o)return;const i=null!==e.getBookmarkId(t,o);i!==r.classList.contains(Em)&&(i?(r.classList.add(Em),r.replaceChildren(this.createStarSvgElement(true))):(r.classList.remove(Em),r.replaceChildren(this.createStarSvgElement(false))));});}removeInjectedIcons(){ds.query(`.${Tm}`,{all:true,shadow:true}).forEach(e=>e.remove());ds.query(".gh-has-inline-bookmark",{all:true,shadow:true}).forEach(e=>{e.classList.remove("gh-has-inline-bookmark");}),this.injectedSignatures=new WeakMap;}static cleanupInjectedArtifacts(){document.getElementById(Am)?.remove(),document.getElementById(Mm)?.remove();ds.query(`#${Mm}`,{all:true,shadow:true}).forEach(e=>e.remove());ds.query(`.${Tm}`,{all:true,shadow:true}).forEach(e=>e.remove());ds.query(".gh-has-inline-bookmark",{all:true,shadow:true}).forEach(e=>{e.classList.remove("gh-has-inline-bookmark");}),document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden");}cleanup(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.unsubscribeBookmarks&&(this.unsubscribeBookmarks(),this.unsubscribeBookmarks=null),this.observer&&(this.observer.disconnect(),this.observer=null),this.injectDebounceTimer&&(clearTimeout(this.injectDebounceTimer),this.injectDebounceTimer=null),Im.cleanupInjectedArtifacts(),this.injectedSignatures=new WeakMap,this.injectedRoots=new WeakSet;}}class Lm{siteAdapter;settings;tree=[];flatItems=[];flatNodes=[];scrollNodes=[];scrollPositions=[];scrollHeights=[];scrollPositionsStale=true;sources=[];activeSourceId="conversation";minLevel=1;treeKey="";listeners=[];updateIntervalId=null;isAutoUpdating=false;expandLevel=6;levelCounts={};isAllExpanded=false;searchQuery="";preSearchState=null;preSearchExpandLevel=null;searchLevelManual=false;matchCount=0;bookmarkMode=false;preBookmarkModeState=null;ghostBookmarkIds=new Set;wasGenerating=false;postGenerationScheduled=false;pendingPostGenerationRefresh=false;lastTreeChangeTime=0;fallbackRefreshTimer=null;static FALLBACK_DELAY=3e3;isActive=false;isRefreshing=false;unsubscribeBookmarks=null;onExpandLevelChange;onShowUserQueriesChange;constructor(e,t,n,r){this.siteAdapter=e,this.settings=t,this.onExpandLevelChange=n,this.onShowUserQueriesChange=r,this.sources=this.normalizeSources(this.siteAdapter.getOutlineSources()),this.expandLevel=t.expandLevel??6,window.addEventListener("message",this.handleMessage.bind(this)),this.unsubscribeBookmarks=km.subscribe(()=>{this.isActive&&this.refresh();});}setActive(e){this.isActive=e,this.updateAutoUpdateState(),e&&this.pendingPostGenerationRefresh&&(this.pendingPostGenerationRefresh=false,this.treeKey="",this.refresh());}updateAutoUpdateState(){const e=this.settings.enabled&&this.settings.autoUpdate&&this.isActive;e&&!this.isAutoUpdating?this.startAutoUpdate():!e&&this.isAutoUpdating&&this.stopAutoUpdate();const t=this.settings.enabled&&this.isActive&&this.siteAdapter.supportsDynamicOutlineSources();t&&!this.sourceObserver?this.startSourceObserver():!t&&this.sourceObserver&&this.stopSourceObserver();}updateSettings(e){this.settings=e,void 0!==e.expandLevel&&(this.expandLevel=e.expandLevel),this.refresh(),this.updateAutoUpdateState();}observer=null;updateDebounceTimer=null;sourceObserver=null;sourceRefreshTimer=null;outlineSourcesSignature="";handleMessage(e){if(e.source!==window)return;const{type:t}=e.data||{};"GH_MONITOR_START"===t?this.settings.autoUpdate&&this.startAutoUpdate():"GH_MONITOR_COMPLETE"===t&&(this.stopAutoUpdate(),this.refresh());}startAutoUpdate(){if(this.observer)return;this.isAutoUpdating=true,this.observer=new MutationObserver(()=>{this.triggerAutoUpdate();});const e=this.siteAdapter.getObserveTarget()??document.body;this.observer.observe(e,{childList:true,subtree:true,characterData:true});}stopAutoUpdate(){this.observer&&(this.observer.disconnect(),this.observer=null),this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null),this.isAutoUpdating=false;}startSourceObserver(){this.sourceObserver||(this.outlineSourcesSignature=this.siteAdapter.getOutlineSourcesSignature(),this.sourceObserver=new MutationObserver(()=>{this.sourceRefreshTimer||(this.sourceRefreshTimer=setTimeout(()=>{this.sourceRefreshTimer=null;const e=this.siteAdapter.getOutlineSourcesSignature();e!==this.outlineSourcesSignature&&(this.outlineSourcesSignature=e,this.refresh());},500));}),this.sourceObserver.observe(document.body,{childList:true,subtree:true}));}stopSourceObserver(){this.sourceObserver&&(this.sourceObserver.disconnect(),this.sourceObserver=null),this.sourceRefreshTimer&&(clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null);}triggerAutoUpdate(){const e=1e3*(this.settings.updateInterval||2);this.updateDebounceTimer||(this.updateDebounceTimer=setTimeout(()=>{this.executeAutoUpdate();},e));}executeAutoUpdate(){this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null);const e=this.siteAdapter.isGenerating();!this.wasGenerating||e||this.postGenerationScheduled||(this.postGenerationScheduled=true,setTimeout(()=>{this.postGenerationScheduled=false,this.isActive?(this.treeKey="",this.refresh()):this.pendingPostGenerationRefresh=true;},500)),this.wasGenerating=e;const t=this.treeKey;if(this.refresh(),this.treeKey!==t){this.lastTreeChangeTime=Date.now(),this.fallbackRefreshTimer&&clearTimeout(this.fallbackRefreshTimer);const e=this.treeKey;this.fallbackRefreshTimer=setTimeout(()=>{this.fallbackRefreshTimer=null,Date.now()-this.lastTreeChangeTime>=Lm.FALLBACK_DELAY-100&&this.treeKey===e&&(this.treeKey="",this.refresh());},Lm.FALLBACK_DELAY);}}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}notify(){this.listeners.forEach(e=>e());}normalizeSources(e){const t=e.filter(e=>e.available);return t.length>0?t:[{id:"conversation",kind:"conversation",label:"对话",available:true}]}updateSources(){const e=this.normalizeSources(this.siteAdapter.getOutlineSources()),t=e.map(e=>`${e.id}:${e.kind}:${e.label}:${e.count??""}`).join("|"),n=this.sources.map(e=>`${e.id}:${e.kind}:${e.label}:${e.count??""}`).join("|");return this.sources=e,this.sources.some(e=>e.id===this.activeSourceId)||(this.activeSourceId=this.sources[0]?.id??"conversation",this.treeKey=""),t!==n}getBookmarkSessionId(){const e=this.siteAdapter.getSessionId();return "conversation"===this.activeSourceId?e:`${e}::${this.activeSourceId}`}getTree(){return this.tree}getFlatItems(){return this.flatItems}getSources(){return this.sources}getActiveSourceId(){return this.activeSourceId}setActiveSource(e){if(e===this.activeSourceId)return;this.sources.find(t=>t.id===e&&t.available)&&(this.activeSourceId=e,this.tree=[],this.flatItems=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.treeKey="",this.preSearchState=null,this.preSearchExpandLevel=null,this.searchLevelManual=false,this.matchCount=0,this.refresh(),this.notify());}getSignature(e){return this.generateSignature(e)}getSearchQuery(){return this.searchQuery}getScrollContainer(){return this.siteAdapter.getOutlineScrollContainer(this.activeSourceId)}markScrollPositionsStale(){this.scrollPositionsStale=true;}setBookmarkMode(e){e&&!this.bookmarkMode?(this.preBookmarkModeState=this.saveTreeCollapsedState(this.tree),this.collapseAllExpandedState(this.tree),this.expandBookmarkPaths(this.tree)):!e&&this.bookmarkMode&&this.preBookmarkModeState&&(this.restoreTreeCollapsedState(this.tree,this.preBookmarkModeState),this.preBookmarkModeState=null),this.bookmarkMode=e,this.searchQuery&&this.performSearch(this.searchQuery),this.notify();}toggleBookmarkMode(){this.setBookmarkMode(!this.bookmarkMode);}getBookmarkMode(){return this.bookmarkMode}saveTreeCollapsedState(e){const t={},n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;t[o]=e.collapsed,e.children.forEach((e,t)=>n(e,`${o}/${t}`));};return e.forEach((e,t)=>n(e,`root/${t}`)),t}restoreTreeCollapsedState(e,t){const n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;o in t&&(e.collapsed=t[o]),e.children.forEach((e,t)=>n(e,`${o}/${t}`));};e.forEach((e,t)=>n(e,`root/${t}`));}collapseAllExpandedState(e){e.forEach(e=>{e.collapsed=true,e.children.length>0&&this.collapseAllExpandedState(e.children);});}expandBookmarkPaths(e){let t=false;return e.forEach(e=>{let n=false;e.children.length>0&&(n=this.expandBookmarkPaths(e.children)),n&&(e.collapsed=false),(e.isBookmarked||n)&&(t=true);}),t}extractUserQueryText(e){return this.siteAdapter.extractUserQueryText(e)}findElementByHeading(e,t){return this.siteAdapter.findElementByHeading(e,t)}findUserQueryElement(e,t){return this.siteAdapter.findUserQueryElement(e,t)}async resolveOutlineTarget(e,t){return this.siteAdapter.resolveOutlineTarget(e,t,this.activeSourceId)}scrollToOutlineTarget(e){this.siteAdapter.scrollToOutlineSourceTarget(e,this.activeSourceId);}getState(){const e=this.settings.showUserQueries?0:1;let t;t=this.searchQuery&&!this.searchLevelManual?100:this.expandLevel??6;const n=this.settings.showUserQueries?0:1;return tt.removeBookmark(e)),this.ghostBookmarkIds.clear(),this.refresh(),e.length}generateSignature(e){if(e.id)return "conversation"===this.activeSourceId?e.id:`${this.activeSourceId}:${e.id}`;let t="";if(e.context)t=e.context;else try{e.element?.nextElementSibling&&(t=(e.element.nextElementSibling.textContent||"").trim().substring(0,50));}catch{}const n=`${e.text}::${t}`;return "conversation"===this.activeSourceId?n:`${this.activeSourceId}:${n}`}toggleBookmark(e){const t=this.getBookmarkSessionId(),n=this.siteAdapter.getSiteId(),r=this.siteAdapter.getCurrentCid()||"",o=this.generateSignature(e);let i=0;e.element instanceof HTMLElement?i=e.element.offsetTop:void 0!==e.scrollTop&&(i=e.scrollTop);const a=km.getState(),s=a.getBookmarkId(t,o);s?(a.removeBookmark(s),e.isBookmarked=false,e.bookmarkId=void 0):(a.addBookmark(t,n,r,e,o,i),e.isBookmarked=true,e.bookmarkId=a.getBookmarkId(t,o)||void 0),this.notify();}refresh(e){if(this.settings.enabled&&!this.isRefreshing){this.isRefreshing=true;try{this._doRefresh(e);}finally{this.isRefreshing=false;}}}handleUrlChange(){this.tree=[],this.flatItems=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.treeKey="",this.levelCounts={},this.notify();for(const e of [80,250,600,1200])setTimeout(()=>this.refresh(),e);}_doRefresh(e){const t=this.updateSources(),n=Mi.getState().settings,r=n?.features?.outline?.showWordCount??false;let o=this.siteAdapter.extractOutlineForSource(this.activeSourceId,this.settings.maxLevel,this.settings.showUserQueries,r);const i=this.getBookmarkSessionId(),a=km.getState().getBookmarksBySession(i);if(this.ghostBookmarkIds=new Set,a.length>0){const e=new Set(a.map(e=>e.id));o.forEach(t=>{const n=this.generateSignature(t),r=a.find(e=>e.signature===n&&e.title===t.text);r&&(t.isBookmarked=true,t.bookmarkId=r.id,e.delete(r.id));});const t={},n={};e.forEach(e=>{const n=a.find(t=>t.id===e);n&&(t[n.title]||(t[n.title]=[]),t[n.title].push(n.id));}),o.forEach(e=>{e.isBookmarked||(n[e.text]||(n[e.text]=[]),n[e.text].push(e));});const r=km.getState();Object.keys(t).forEach(o=>{const i=t[o],a=n[o];if(i&&a&&1===i.length&&1===a.length){const t=i[0],n=a[0],o=this.generateSignature(n);r.updateBookmark(t,{signature:o}),n.isBookmarked=true,n.bookmarkId=t,e.delete(t);}}),this.ghostBookmarkIds=new Set(e);const i=[];if(e.forEach(e=>{const t=a.find(t=>t.id===e);if(t){if(0===t.level&&!this.settings.showUserQueries)return;i.push({level:t.level,text:t.title,element:null,isUserQuery:0===t.level,isBookmarked:true,isGhost:true,bookmarkId:t.id,scrollTop:t.scrollTop});}}),i.length>0){const e=e=>e.isGhost?e.scrollTop:e.element instanceof HTMLElement?e.element.offsetTop:0;o=[...o,...i].sort((t,n)=>e(t)-e(n));}}if(0===o.length)return void(this.tree.length>0?(this.tree=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.notify()):t&&this.notify());this.levelCounts={},o.forEach(e=>{this.levelCounts[e.level]=(this.levelCounts[e.level]||0)+1;});const s=o.filter(e=>!e.isUserQuery).map(e=>e.level);this.minLevel=s.length>0?Math.min(...s):1;const l=r?"wc:1":"wc:0",c=this.siteAdapter.getSessionId()||"no-session",d="undefined"!=typeof window?window.location.pathname:"",u=function(e){let t=5381;for(let n=0;n>>0;return t.toString(16).padStart(8,"0")}(`${this.siteAdapter.getSiteId()}:${c}:${d}:${this.activeSourceId}`+"|"+l+"|"+o.map(e=>`${e.text}:${e.isBookmarked}`).join("|")),h={};if(this.tree.length>0&&this.captureTreeState(this.tree,h),this.treeKey===u&&0!==this.tree.length&&void 0===e){let e=false;const n=this.siteAdapter.getSiteId();return n!==go&&n!==yo||(e=this.syncFlatNodeRuntimeData(o)),this.scrollPositionsStale=true,void((e||t)&&this.notify())}this.tree=this.buildTree(o,this.minLevel),this.treeKey=u,this.flatItems=o,this.flatNodes=this.flattenTree(this.tree),this.updateScrollPositions();const g=void 0!==e?e:this.expandLevel??6;this.expandLevel=g;const p=this.settings.showUserQueries?0:1,m=g0&&this.restoreTreeState(this.tree,h),this.searchQuery&&this.performSearch(this.searchQuery),this.bookmarkMode&&this.expandBookmarkPaths(this.tree);const f=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=this.expandLevel>=f,this.notify();}buildTree(e,t){const n=[],r=[];let o=0;return e.forEach((e,i)=>{const a=e.isUserQuery?0:e.level-t+1;let s;e.isUserQuery&&(o++,s=o);const l={...e,relativeLevel:a,index:i,queryIndex:s,children:[],collapsed:false},c=e;for(c.isBookmarked&&(l.isBookmarked=true),c.isGhost&&(l.isGhost=true),c.bookmarkId&&(l.bookmarkId=c.bookmarkId);r.length>0&&r[r.length-1].relativeLevel>=a;)r.pop();0===r.length?n.push(l):r[r.length-1].children.push(l),r.push(l);}),n}syncFlatNodeRuntimeData(e){let t=this.flatItems.length!==e.length;return this.flatItems=e,e.forEach((e,n)=>{const r=this.flatNodes[n];if(!r)return void(t=true);const o=e;(r.element!==e.element||r.id!==e.id||r.navigationId!==e.navigationId||r.context!==e.context||r.wordCount!==e.wordCount||r.isTruncated!==e.isTruncated||r.isUserQuery!==e.isUserQuery||r.isBookmarked!==o.isBookmarked||r.isGhost!==o.isGhost||r.bookmarkId!==o.bookmarkId||void 0!==o.scrollTop&&r.scrollTop!==o.scrollTop)&&(t=true),r.element=e.element,r.id=e.id,r.navigationId=e.navigationId,r.context=e.context,r.wordCount=e.wordCount,r.isTruncated=e.isTruncated,r.isUserQuery=e.isUserQuery,r.isBookmarked=o.isBookmarked,r.isGhost=o.isGhost,r.bookmarkId=o.bookmarkId,void 0!==o.scrollTop&&(r.scrollTop=o.scrollTop);}),t}flattenTree(e){const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children.length>0&&n(e.children);});};return n(e),t}updateScrollPositions(){this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[];const e=this.getScrollContainer();if(!e||0===this.flatNodes.length)return;const t=e.getBoundingClientRect().top,n=e.scrollTop,r=[];let o=0;const i=this.shouldKeepPreviousVisibleItem(),a=e=>{const t=e.scrollTop;if(!i||"number"!=typeof t||Number.isNaN(t))return false;const n="number"!=typeof e.scrollHeight||Number.isNaN(e.scrollHeight)?0:e.scrollHeight;return r.push({node:e,top:t,height:n,order:o}),o+=1,true};if(this.flatNodes.forEach(e=>{if(e.isGhost)return;let i=e.element;if(i&&i.isConnected||("conversation"===this.activeSourceId&&(i=e.isUserQuery&&0===e.level&&void 0!==e.queryIndex?this.findUserQueryElement(e.queryIndex,e.text):this.findElementByHeading(e.level,e.text)),i&&(e.element=i)),!i||!i.isConnected)return void a(e);const s=i.getClientRects();if(0===s.length)return void a(e);const l=i.getBoundingClientRect(),c=l.top-t+n,d=l.height||s[0]?.height||0;e.scrollTop=c,e.scrollHeight=d,r.push({node:e,top:c,height:d,order:o}),o+=1;}),0===r.length)return void(this.scrollPositionsStale=false);let s=true;for(let l=1;le.top===t.top?e.order-t.order:e.top-t.top),r.forEach(e=>{this.scrollNodes.push(e.node),this.scrollPositions.push(e.top),this.scrollHeights.push(e.height);}),this.scrollPositionsStale=false;}captureTreeState(e,t){e.forEach(e=>{const n=e.id?`id:${e.id}`:`${e.level}_${e.text}`,r=e.children&&e.children.length>0;t[n]={collapsed:e.collapsed,forceExpanded:e.forceExpanded,hadChildren:r},r&&this.captureTreeState(e.children,t);});}restoreTreeState(e,t){e.forEach(e=>{const n=e.id?`id:${e.id}`:`${e.level}_${e.text}`,r=t[n];if(r){const t=e.children&&e.children.length>0;!r.hadChildren&&t||(e.collapsed=r.collapsed),void 0!==r.forceExpanded&&(e.forceExpanded=r.forceExpanded);}e.children.length>0&&this.restoreTreeState(e.children,t);});}initializeCollapsedState(e,t){e.forEach(e=>{if(e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.initializeCollapsedState(e.children,t);}else e.collapsed=false;});}clearForceExpandedState(e,t){e.forEach(e=>{if(e.forceExpanded=false,e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.clearForceExpandedState(e.children,t);}else e.collapsed=false;});}toggleNode(e){e.collapsed=!e.collapsed,e.collapsed||(e.forceExpanded=true),this.notify();}collapseAll(){const e=this.settings.showUserQueries?0:this.minLevel||1;this.setLevel(e);}expandAll(){const e=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.setLevel(e);}setLevel(e){if(this.bookmarkMode)return void Pi(le("bookmarkModeDisableLevel"));this.expandLevel=e,this.tree.length>0&&this.clearForceExpandedState(this.tree,e);const t=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=e>=t,this.searchQuery&&(this.searchLevelManual=true),this.onExpandLevelChange&&this.onExpandLevelChange(e),this.notify();}setShowUserQueries(e){this.settings.showUserQueries=e,this.refresh(),this.notify(),this.onShowUserQueriesChange&&this.onShowUserQueriesChange(e);}toggleGroupMode(){this.setShowUserQueries(!this.settings.showUserQueries);}revealNode(e){const t=e=>{e.forEach(e=>{e.forceVisible=false,e.children&&e.children.length>0&&t(e.children);});};t(this.tree);const n=(e,t,r=[])=>{for(const o of e){if(o.index===t)return r.forEach(e=>{e.collapsed=false,e.forceExpanded=true,e.forceVisible=true;}),o.forceVisible=true,true;if(o.children&&o.children.length>0&&n(o.children,t,[...r,o]))return true}return false};n(this.tree,e)&&this.notify();}clearForceVisible(){const e=t=>{t.forEach(t=>{if(t.forceVisible&&(t.forceVisible=false,t.forceExpanded=false,t.children&&t.children.length>0)){const e=t.children.every(e=>e.relativeLevel>this.expandLevel);t.collapsed=e;}t.children&&t.children.length>0&&e(t.children);});};e(this.tree),this.notify();}setSearchQuery(e){if(e)!this.searchQuery&&this.tree.length>0&&(this.preSearchState={},this.captureTreeState(this.tree,this.preSearchState),this.preSearchExpandLevel=this.expandLevel),this.tree.length>0&&this.clearForceExpandedState(this.tree,0),this.searchQuery=e,this.searchLevelManual=false,this.performSearch(e);else if(this.searchQuery="",this.searchLevelManual=false,this.tree.length>0){null!==this.preSearchExpandLevel&&(this.expandLevel=this.preSearchExpandLevel,this.preSearchExpandLevel=null);const e=this.expandLevel??6;this.clearForceExpandedState(this.tree,e),this.preSearchState&&(this.restoreTreeState(this.tree,this.preSearchState),this.preSearchState=null);}this.notify();}performSearch(e){const t=e=>e.toLowerCase(),n=t(e);let r=0;const o=e=>{let i=false;return e.forEach(e=>{const a=t(e.text).includes(n);if(e.isMatch=a,a)if(this.bookmarkMode){const t=e=>!!e.isBookmarked||(e.children?.some(t)||false);(e.isBookmarked||t(e))&&r++;}else r++;if(e.children.length>0){let t=true;if(this.bookmarkMode){const n=e=>!!e.isBookmarked||(e.children?.some(n)||false);e.isBookmarked&&!e.children.some(n)&&(t=false);}e.hasMatchedDescendant=!!t&&o(e.children);}else e.hasMatchedDescendant=false;e.hasMatchedDescendant&&(e.collapsed=false),(a||e.hasMatchedDescendant)&&(i=true);}),i};o(this.tree),this.matchCount=r;}findVisibleItemIndex(e,t){if("current"!==this.settings.followMode)return null;this.scrollPositionsStale&&this.updateScrollPositions();const n=this.scrollNodes.length;if(0===n)return null;const r=e,o=e+t;let i=0,a=n-1,s=-1;for(;i<=a;){const e=i+a>>1;this.scrollPositions[e]<=r?(s=e,i=e+1):a=e-1;}if(s>=0){const e=this.scrollPositions[s],t=this.scrollHeights[s]||0;return er)?this.scrollNodes[s].index:s+1(Nm=()=>e({_hasHydrated:true}),{prompts:io(),_hasHydrated:false,addPrompt:t=>{const n={id:"custom_"+Date.now(),...t};return e(e=>({prompts:[...e.prompts,n]})),n},updatePrompt:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,...n}:e)})),deletePrompt:t=>e(e=>({prompts:e.prompts.filter(e=>e.id!==t)})),renameCategory:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),deleteCategory:(t,n="未分类")=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),updateOrder:t=>e(e=>{const n=[];return t.forEach(t=>{const r=e.prompts.find(e=>e.id===t);r&&n.push(r);}),e.prompts.forEach(e=>{n.find(t=>t.id===e.id)||n.push(e);}),{prompts:n}}),setHasHydrated:t=>e({_hasHydrated:t}),togglePin:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,pinned:!e.pinned}:e)})),updateLastUsed:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,lastUsedAt:Date.now()}:e)})),setPrompts:t=>e({prompts:t})}),{name:"prompts",storage:Uo(()=>gi),partialize:e=>({prompts:e.prompts}),onRehydrateStorage:()=>()=>{Nm?.();}})),Dm=()=>Rm.getState().prompts,Pm=()=>Rm.getState(),qm=()=>{const e=Dm(),t=new Set;return e.forEach(e=>{e.category&&t.add(e.category);}),Array.from(t)},Bm=(e="",t=Ao)=>{let n=Dm();if(t!==Ao&&t!==Mo&&(n=n.filter(e=>e.category===t)),e){const t=e.toLowerCase();n=n.filter(e=>e.title.toLowerCase().includes(t)||e.content.toLowerCase().includes(t));}return n},$m=Object.freeze(Object.defineProperty({__proto__:null,filterPrompts:Bm,getCategories:qm,getPromptsState:Dm,getPromptsStore:Pm,usePromptsStore:Rm},Symbol.toStringTag,{value:"Module"}));function _m(){if("undefined"==typeof navigator)return false;const e=navigator.userAgentData;if(e?.mobile)return true;const t=[navigator.platform,e?.platform,navigator.userAgent].filter(Boolean).join(" ").toLowerCase();return !!/(android|iphone|ipad|ipod|mobile|tablet|windows phone)/.test(t)||/mac/.test(t)&&navigator.maxTouchPoints>1}const Om="ophel:aistudio-submit-shortcut-synced";class zm{adapter;constructor(e){this.adapter=e;}async init(){Rm.getState()._hasHydrated||await new Promise(e=>{const t=Rm.subscribe(n=>{n._hasHydrated&&(t(),e());});});}getPrompts(){return Pm().prompts}addPrompt(e){return Pm().addPrompt(e)}updatePrompt(e,t){Pm().updatePrompt(e,t);}deletePrompt(e){Pm().deletePrompt(e);}getCategories(){return qm()}renameCategory(e,t){Pm().renameCategory(e,t);}deleteCategory(e,t="未分类"){Pm().deleteCategory(e,t);}updateOrder(e){Pm().updateOrder(e);}filterPrompts(e="",t=Ao){return Bm(e,t)}togglePin(e){Pm().togglePin(e);}updateLastUsed(e){Pm().updateLastUsed(e);}setPrompts(e){Pm().setPrompts(e);}async insertPrompt(e){const t=[0,80,120,180,240];for(let n=0;n0&&await new Promise(e=>setTimeout(e,t[n])),this.adapter.findTextarea();if(this.adapter.insertPrompt(e))return true}return false}getEditorContent(e){return e?e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement?e.value||"":e.textContent||"":""}isElementDisabled(e){if(!e)return true;if(e instanceof HTMLButtonElement&&e.disabled)return true;if(e.hasAttribute("disabled"))return true;return "true"===e.getAttribute("aria-disabled")||"true"===e.getAttribute("data-disabled")}isElementVisible(e){if(!e||!e.isConnected)return false;if(e.closest(".gh-main-panel"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}collectSubmitButtons(e){const t=[],n=new Set;for(const r of e){const e=ds.query(r,{all:true,shadow:true});if(e&&Array.isArray(e))for(const r of e)r instanceof HTMLElement&&!n.has(r)&&(n.add(r),t.push(r));}return t}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}findBestSubmitButton(e,t){const n=this.adapter.findSubmitButton(t);if(n&&this.isElementVisible(n))return n;const r=this.collectSubmitButtons(e).filter(e=>this.isElementVisible(e));if(0===r.length)return null;if(!t||!t.isConnected)return r[0];const o=t.closest("form");if(o){const e=r.filter(e=>e.closest("form")===o);if(e.length>0){return e.find(e=>!this.isElementDisabled(e))||e[0]}}const i=t.getBoundingClientRect();let a=r[0],s=Number.POSITIVE_INFINITY;for(const l of r){const e=this.getRectDistance(i,l.getBoundingClientRect());esetTimeout(e,50));}return null}getEffectiveSubmitShortcut(e){return this.adapter.getSiteId()===bo&&_m()?"ctrlEnter":e}syncAiStudioSubmitShortcut(e="enter"){if(this.adapter.getSiteId()!==bo)return false;const t=this.getEffectiveSubmitShortcut(e)??e,n=t!==e,r="ctrlEnter"===t?2:1;let o={};const i=localStorage.getItem("aiStudioUserPreference");if(i)try{const e=JSON.parse(i);e&&"object"==typeof e&&(o=e);}catch{}if(o.enterKeyBehavior===r)return false;try{localStorage.setItem("aiStudioUserPreference",JSON.stringify({...o,enterKeyBehavior:r}));}catch{return false}return window.dispatchEvent(new CustomEvent(Om,{detail:{submitShortcut:t,forcedByMobile:n}})),true}async waitForSubmitConfirmation(e,t,n){const r=Date.now()+1500,o=e.trim().length>0;for(;Date.now()0){const e=this.findBestSubmitButton(t,r);if(!e&&n.button&&!n.button.isConnected)return true;if(e&&!n.wasDisabled&&this.isElementDisabled(e))return true}await new Promise(e=>setTimeout(e,60));}return false}resolveSubmitKeyConfig(e){const t=this.getEffectiveSubmitShortcut(e);return "ctrlEnter"===t?{key:"Ctrl+Enter"}:"enter"===t?{key:"Enter"}:this.adapter.getSubmitKeyConfig()}dispatchSubmitByKeyboard(e,t){e.focus();const n="Ctrl+Enter"===this.resolveSubmitKeyConfig(t).key,r=/Mac|iPhone|iPad|iPod/.test(navigator.platform),o={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,ctrlKey:n&&!r,metaKey:n&&r,shiftKey:false};return e.dispatchEvent(new KeyboardEvent("keydown",o)),e.dispatchEvent(new KeyboardEvent("keypress",o)),e.dispatchEvent(new KeyboardEvent("keyup",o)),true}shouldRetryWithKeyboard(e){if(this.adapter.isGenerating?.())return false;const t=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;const n=this.getEditorContent(t).replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim(),r=e.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();return !!n&&(!!r&&(n===r||n.includes(r)||r.includes(n)))}async submitPrompt(e){this.syncAiStudioSubmitShortcut(e??"enter");const t=this.adapter.getSubmitButtonSelectors(),n=this.adapter.getTextareaElement()||this.adapter.findTextarea(),r=this.getEditorContent(n),o=r.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();let i=false,a=null,s=null,l=true;if(t.length>0){s=this.findBestSubmitButton(t,n),l=this.isElementDisabled(s);let e=s;if(l){const r=null===s?2e3:500,o=await this.waitForEnabledSubmitButton(t,n,r);o&&(e=o,s=o,l=false);}e&&!this.isElementDisabled(e)&&(e.click(),a=e,i=true);}if(!i){if(!o)return false;const t=n||this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;i=this.dispatchSubmitByKeyboard(t,e);}if(!i)return false;let c=await this.waitForSubmitConfirmation(r,t,{button:a||s,clicked:!!a,wasDisabled:l});if(c)return true;if(!a||!this.shouldRetryWithKeyboard(r))return false;const d=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!d)return false;return !!this.dispatchSubmitByKeyboard(d,e)&&(c=await this.waitForSubmitConfirmation(r,t,{button:this.findBestSubmitButton(t,d),clicked:false,wasDisabled:false}),c)}}const Fm=e=>({id:`q_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,content:e,createdAt:Date.now(),status:"pending",type:"prompt"}),Um=Fo()((e,t)=>({items:[],isProcessing:false,isPaused:false,enqueue:t=>{const n=Fm(t);return e(e=>({items:[...e.items,n]})),n},enqueueMany:t=>{const n=t.map(e=>e.trim()).filter(Boolean).map(e=>Fm(e));return 0===n.length?[]:(e(e=>({items:[...e.items,...n]})),n)},dequeue:()=>{const{items:n}=t(),r=n.find(e=>"pending"===e.status);return r?(e(e=>({items:e.items.map(e=>e.id===r.id?{...e,status:"sending"}:e),isProcessing:true})),r):null},remove:t=>e(e=>({items:e.items.filter(e=>e.id!==t)})),updateContent:(t,n)=>e(e=>({items:e.items.map(e=>e.id===t?{...e,content:n}:e)})),updateStatus:(t,n)=>e(e=>{const r=e.items.map(e=>e.id===t?{...e,status:n}:e),o=r.some(e=>"pending"===e.status||"sending"===e.status);return {items:r,isProcessing:o}}),clear:()=>e({items:[],isProcessing:false}),pause:()=>e({isPaused:true}),resume:()=>e({isPaused:false})}));class Hm{adapter;promptManager;intervalId=null;idleCount=0;IDLE_THRESHOLD=2;POLL_INTERVAL=1e3;constructor(e,t){this.adapter=e,this.promptManager=t;}start(){this.intervalId||(this.idleCount=0,this.intervalId=setInterval(()=>this.tick(),this.POLL_INTERVAL));}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.idleCount=0;}isRunning(){return null!==this.intervalId}async tick(){const e=Um.getState();if(0===e.items.filter(e=>"pending"===e.status).length||e.isPaused)return void(this.idleCount=0);if(e.items.filter(e=>"sending"===e.status).length>0)return void(this.idleCount=0);this.adapter.isGenerating()?this.idleCount=0:(this.idleCount++,this.idleCount>=this.IDLE_THRESHOLD&&(this.idleCount=0,await this.dispatchNext()));}async dispatchNext(){const e=Um.getState(),t=e.dequeue();if(t)try{if(!(await this.promptManager.insertPrompt(t.content)))return void e.updateStatus(t.id,"failed");const n=Mi.getState().settings.features?.prompts?.submitShortcut??"enter";if(!(await this.promptManager.submitPrompt(n)))return void e.updateStatus(t.id,"failed");e.updateStatus(t.id,"sent");}catch(RS){console.error("[QueueDispatcher] 发送失败:",RS),e.updateStatus(t.id,"failed");}}async sendImmediately(e,t){try{if(!(await this.promptManager.insertPrompt(e)))return !1;return await this.promptManager.submitPrompt(t)}catch(RS){return console.error("[QueueDispatcher] 立即发送失败:",RS),false}}async processNextNow(){const e=Um.getState();if(e.isPaused)return false;if(this.adapter.isGenerating())return false;if(e.items.some(e=>"sending"===e.status))return false;return !!e.items.some(e=>"pending"===e.status)&&(this.idleCount=0,await this.dispatchNext(),true)}}const Wm=[{id:"google-gradient",name:"Google 渐变",description:"默认主题,蓝绿渐变 Header",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f9fafb","--gh-bg-tertiary":"#f3f4f6","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e5e7eb","--gh-border-active":"#4285f4","--gh-hover":"#f3f4f6","--gh-active-bg":"#e5e7eb","--gh-input-bg":"#ffffff","--gh-input-border":"#d1d5db","--gh-input-focus-border":"#4285f4","--gh-input-focus-shadow":"0 0 0 2px rgba(66, 133, 244, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(66, 133, 244, 0.3)","--gh-primary":"#4285f4","--gh-secondary":"#34a853","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-tag-active-bg":"#4285f4","--gh-checkbox-bg":"#4f46e5","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e5e7eb","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(66, 133, 244, 0.1) 0%, rgba(52, 211, 153, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#c7d2fe","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(16, 185, 129, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(52, 211, 153, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(66, 133, 244, 0.08)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e5e7eb","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(59, 130, 246, 0.3)","--gh-slider-dot-bg":"#d1d5db","--gh-code-bg":"rgba(0, 0, 0, 0.05)"}},{id:"purple",name:"紫罗兰",description:"优雅紫色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#faf5ff","--gh-bg-tertiary":"#f3e8ff","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#8b5cf6","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#d8b4fe","--gh-input-focus-border":"#8b5cf6","--gh-input-focus-shadow":"0 0 0 2px rgba(139, 92, 246, 0.1)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(139, 92, 246, 0.3)","--gh-primary":"#8b5cf6","--gh-secondary":"#a855f7","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-tag-active-bg":"#8b5cf6","--gh-checkbox-bg":"#8b5cf6","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(139, 92, 246, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(139, 92, 246, 0.08)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(139, 92, 246, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(139, 92, 246, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#f3e8ff","--gh-highlight-pulse":"rgba(139, 92, 246, 0.3)","--gh-slider-dot-bg":"#d8b4fe","--gh-code-bg":"rgba(139, 92, 246, 0.08)"}},{id:"ocean",name:"海洋蓝",description:"清新海洋主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f0f9ff","--gh-bg-tertiary":"#e0f2fe","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#bae6fd","--gh-border-active":"#0ea5e9","--gh-hover":"#e0f2fe","--gh-active-bg":"#bae6fd","--gh-input-bg":"#ffffff","--gh-input-border":"#7dd3fc","--gh-input-focus-border":"#0ea5e9","--gh-input-focus-shadow":"0 0 0 2px rgba(14, 165, 233, 0.1)","--gh-shadow":"0 10px 40px rgba(14, 165, 233, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(14, 165, 233, 0.3)","--gh-primary":"#0ea5e9","--gh-secondary":"#06b6d4","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-tag-active-bg":"#0ea5e9","--gh-checkbox-bg":"#0ea5e9","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#bae6fd","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(14, 165, 233, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#bae6fd","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(14, 165, 233, 0.25)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.5)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.1)","--gh-outline-sync-border":"#fb923c","--gh-user-query-bg":"rgba(14, 165, 233, 0.08)","--gh-user-query-hover-bg":"rgba(14, 165, 233, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#bae6fd","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(14, 165, 233, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(14, 165, 233, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#e0f2fe","--gh-highlight-pulse":"rgba(14, 165, 233, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(14, 165, 233, 0.08)"}},{id:"sakura",name:"樱花物语",description:"柔美粉色主题",variables:{"--gh-bg":"#fff5f7","--gh-bg-secondary":"#fff0f3","--gh-bg-tertiary":"#ffe4e9","--gh-text":"#4a0418","--gh-text-secondary":"#9d4f64","--gh-text-tertiary":"#d48aa0","--gh-text-on-primary":"#881337","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fecdd3","--gh-border-active":"#fb7185","--gh-hover":"#ffe4e9","--gh-active-bg":"#fecdd3","--gh-input-bg":"#ffffff","--gh-input-border":"#fda4af","--gh-input-focus-border":"#fb7185","--gh-input-focus-shadow":"0 0 0 2px rgba(251, 113, 133, 0.2)","--gh-shadow":"0 10px 40px rgba(251, 113, 133, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(255, 179, 193, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(251, 113, 133, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-primary":"#fb7185","--gh-secondary":"#f43f5e","--gh-danger":"#e11d48","--gh-header-bg":"linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)","--gh-tag-active-bg":"#fb7185","--gh-checkbox-bg":"#fb7185","--gh-badge-text":"#881337","--gh-badge-bg":"#fff1f2","--gh-badge-border":"#fecdd3","--gh-badge-shadow":"#fff0f3","--gh-selected-gradient":"linear-gradient(135deg, rgba(251, 113, 133, 0.15) 0%, rgba(244, 63, 94, 0.1) 100%)","--gh-folder-bg-default":"#fff1f2","--gh-folder-bg-expanded":"#ffe4e6","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#f5f3ff","--gh-outline-locate-bg":"rgba(251, 113, 133, 0.2)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(251, 113, 133, 0.08)","--gh-user-query-hover-bg":"rgba(251, 113, 133, 0.15)","--gh-bg-danger":"#fff1f2","--gh-text-danger":"#e11d48","--gh-bg-danger-hover":"#ffe4e6","--gh-brand-gradient":"linear-gradient(135deg, #fb7185 0%, #f43f5e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#881337","--gh-card-bg":"#ffffff","--gh-card-border":"#ffe4e6","--gh-overlay-bg":"rgba(255, 241, 242, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(251, 113, 133, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ffe4e6","--gh-highlight-pulse":"rgba(251, 113, 133, 0.3)","--gh-slider-dot-bg":"#fda4af","--gh-code-bg":"rgba(251, 113, 133, 0.08)"}},{id:"mint",name:"清新薄荷",description:"活力青绿主题",variables:{"--gh-bg":"#f0fdf9","--gh-bg-secondary":"#e6fffa","--gh-bg-tertiary":"#ccfbf1","--gh-text":"#134e4a","--gh-text-secondary":"#2d7a74","--gh-text-tertiary":"#5eead4","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#99f6e4","--gh-border-active":"#2dd4bf","--gh-hover":"#ccfbf1","--gh-active-bg":"#99f6e4","--gh-input-bg":"#ffffff","--gh-input-border":"#5eead4","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.2)","--gh-shadow":"0 10px 40px rgba(45, 212, 191, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(45, 212, 191, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(45, 212, 191, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#14b8a6","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #14b8a6 0%, #34d399 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#115e59","--gh-badge-bg":"#ccfbf1","--gh-badge-border":"#99f6e4","--gh-badge-shadow":"#e6fffa","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.15) 0%, rgba(20, 184, 166, 0.1) 100%)","--gh-folder-bg-default":"#ccfbf1","--gh-folder-bg-expanded":"#99f6e4","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#f43f5e","--gh-outline-locate-shadow":"rgba(244, 63, 94, 0.5)","--gh-outline-sync-bg":"rgba(244, 63, 94, 0.1)","--gh-outline-sync-border":"#fb7185","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #14b8a6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#115e59","--gh-card-bg":"#ffffff","--gh-card-border":"#99f6e4","--gh-overlay-bg":"rgba(240, 253, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(45, 212, 191, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ccfbf1","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#5eead4","--gh-code-bg":"rgba(45, 212, 191, 0.1)"}},{id:"nordic",name:"北欧霜雪",description:"极简冷淡主题",variables:{"--gh-bg":"#f8fafc","--gh-bg-secondary":"#f1f5f9","--gh-bg-tertiary":"#e2e8f0","--gh-text":"#0f172a","--gh-text-secondary":"#475569","--gh-text-tertiary":"#94a3b8","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#cbd5e1","--gh-border-active":"#64748b","--gh-hover":"#e2e8f0","--gh-active-bg":"#cbd5e1","--gh-input-bg":"#ffffff","--gh-input-border":"#cbd5e1","--gh-input-focus-border":"#64748b","--gh-input-focus-shadow":"0 0 0 2px rgba(100, 116, 139, 0.15)","--gh-shadow":"0 10px 40px rgba(15, 23, 42, 0.08)","--gh-shadow-sm":"0 1px 3px rgba(15, 23, 42, 0.05)","--gh-shadow-lg":"0 20px 60px rgba(15, 23, 42, 0.12)","--gh-shadow-brand":"0 4px 12px rgba(100, 116, 139, 0.2)","--gh-primary":"#64748b","--gh-secondary":"#475569","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-tag-active-bg":"#64748b","--gh-checkbox-bg":"#64748b","--gh-badge-text":"#334155","--gh-badge-bg":"#f1f5f9","--gh-badge-border":"#cbd5e1","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(100, 116, 139, 0.1) 0%, rgba(71, 85, 105, 0.08) 100%)","--gh-folder-bg-default":"#f1f5f9","--gh-folder-bg-expanded":"#e2e8f0","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(100, 116, 139, 0.15)","--gh-outline-locate-border":"#ef4444","--gh-outline-locate-shadow":"rgba(239, 68, 68, 0.5)","--gh-outline-sync-bg":"rgba(239, 68, 68, 0.1)","--gh-outline-sync-border":"#f87171","--gh-user-query-bg":"rgba(100, 116, 139, 0.06)","--gh-user-query-hover-bg":"rgba(100, 116, 139, 0.12)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#cbd5e1","--gh-overlay-bg":"rgba(241, 245, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(100, 116, 139, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(100, 116, 139, 0.25)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e2e8f0","--gh-highlight-pulse":"rgba(100, 116, 139, 0.25)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(100, 116, 139, 0.06)"}},{id:"lemon-soda",name:"柠檬苏打",description:"明亮活力主题",variables:{"--gh-bg":"#fefce8","--gh-bg-secondary":"#fef9c3","--gh-bg-tertiary":"#fde047","--gh-text":"#854d0e","--gh-text-secondary":"#a16207","--gh-text-tertiary":"#ca8a04","--gh-text-on-primary":"#854d0e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde047","--gh-border-active":"#eab308","--gh-hover":"#fef9c3","--gh-active-bg":"#fde047","--gh-input-bg":"#ffffff","--gh-input-border":"#fde047","--gh-input-focus-border":"#eab308","--gh-input-focus-shadow":"0 0 0 2px rgba(234, 179, 8, 0.2)","--gh-shadow":"0 10px 40px rgba(234, 179, 8, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(234, 179, 8, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(234, 179, 8, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-primary":"#eab308","--gh-secondary":"#ca8a04","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-tag-active-bg":"#eab308","--gh-checkbox-bg":"#eab308","--gh-badge-text":"#854d0e","--gh-badge-bg":"#fef9c3","--gh-badge-border":"#fde047","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(234, 179, 8, 0.15) 0%, rgba(132, 204, 22, 0.1) 100%)","--gh-folder-bg-default":"#fef9c3","--gh-folder-bg-expanded":"#fde047","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(234, 179, 8, 0.2)","--gh-outline-locate-border":"#3b82f6","--gh-outline-locate-shadow":"rgba(59, 130, 246, 0.5)","--gh-outline-sync-bg":"rgba(59, 130, 246, 0.1)","--gh-outline-sync-border":"#60a5fa","--gh-user-query-bg":"rgba(234, 179, 8, 0.08)","--gh-user-query-hover-bg":"rgba(234, 179, 8, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#854d0e","--gh-card-bg":"#ffffff","--gh-card-border":"#fde047","--gh-overlay-bg":"rgba(254, 252, 232, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(234, 179, 8, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.8)","--gh-emoji-selected-bg":"#fde047","--gh-highlight-pulse":"rgba(234, 179, 8, 0.3)","--gh-slider-dot-bg":"#d4d4d8","--gh-code-bg":"rgba(234, 179, 8, 0.1)"}},{id:"ancient-scroll",name:"羊皮卷",description:"复古纸张主题",variables:{"--gh-bg":"#fffbeb","--gh-bg-secondary":"#fef3c7","--gh-bg-tertiary":"#fde68a","--gh-text":"#451a03","--gh-text-secondary":"#92400e","--gh-text-tertiary":"#b45309","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde68a","--gh-border-active":"#d97706","--gh-hover":"#fef3c7","--gh-active-bg":"#fde68a","--gh-input-bg":"#ffffff","--gh-input-border":"#fcd34d","--gh-input-focus-border":"#d97706","--gh-input-focus-shadow":"0 0 0 2px rgba(217, 119, 6, 0.2)","--gh-shadow":"0 10px 40px rgba(146, 64, 14, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(146, 64, 14, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(146, 64, 14, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(217, 119, 6, 0.25)","--gh-primary":"#d97706","--gh-secondary":"#b45309","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-tag-active-bg":"#d97706","--gh-checkbox-bg":"#d97706","--gh-badge-text":"#78350f","--gh-badge-bg":"#fef3c7","--gh-badge-border":"#fcd34d","--gh-badge-shadow":"#fffbeb","--gh-selected-gradient":"linear-gradient(135deg, rgba(217, 119, 6, 0.15) 0%, rgba(146, 64, 14, 0.1) 100%)","--gh-folder-bg-default":"#fef3c7","--gh-folder-bg-expanded":"#fde68a","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(217, 119, 6, 0.2)","--gh-outline-locate-border":"#0d9488","--gh-outline-locate-shadow":"rgba(13, 148, 136, 0.5)","--gh-outline-sync-bg":"rgba(13, 148, 136, 0.1)","--gh-outline-sync-border":"#14b8a6","--gh-user-query-bg":"rgba(217, 119, 6, 0.08)","--gh-user-query-hover-bg":"rgba(217, 119, 6, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#78350f","--gh-card-bg":"#fffbeb","--gh-card-border":"#fde68a","--gh-overlay-bg":"rgba(255, 251, 235, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(217, 119, 6, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(217, 119, 6, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#fde68a","--gh-highlight-pulse":"rgba(217, 119, 6, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(217, 119, 6, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.12'/%3E%3C/svg%3E\")"}},{id:"mono-pro",name:"极致黑白",description:"纯粹单色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f4f4f5","--gh-bg-tertiary":"#e4e4e7","--gh-text":"#09090b","--gh-text-secondary":"#52525b","--gh-text-tertiary":"#a1a1aa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e4e4e7","--gh-border-active":"#18181b","--gh-hover":"#f4f4f5","--gh-active-bg":"#e4e4e7","--gh-input-bg":"#ffffff","--gh-input-border":"#d4d4d8","--gh-input-focus-border":"#18181b","--gh-input-focus-shadow":"0 0 0 2px rgba(24, 24, 27, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.12)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-primary":"#18181b","--gh-secondary":"#3f3f46","--gh-danger":"#71717a","--gh-header-bg":"#000000","--gh-tag-active-bg":"#18181b","--gh-checkbox-bg":"#18181b","--gh-badge-text":"#18181b","--gh-badge-bg":"#f4f4f5","--gh-badge-border":"#e4e4e7","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(24, 24, 27, 0.08) 0%, rgba(63, 63, 70, 0.05) 100%)","--gh-folder-bg-default":"#f4f4f5","--gh-folder-bg-expanded":"#e4e4e7","--gh-folder-bg-0":"#f4f4f5","--gh-folder-bg-1":"#f4f4f5","--gh-folder-bg-2":"#f4f4f5","--gh-folder-bg-3":"#f4f4f5","--gh-folder-bg-4":"#f4f4f5","--gh-folder-bg-5":"#f4f4f5","--gh-folder-bg-6":"#f4f4f5","--gh-folder-bg-7":"#f4f4f5","--gh-outline-locate-bg":"rgba(24, 24, 27, 0.08)","--gh-outline-locate-border":"#dc2626","--gh-outline-locate-shadow":"rgba(220, 38, 38, 0.5)","--gh-outline-sync-bg":"rgba(220, 38, 38, 0.1)","--gh-outline-sync-border":"#ef4444","--gh-user-query-bg":"rgba(24, 24, 27, 0.04)","--gh-user-query-hover-bg":"rgba(24, 24, 27, 0.08)","--gh-bg-danger":"#f4f4f5","--gh-text-danger":"#18181b","--gh-bg-danger-hover":"#e4e4e7","--gh-brand-gradient":"linear-gradient(135deg, #000000 0%, #333333 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e4e4e7","--gh-overlay-bg":"rgba(255, 255, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.25)","--gh-search-highlight-bg":"rgba(0, 0, 0, 0.1)","--gh-emoji-selected-bg":"#e4e4e7","--gh-highlight-pulse":"rgba(24, 24, 27, 0.2)","--gh-slider-dot-bg":"#a1a1aa","--gh-code-bg":"rgba(24, 24, 27, 0.05)"}},{id:"porcelain",name:"青花瓷",description:"东方古典主题",variables:{"--gh-bg":"#f9fbff","--gh-bg-secondary":"#eff6ff","--gh-bg-tertiary":"#e0e7ff","--gh-text":"#1e4e79","--gh-text-secondary":"#4e7ca1","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"rgba(78, 124, 161, 0.2)","--gh-border-active":"#1e4e79","--gh-hover":"#eff6ff","--gh-active-bg":"#dbeafe","--gh-input-bg":"#ffffff","--gh-input-border":"#bfdbfe","--gh-input-focus-border":"#1e4e79","--gh-input-focus-shadow":"0 0 0 2px rgba(30, 78, 121, 0.1)","--gh-shadow":"0 10px 40px -10px rgba(30, 78, 121, 0.15), 0 4px 12px -4px rgba(30, 78, 121, 0.1)","--gh-shadow-sm":"0 2px 6px rgba(30, 78, 121, 0.08)","--gh-shadow-lg":"0 20px 60px rgba(30, 78, 121, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-primary":"#1e4e79","--gh-secondary":"#4e7ca1","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-tag-active-bg":"#1e4e79","--gh-checkbox-bg":"#1e4e79","--gh-badge-text":"#1e4e79","--gh-badge-bg":"#eff6ff","--gh-badge-border":"rgba(78, 124, 161, 0.3)","--gh-badge-shadow":"#f9fbff","--gh-selected-gradient":"linear-gradient(135deg, rgba(30, 78, 121, 0.1) 0%, rgba(78, 124, 161, 0.05) 100%)","--gh-folder-bg-default":"#eff6ff","--gh-folder-bg-expanded":"#dbeafe","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(30, 78, 121, 0.15)","--gh-outline-locate-border":"#b91c1c","--gh-outline-locate-shadow":"rgba(185, 28, 28, 0.5)","--gh-outline-sync-bg":"rgba(185, 28, 28, 0.1)","--gh-outline-sync-border":"#dc2626","--gh-user-query-bg":"rgba(30, 78, 121, 0.05)","--gh-user-query-hover-bg":"rgba(30, 78, 121, 0.1)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"rgba(78, 124, 161, 0.15)","--gh-overlay-bg":"rgba(249, 251, 255, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(30, 78, 121, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-search-highlight-bg":"rgba(78, 124, 161, 0.2)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(30, 78, 121, 0.2)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(30, 78, 121, 0.06)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.5' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.1'/%3E%3C/svg%3E\")"}},{id:"shortbread",name:"奶油脆饼",description:"莫兰迪治愈主题",variables:{"--gh-bg":"#f5f5f4","--gh-bg-secondary":"#e7e5e4","--gh-bg-tertiary":"#d6d3d1","--gh-text":"#44403c","--gh-text-secondary":"#78716c","--gh-text-tertiary":"#a8a29e","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d6d3d1","--gh-border-active":"#a8a29e","--gh-hover":"#e7e5e4","--gh-active-bg":"#d6d3d1","--gh-input-bg":"#ffffff","--gh-input-border":"#d6d3d1","--gh-input-focus-border":"#78716c","--gh-input-focus-shadow":"0 0 0 2px rgba(120, 113, 108, 0.2)","--gh-shadow":"0 10px 40px rgba(120, 113, 108, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(120, 113, 108, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(120, 113, 108, 0.15)","--gh-shadow-brand":"0 4px 12px rgba(120, 113, 108, 0.2)","--gh-primary":"#78716c","--gh-secondary":"#57534e","--gh-danger":"#ef4444","--gh-header-bg":"#78716c","--gh-tag-active-bg":"#78716c","--gh-checkbox-bg":"#78716c","--gh-badge-text":"#44403c","--gh-badge-bg":"#e7e5e4","--gh-badge-border":"#d6d3d1","--gh-badge-shadow":"#f5f5f4","--gh-selected-gradient":"linear-gradient(135deg, rgba(120, 113, 108, 0.15) 0%, rgba(87, 83, 78, 0.1) 100%)","--gh-folder-bg-default":"#e7e5e4","--gh-folder-bg-expanded":"#d6d3d1","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(120, 113, 108, 0.2)","--gh-outline-locate-border":"#2563eb","--gh-outline-locate-shadow":"rgba(37, 99, 235, 0.5)","--gh-outline-sync-bg":"rgba(37, 99, 235, 0.1)","--gh-outline-sync-border":"#3b82f6","--gh-user-query-bg":"rgba(120, 113, 108, 0.08)","--gh-user-query-hover-bg":"rgba(120, 113, 108, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #78716c 0%, #57534e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.5)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.7)","--gh-glass-text":"#44403c","--gh-card-bg":"#ffffff","--gh-card-border":"#d6d3d1","--gh-overlay-bg":"rgba(245, 245, 244, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(120, 113, 108, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(120, 113, 108, 0.3)","--gh-search-highlight-bg":"rgba(120, 113, 108, 0.3)","--gh-emoji-selected-bg":"#d6d3d1","--gh-highlight-pulse":"rgba(120, 113, 108, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(120, 113, 108, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"unicorn-dream",name:"独角兽",description:"梦幻童话主题",variables:{"--gh-bg":"#faf5ff","--gh-bg-secondary":"#f3e8ff","--gh-bg-tertiary":"#e9d5ff","--gh-text":"#5b21b6","--gh-text-secondary":"#7c3aed","--gh-text-tertiary":"#8b5cf6","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#d8b4fe","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#e9d5ff","--gh-input-focus-border":"#22d3ee","--gh-input-focus-shadow":"0 0 0 2px rgba(34, 211, 238, 0.3)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(139, 92, 246, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(139, 92, 246, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(244, 114, 182, 0.3)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #f472b6 0%, #22d3ee 50%, #a78bfa 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#7c3aed","--gh-badge-bg":"#f3e8ff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#faf5ff","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(167, 139, 250, 0.2)","--gh-outline-locate-border":"#a78bfa","--gh-outline-locate-shadow":"rgba(167, 139, 250, 0.5)","--gh-outline-sync-bg":"rgba(167, 139, 250, 0.15)","--gh-outline-sync-border":"#a78bfa","--gh-user-query-bg":"rgba(167, 139, 250, 0.1)","--gh-user-query-hover-bg":"rgba(167, 139, 250, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #f472b6 0%, #22d3ee 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#5b21b6","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(250, 245, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(167, 139, 250, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(167, 139, 250, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e9d5ff","--gh-highlight-pulse":"rgba(244, 114, 182, 0.3)","--gh-slider-dot-bg":"#e2e8f0","--gh-code-bg":"rgba(167, 139, 250, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.01' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.4'/%3E%3C/svg%3E\")","--gh-bg-animation":"gh-mist-drift 20s linear infinite alternate"}}],jm=[{id:"classic-dark",name:"经典深黑",description:"默认深色主题",variables:{"--gh-bg":"#1e1e1e","--gh-bg-secondary":"#0b0b0b","--gh-bg-tertiary":"#262626","--gh-text":"#e3e3e3","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#6b7280","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#333333","--gh-border-active":"#818cf8","--gh-hover":"#262626","--gh-active-bg":"#333333","--gh-input-bg":"#262626","--gh-input-border":"#404040","--gh-input-focus-border":"#818cf8","--gh-input-focus-shadow":"0 0 0 2px rgba(129, 140, 248, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(129, 140, 248, 0.3)","--gh-primary":"#818cf8","--gh-secondary":"#6366f1","--gh-danger":"#fca5a5","--gh-header-bg":"#1e1e1e","--gh-tag-active-bg":"rgba(129, 140, 248, 0.6)","--gh-checkbox-bg":"#818cf8","--gh-badge-text":"#e5e7eb","--gh-badge-bg":"#374151","--gh-badge-border":"#4b5563","--gh-badge-shadow":"#1f2937","--gh-selected-gradient":"linear-gradient(135deg, rgba(129, 140, 248, 0.25) 0%, rgba(99, 102, 241, 0.15) 100%)","--gh-folder-bg-default":"rgba(66, 133, 244, 0.15)","--gh-folder-bg-expanded":"rgba(66, 133, 244, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(66, 133, 244, 0.15)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1a73e8 0%, #1e8e3e 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e3e3e3","--gh-card-bg":"#0b0b0b","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(129, 140, 248, 0.3)","--gh-highlight-pulse":"rgba(129, 140, 248, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(255, 255, 255, 0.08)"}},{id:"midnight-blue",name:"午夜蓝",description:"深邃蓝色主题",variables:{"--gh-bg":"#0f172a","--gh-bg-secondary":"#020617","--gh-bg-tertiary":"#1e293b","--gh-text":"#e2e8f0","--gh-text-secondary":"#94a3b8","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#334155","--gh-border-active":"#60a5fa","--gh-hover":"#1e293b","--gh-active-bg":"#334155","--gh-input-bg":"#1e293b","--gh-input-border":"#475569","--gh-input-focus-border":"#60a5fa","--gh-input-focus-shadow":"0 0 0 2px rgba(96, 165, 250, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(96, 165, 250, 0.3)","--gh-primary":"#60a5fa","--gh-secondary":"#3b82f6","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-tag-active-bg":"rgba(96, 165, 250, 0.6)","--gh-checkbox-bg":"#60a5fa","--gh-badge-text":"#e2e8f0","--gh-badge-bg":"#334155","--gh-badge-border":"#475569","--gh-badge-shadow":"#1e293b","--gh-selected-gradient":"linear-gradient(135deg, rgba(96, 165, 250, 0.25) 0%, rgba(59, 130, 246, 0.15) 100%)","--gh-folder-bg-default":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-expanded":"rgba(59, 130, 246, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(96, 165, 250, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(96, 165, 250, 0.15)","--gh-user-query-hover-bg":"rgba(96, 165, 250, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e2e8f0","--gh-card-bg":"#020617","--gh-card-border":"#334155","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(96, 165, 250, 0.3)","--gh-highlight-pulse":"rgba(96, 165, 250, 0.4)","--gh-slider-dot-bg":"#475569","--gh-code-bg":"rgba(96, 165, 250, 0.12)"}},{id:"forest",name:"暗夜森林",description:"深绿色主题",variables:{"--gh-bg":"#0f1a14","--gh-bg-secondary":"#050a07","--gh-bg-tertiary":"#14261c","--gh-text":"#d1fae5","--gh-text-secondary":"#86efac","--gh-text-tertiary":"#6ee7b7","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1f3d2b","--gh-border-active":"#34d399","--gh-hover":"#14261c","--gh-active-bg":"#1f3d2b","--gh-input-bg":"#14261c","--gh-input-border":"#2a5a3d","--gh-input-focus-border":"#34d399","--gh-input-focus-shadow":"0 0 0 2px rgba(52, 211, 153, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(52, 211, 153, 0.3)","--gh-primary":"#34d399","--gh-secondary":"#10b981","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-tag-active-bg":"rgba(52, 211, 153, 0.6)","--gh-checkbox-bg":"#34d399","--gh-badge-text":"#d1fae5","--gh-badge-bg":"#1f3d2b","--gh-badge-border":"#2a5a3d","--gh-badge-shadow":"#14261c","--gh-selected-gradient":"linear-gradient(135deg, rgba(52, 211, 153, 0.25) 0%, rgba(16, 185, 129, 0.15) 100%)","--gh-folder-bg-default":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-expanded":"rgba(16, 185, 129, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#e879f9","--gh-outline-locate-shadow":"rgba(232, 121, 249, 0.6)","--gh-outline-sync-bg":"rgba(232, 121, 249, 0.15)","--gh-outline-sync-border":"#d946ef","--gh-user-query-bg":"rgba(52, 211, 153, 0.15)","--gh-user-query-hover-bg":"rgba(52, 211, 153, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#d1fae5","--gh-card-bg":"#050a07","--gh-card-border":"#1f3d2b","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(52, 211, 153, 0.3)","--gh-highlight-pulse":"rgba(52, 211, 153, 0.4)","--gh-slider-dot-bg":"#2a5a3d","--gh-code-bg":"rgba(52, 211, 153, 0.12)"}},{id:"cyberpunk",name:"赛博霓虹",description:"高对比科技主题",variables:{"--gh-bg":"#050505","--gh-bg-secondary":"#121212","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#e0e0e0","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#707070","--gh-text-on-primary":"#ffffff","--gh-footer-text":"#f472b6","--gh-border":"#333333","--gh-border-active":"#f472b6","--gh-hover":"#1a1a1a","--gh-active-bg":"#262626","--gh-input-bg":"#121212","--gh-input-border":"#404040","--gh-input-focus-border":"#f472b6","--gh-input-focus-shadow":"0 0 0 2px rgba(244, 114, 182, 0.3)","--gh-shadow":"0 0 20px rgba(244, 114, 182, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.8)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 0 15px rgba(244, 114, 182, 0.4)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ff0055","--gh-header-bg":"linear-gradient(45deg, #000000 0%, #1a1a1a 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#f472b6","--gh-badge-bg":"#1a1a1a","--gh-badge-border":"#333333","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-expanded":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.2)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.2)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.2)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.2)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.2)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.2)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.2)","--gh-outline-locate-border":"#facc15","--gh-outline-locate-shadow":"0 0 10px rgba(250, 204, 21, 0.6)","--gh-outline-sync-bg":"rgba(250, 204, 21, 0.15)","--gh-outline-sync-border":"#eab308","--gh-user-query-bg":"rgba(34, 211, 238, 0.1)","--gh-user-query-hover-bg":"rgba(34, 211, 238, 0.2)","--gh-bg-danger":"rgba(255, 0, 85, 0.15)","--gh-text-danger":"#ff0055","--gh-bg-danger-hover":"rgba(255, 0, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #be185d 0%, #0891b2 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.1)","--gh-glass-text":"#f472b6","--gh-card-bg":"#0a0a0a","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.85)","--gh-btn-shadow":"0 0 10px rgba(244, 114, 182, 0.3)","--gh-btn-shadow-hover":"0 0 15px rgba(244, 114, 182, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"rgba(244, 114, 182, 0.3)","--gh-highlight-pulse":"rgba(34, 211, 238, 0.4)","--gh-slider-dot-bg":"#555555","--gh-code-bg":"rgba(244, 114, 182, 0.1)"}},{id:"coffee",name:"醇香咖啡",description:"暖调护眼主题",variables:{"--gh-bg":"#1c1917","--gh-bg-secondary":"#292524","--gh-bg-tertiary":"#44403c","--gh-text":"#e7e5e4","--gh-text-secondary":"#a8a29e","--gh-text-tertiary":"#78716c","--gh-text-on-primary":"#e7e5e4","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44403c","--gh-border-active":"#d4a373","--gh-hover":"#292524","--gh-active-bg":"#44403c","--gh-input-bg":"#292524","--gh-input-border":"#57534e","--gh-input-focus-border":"#d4a373","--gh-input-focus-shadow":"0 0 0 2px rgba(212, 163, 115, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(212, 163, 115, 0.2)","--gh-primary":"#d4a373","--gh-secondary":"#a96e45","--gh-danger":"#ef4444","--gh-header-bg":"#292524","--gh-tag-active-bg":"#d4a373","--gh-checkbox-bg":"#d4a373","--gh-badge-text":"#e7e5e4","--gh-badge-bg":"#44403c","--gh-badge-border":"#57534e","--gh-badge-shadow":"#1c1917","--gh-selected-gradient":"linear-gradient(135deg, rgba(212, 163, 115, 0.2) 0%, rgba(169, 110, 69, 0.15) 100%)","--gh-folder-bg-default":"rgba(212, 163, 115, 0.15)","--gh-folder-bg-expanded":"rgba(169, 110, 69, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(212, 163, 115, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(212, 163, 115, 0.1)","--gh-user-query-hover-bg":"rgba(212, 163, 115, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #d4a373 0%, #a96e45 100%)","--gh-brand-border":"#44403c","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e7e5e4","--gh-card-bg":"#292524","--gh-card-border":"#44403c","--gh-overlay-bg":"rgba(28, 25, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(212, 163, 115, 0.25)","--gh-highlight-pulse":"rgba(212, 163, 115, 0.3)","--gh-slider-dot-bg":"#78716c","--gh-code-bg":"rgba(212, 163, 115, 0.12)"}},{id:"sunset",name:"幻梦落日",description:"紫橙渐变艺术主题",variables:{"--gh-bg":"#120a21","--gh-bg-secondary":"#1d1136","--gh-bg-tertiary":"#2a1b4b","--gh-text":"#f3e8ff","--gh-text-secondary":"#d8b4fe","--gh-text-tertiary":"#a78bfa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#4c1d95","--gh-border-active":"#f97316","--gh-hover":"#2a1b4b","--gh-active-bg":"#392463","--gh-input-bg":"#1d1136","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#f97316","--gh-input-focus-shadow":"0 0 0 2px rgba(249, 115, 22, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(249, 115, 22, 0.3)","--gh-primary":"#f97316","--gh-secondary":"#8b5cf6","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #be185d 100%)","--gh-tag-active-bg":"#f97316","--gh-checkbox-bg":"#f97316","--gh-badge-text":"#f3e8ff","--gh-badge-bg":"#2a1b4b","--gh-badge-border":"#4c1d95","--gh-badge-shadow":"#120a21","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.25) 0%, rgba(249, 115, 22, 0.2) 100%)","--gh-folder-bg-default":"rgba(139, 92, 246, 0.2)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(249, 115, 22, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(139, 92, 246, 0.1)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#f3e8ff","--gh-card-bg":"#1d1136","--gh-card-border":"#4c1d95","--gh-overlay-bg":"rgba(18, 10, 33, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(139, 92, 246, 0.3)","--gh-highlight-pulse":"rgba(249, 115, 22, 0.4)","--gh-slider-dot-bg":"#a78bfa","--gh-code-bg":"rgba(139, 92, 246, 0.12)"}},{id:"dracula",name:"德古拉",description:"经典极客主题",variables:{"--gh-bg":"#282a36","--gh-bg-secondary":"#21222c","--gh-bg-tertiary":"#44475a","--gh-text":"#f8f8f2","--gh-text-secondary":"#bd93f9","--gh-text-tertiary":"#6272a4","--gh-text-on-primary":"#f8f8f2","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44475a","--gh-border-active":"#ff79c6","--gh-hover":"#44475a","--gh-active-bg":"#21222c","--gh-input-bg":"#21222c","--gh-input-border":"#6272a4","--gh-input-focus-border":"#ff79c6","--gh-input-focus-shadow":"0 0 0 2px rgba(255, 121, 198, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(255, 121, 198, 0.3)","--gh-primary":"#ff79c6","--gh-secondary":"#bd93f9","--gh-danger":"#ff5555","--gh-header-bg":"#21222c","--gh-tag-active-bg":"#ff79c6","--gh-checkbox-bg":"#ff79c6","--gh-badge-text":"#f8f8f2","--gh-badge-bg":"#44475a","--gh-badge-border":"#6272a4","--gh-badge-shadow":"#282a36","--gh-selected-gradient":"linear-gradient(135deg, rgba(189, 147, 249, 0.25) 0%, rgba(255, 121, 198, 0.15) 100%)","--gh-folder-bg-default":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-expanded":"rgba(255, 121, 198, 0.25)","--gh-folder-bg-0":"rgba(241, 250, 140, 0.15)","--gh-folder-bg-1":"rgba(255, 121, 198, 0.15)","--gh-folder-bg-2":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-3":"rgba(80, 250, 123, 0.15)","--gh-folder-bg-4":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-5":"rgba(255, 184, 108, 0.15)","--gh-folder-bg-6":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-7":"rgba(255, 121, 198, 0.15)","--gh-outline-locate-bg":"rgba(255, 121, 198, 0.25)","--gh-outline-locate-border":"#4ade80","--gh-outline-locate-shadow":"rgba(74, 222, 128, 0.6)","--gh-outline-sync-bg":"rgba(74, 222, 128, 0.15)","--gh-outline-sync-border":"#22c55e","--gh-user-query-bg":"rgba(189, 147, 249, 0.1)","--gh-user-query-hover-bg":"rgba(189, 147, 249, 0.2)","--gh-bg-danger":"rgba(255, 85, 85, 0.15)","--gh-text-danger":"#ff5555","--gh-bg-danger-hover":"rgba(255, 85, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #bd93f9 0%, #ff79c6 100%)","--gh-brand-border":"#44475a","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#f8f8f2","--gh-card-bg":"#21222c","--gh-card-border":"#44475a","--gh-overlay-bg":"rgba(40, 42, 54, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(241, 250, 140, 0.5)","--gh-emoji-selected-bg":"rgba(189, 147, 249, 0.3)","--gh-highlight-pulse":"rgba(255, 121, 198, 0.4)","--gh-slider-dot-bg":"#6272a4","--gh-code-bg":"rgba(189, 147, 249, 0.12)"}},{id:"deep-abyss",name:"深海幽蓝",description:"静谧蓝绿主题",variables:{"--gh-bg":"#042f2e","--gh-bg-secondary":"#134e4a","--gh-bg-tertiary":"#115e59","--gh-text":"#ccfbf1","--gh-text-secondary":"#5eead4","--gh-text-tertiary":"#2dd4bf","--gh-text-on-primary":"#042f2e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#115e59","--gh-border-active":"#2dd4bf","--gh-hover":"#134e4a","--gh-active-bg":"#115e59","--gh-input-bg":"#134e4a","--gh-input-border":"#115e59","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#0ea5e9","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f766e 0%, #0369a1 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#ccfbf1","--gh-badge-bg":"#115e59","--gh-badge-border":"#2d7a74","--gh-badge-shadow":"#042f2e","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.25) 0%, rgba(14, 165, 233, 0.15) 100%)","--gh-folder-bg-default":"rgba(45, 212, 191, 0.15)","--gh-folder-bg-expanded":"rgba(14, 165, 233, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#fb923c","--gh-outline-locate-shadow":"rgba(251, 146, 60, 0.6)","--gh-outline-sync-bg":"rgba(251, 146, 60, 0.15)","--gh-outline-sync-border":"#f97316","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #0ea5e9 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#ccfbf1","--gh-card-bg":"#134e4a","--gh-card-border":"#115e59","--gh-overlay-bg":"rgba(4, 47, 46, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(45, 212, 191, 0.25)","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#334155","--gh-code-bg":"rgba(45, 212, 191, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='turbulence' baseFrequency='0.02' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"crimson-moon",name:"猩红赤月",description:"暗红狂野主题",variables:{"--gh-bg":"#0f0f0f","--gh-bg-secondary":"#1c1c1c","--gh-bg-tertiary":"#2a2a2a","--gh-text":"#fecaca","--gh-text-secondary":"#f87171","--gh-text-tertiary":"#ef4444","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#450a0a","--gh-border-active":"#ef4444","--gh-hover":"#2a2a2a","--gh-active-bg":"#450a0a","--gh-input-bg":"#1c1c1c","--gh-input-border":"#450a0a","--gh-input-focus-border":"#ef4444","--gh-input-focus-shadow":"0 0 0 2px rgba(239, 68, 68, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.8)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.6)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 4px 12px rgba(239, 68, 68, 0.3)","--gh-primary":"#ef4444","--gh-secondary":"#991b1b","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #7f1d1d 0%, #991b1b 100%)","--gh-tag-active-bg":"#ef4444","--gh-checkbox-bg":"#ef4444","--gh-badge-text":"#fee2e2","--gh-badge-bg":"#450a0a","--gh-badge-border":"#7f1d1d","--gh-badge-shadow":"#0f0f0f","--gh-selected-gradient":"linear-gradient(135deg, rgba(239, 68, 68, 0.25) 0%, rgba(153, 27, 27, 0.15) 100%)","--gh-folder-bg-default":"rgba(239, 68, 68, 0.15)","--gh-folder-bg-expanded":"rgba(153, 27, 27, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(251, 113, 133, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(239, 68, 68, 0.25)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(239, 68, 68, 0.1)","--gh-user-query-hover-bg":"rgba(239, 68, 68, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#fecaca","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #ef4444 0%, #991b1b 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#fecaca","--gh-card-bg":"#1c1c1c","--gh-card-border":"#450a0a","--gh-overlay-bg":"rgba(15, 15, 15, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(239, 68, 68, 0.25)","--gh-highlight-pulse":"rgba(239, 68, 68, 0.3)","--gh-slider-dot-bg":"#f87171","--gh-code-bg":"rgba(239, 68, 68, 0.12)"}},{id:"retro-terminal",name:"黑客终端",description:"复古 CRT 主题",variables:{"--gh-bg":"#0c0c0c","--gh-bg-secondary":"#000000","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#22c55e","--gh-text-secondary":"#15803d","--gh-text-tertiary":"#14532d","--gh-text-on-primary":"#22c55e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#14532d","--gh-border-active":"#22c55e","--gh-hover":"#1a1a1a","--gh-active-bg":"#14532d","--gh-input-bg":"#000000","--gh-input-border":"#15803d","--gh-input-focus-border":"#4ade80","--gh-input-focus-shadow":"0 0 0 2px rgba(74, 222, 128, 0.3)","--gh-shadow":"0 0 20px rgba(34, 197, 94, 0.1)","--gh-shadow-sm":"0 0 10px rgba(34, 197, 94, 0.1)","--gh-shadow-lg":"0 0 40px rgba(34, 197, 94, 0.2)","--gh-shadow-brand":"0 0 15px rgba(34, 197, 94, 0.3)","--gh-primary":"#15803d","--gh-secondary":"#4ade80","--gh-danger":"#ef4444","--gh-header-bg":"#000000","--gh-tag-active-bg":"#22c55e","--gh-checkbox-bg":"#22c55e","--gh-badge-text":"#22c55e","--gh-badge-bg":"#000000","--gh-badge-border":"#15803d","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(90deg, rgba(34, 197, 94, 0.25) 0%, rgba(34, 197, 94, 0.05) 100%)","--gh-folder-bg-default":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-expanded":"rgba(34, 197, 94, 0.2)","--gh-folder-bg-0":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-1":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-2":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-3":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-4":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-5":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-6":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-7":"rgba(34, 197, 94, 0.1)","--gh-outline-locate-bg":"rgba(34, 197, 94, 0.5)","--gh-outline-locate-border":"#f59e0b","--gh-outline-locate-shadow":"0 0 15px rgba(245, 158, 11, 0.6)","--gh-outline-sync-bg":"rgba(245, 158, 11, 0.1)","--gh-outline-sync-border":"#d97706","--gh-user-query-bg":"rgba(34, 197, 94, 0.05)","--gh-user-query-hover-bg":"rgba(34, 197, 94, 0.1)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #022c22 0%, #15803d 100%)","--gh-brand-border":"#15803d","--gh-glass-bg":"rgba(0, 0, 0, 0.8)","--gh-glass-bg-hover":"rgba(0, 0, 0, 0.9)","--gh-glass-text":"#22c55e","--gh-card-bg":"#000000","--gh-card-border":"#15803d","--gh-overlay-bg":"rgba(0, 0, 0, 0.9)","--gh-btn-shadow":"0 0 8px rgba(34, 197, 94, 0.4)","--gh-btn-shadow-hover":"0 0 12px rgba(34, 197, 94, 0.6)","--gh-search-highlight-bg":"rgba(34, 197, 94, 0.4)","--gh-emoji-selected-bg":"rgba(34, 197, 94, 0.2)","--gh-highlight-pulse":"rgba(34, 197, 94, 0.5)","--gh-slider-dot-bg":"#14532d","--gh-code-bg":"rgba(34, 197, 94, 0.15)","--gh-bg-image":"repeating-linear-gradient(to bottom, transparent 0px, transparent 2px, rgba(34, 197, 94, 0.05) 2px, rgba(34, 197, 94, 0.05) 4px)","--gh-bg-animation":"gh-scanline 8s linear infinite"}},{id:"eva-unit-01",name:"代号:暴走",description:"机甲撞色主题",variables:{"--gh-bg":"#2e1065","--gh-bg-secondary":"#1e0b4b","--gh-bg-tertiary":"#4c1d95","--gh-text":"#d9f99d","--gh-text-secondary":"#bef264","--gh-text-tertiary":"#a3e635","--gh-text-on-primary":"#1e0b4b","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d9f99d","--gh-border-active":"#a3e635","--gh-hover":"#4c1d95","--gh-active-bg":"#5b21b6","--gh-input-bg":"#1e0b4b","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#a3e635","--gh-input-focus-shadow":"0 0 0 2px rgba(163, 230, 53, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(163, 230, 53, 0.3)","--gh-primary":"#a3e635","--gh-secondary":"#f97316","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #a3e635 100%)","--gh-tag-active-bg":"#a3e635","--gh-checkbox-bg":"#a3e635","--gh-badge-text":"#1e0b4b","--gh-badge-bg":"#d9f99d","--gh-badge-border":"#a3e635","--gh-badge-shadow":"#2e1065","--gh-selected-gradient":"linear-gradient(135deg, rgba(163, 230, 53, 0.25) 0%, rgba(249, 115, 22, 0.15) 100%)","--gh-folder-bg-default":"rgba(163, 230, 53, 0.15)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(163, 230, 53, 0.3)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.6)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.15)","--gh-outline-sync-border":"#ea580c","--gh-user-query-bg":"rgba(163, 230, 53, 0.1)","--gh-user-query-hover-bg":"rgba(163, 230, 53, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #a3e635 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#d9f99d","--gh-card-bg":"#1e0b4b","--gh-card-border":"#5b21b6","--gh-overlay-bg":"rgba(46, 16, 101, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(249, 115, 22, 0.5)","--gh-emoji-selected-bg":"rgba(163, 230, 53, 0.3)","--gh-highlight-pulse":"rgba(163, 230, 53, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(163, 230, 53, 0.12)"}},{id:"aurora",name:"极光行者",description:"自然奇观主题",variables:{"--gh-bg":"#020617","--gh-bg-secondary":"#0f172a","--gh-bg-tertiary":"#1e293b","--gh-text":"#e0f2fe","--gh-text-secondary":"#bae6fd","--gh-text-tertiary":"#7dd3fc","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1e293b","--gh-border-active":"#38bdf8","--gh-hover":"#0f172a","--gh-active-bg":"#1e293b","--gh-input-bg":"#0f172a","--gh-input-border":"#1e293b","--gh-input-focus-border":"#38bdf8","--gh-input-focus-shadow":"0 0 0 2px rgba(56, 189, 248, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.5)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(56, 189, 248, 0.3)","--gh-primary":"#38bdf8","--gh-secondary":"#34d399","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f172a 0%, #1e40af 100%)","--gh-tag-active-bg":"#38bdf8","--gh-checkbox-bg":"#38bdf8","--gh-badge-text":"#e0f2fe","--gh-badge-bg":"#1e293b","--gh-badge-border":"#38bdf8","--gh-badge-shadow":"#020617","--gh-selected-gradient":"linear-gradient(135deg, rgba(56, 189, 248, 0.25) 0%, rgba(52, 211, 153, 0.15) 100%)","--gh-folder-bg-default":"rgba(56, 189, 248, 0.15)","--gh-folder-bg-expanded":"rgba(52, 211, 153, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.25)","--gh-outline-locate-border":"#f472b6","--gh-outline-locate-shadow":"rgba(244, 114, 182, 0.5)","--gh-outline-sync-bg":"rgba(244, 114, 182, 0.15)","--gh-outline-sync-border":"#f472b6","--gh-user-query-bg":"rgba(56, 189, 248, 0.1)","--gh-user-query-hover-bg":"rgba(56, 189, 248, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #0369a1 0%, #0f766e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e0f2fe","--gh-card-bg":"#0f172a","--gh-card-border":"#1e293b","--gh-overlay-bg":"rgba(2, 6, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(56, 189, 248, 0.25)","--gh-highlight-pulse":"rgba(56, 189, 248, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(56, 189, 248, 0.12)"}}],Gm=(e,t)=>{const n=((e,t)=>("light"===t?Wm:jm).find(t=>t.id===e))(e,t);return n||("light"===t?Wm[0]:jm[0])},Vm="google-gradient",Qm="classic-dark",Km="ophel-native-adaptive-style";class Zm{mode;preference;lightPresetId;darkPresetId;hostThemeObserver=null;onModeChange;adapter;nativeThemeOverrideEnabled;customStyles=[];skipNextDetection=false;listeners=new Set;systemMediaQuery=null;handleSystemChange=e=>{if("system"!==this.preference)return;const t=e.matches?"dark":"light";this.mode!==t&&(this.mode=t,this.emitChange(),this.syncHostTheme(t,"system"),this.onModeChange&&this.onModeChange(t,this.preference));};constructor(e,t,n,r="google-gradient",o="classic-dark",i=true){const a="system"===e?"system":"dark"===e?"dark":"light";this.preference=a,this.mode=this.resolveMode(a),this.lightPresetId=r,this.darkPresetId=o,this.onModeChange=t,this.adapter=n,this.nativeThemeOverrideEnabled=i,this.injectGlobalStyles(),this.ensureSystemListener();}ensureSystemListener(){!this.systemMediaQuery&&"undefined"!=typeof window&&window.matchMedia&&(this.systemMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),"function"==typeof this.systemMediaQuery.addEventListener?this.systemMediaQuery.addEventListener("change",this.handleSystemChange):"function"==typeof this.systemMediaQuery.addListener&&this.systemMediaQuery.addListener(this.handleSystemChange));}getSystemMode(){return "undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}resolveMode(e){return "system"===e?this.getSystemMode():e}isHostThemeSyncActive(){return this.adapter?.supportsHostThemeSync()??true}isNativeThemeOverrideActive(){return this.nativeThemeOverrideEnabled&&this.isHostThemeSyncActive()}syncHostTheme(e,t=e){if(this.isHostThemeSyncActive()){if("system"===t){!this.applySystemPreferenceToHost(e)&&this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(e).catch(()=>{});}else this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{});this.applyTheme(e);}else this.applyTheme(e);}applySystemPreferenceToHost(e){if(!this.adapter)return false;const t=this.adapter.getSiteId();try{switch(t){case go:return localStorage.setItem("theme","system"),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case To:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case fo:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case Co:{const t=localStorage.getItem("theme");localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e,document.body&&(document.body.setAttribute("data-theme",e),document.body.style.colorScheme=e);const n=document.querySelector('meta[name="color-scheme"]');return n&&n.setAttribute("content",e),"system"!==t&&this.adapter?.toggleTheme?this.adapter.toggleTheme("system").catch(()=>{}):window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0}case bo:{const t=localStorage.getItem("aiStudioUserPreference")||"{}";let n={};try{n=JSON.parse(t);}catch{n={};}n.theme="system";const r=JSON.stringify(n);localStorage.setItem("aiStudioUserPreference",r);const o=document.body;"dark"===e?(o.classList.add("dark-theme"),o.classList.remove("light-theme")):(o.classList.remove("dark-theme"),o.classList.add("light-theme")),o.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:r,storageArea:localStorage}));const i=document.querySelector("app-root, ms-app, body");return i&&i.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}case xo:case po:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case ho:return localStorage.removeItem("Bard-Color-Theme"),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:null,storageArea:localStorage})),!0;case uo:case mo:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case yo:return !1;case ko:return localStorage.setItem("yb_web_theme_mode","system"),window.dispatchEvent(new StorageEvent("storage",{key:"yb_web_theme_mode",newValue:"system",storageArea:localStorage})),document.documentElement.style.colorScheme="",!0;default:return !1}}catch{return false}}injectGlobalStyles(){if(document.getElementById("gh-global-styles"))return;const e=document.createElement("style");e.id="gh-global-styles",e.textContent="\n ::view-transition-old(root),\n ::view-transition-new(root),\n ::view-transition-old(gh-page),\n ::view-transition-new(gh-page) {\n animation: none;\n mix-blend-mode: normal;\n }\n\n ::view-transition-new(gh-page),\n ::view-transition-new(root) {\n clip-path: circle(0px at var(--theme-x, 50%) var(--theme-y, 50%));\n }\n ",document.head.appendChild(e);}injectNativeThemeOverrideCss(){if(!this.adapter||!this.isNativeThemeOverrideActive())return;const e=this.adapter.getNativeThemeCss();if(!e||document.getElementById(Km))return;const t=document.createElement("style");t.id=Km,t.textContent=e,document.head.appendChild(t);}removeNativeThemeOverrideCss(){document.getElementById(Km)?.remove();}syncNativeThemeOverrideCssState(){this.isNativeThemeOverrideActive()?this.injectNativeThemeOverrideCss():this.removeNativeThemeOverrideCss();}setAdapter(e){this.adapter=e,this.syncNativeThemeOverrideCssState(),this.isHostThemeSyncActive()||(this.stopThemeMonitoring(),this.syncPluginUiTheme(this.mode));}setOnModeChange(e){this.onModeChange=e;}setNativeThemeOverrideEnabled(e){const t=false!==e;this.nativeThemeOverrideEnabled=t,this.syncNativeThemeOverrideCssState();}applyModePreference(e){const t="system"===e?"system":"dark"===e?"dark":"light";this.preference=t,this.mode=this.resolveMode(t),this.emitChange(),"system"!==this.preference?this.applyTheme(this.mode):this.syncHostTheme(this.mode,"system");}applyGenericHostThemeFallback(e){const t=this.adapter?.getSiteId()===ho;if("dark"===e)return document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme"),void(document.body.style.colorScheme="dark");document.body.classList.remove("dark-theme"),document.body.style.colorScheme="light",t?document.body.classList.add("light-theme"):document.body.classList.remove("light-theme");}detectHostThemeMode(){const e=document.documentElement.getAttribute("yb-theme-mode");if("dark"===e)return "dark";if("light"===e)return "light";if("system"===e)return this.getSystemMode();const t=document.documentElement.className;if(/\bdark\b/i.test(t))return "dark";if(/\blight\b/i.test(t))return "light";const n=document.body.className;if(/\bdark-theme\b/i.test(n))return "dark";if(/\blight-theme\b/i.test(n))return "light";const r=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===r?"dark":"light"===r?"light":"dark"===document.body.style.colorScheme?"dark":"light"}detectHostThemePreference(){if(!this.adapter)return null;const e=this.adapter.getSiteId();try{switch(e){case go:case fo:case To:case Co:{const e=localStorage.getItem("theme");return "light"===e||"dark"===e||"system"===e?e:null}case bo:{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.theme;return "light"===n||"dark"===n||"system"===n?n:null}case xo:{const e=localStorage.getItem("__appKit_@deepseek/chat_themePreference");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.value;return "light"===n||"dark"===n||"system"===n?n:null}case po:{const e=localStorage.getItem("SKIN_MODE");return "1"===e?"light":"2"===e?"dark":"3"===e?"system":null}case ho:{const e=localStorage.getItem("Bard-Color-Theme");return e?/dark/i.test(e)?"dark":/light/i.test(e)?"light":null:"system"}case uo:{const e=localStorage.getItem("LSS-userThemeMode");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.value;return "auto"===n||"system"===n?"system":"dark"===n||"light"===n?n:null}case mo:{const e=ds.query("md-primary-tab",{all:!0,shadow:!0});if(!e||0===e.length)return null;const t=[];for(const r of e){let e=r.querySelector("md-icon");e||(e=ds.query("md-icon",{parent:r,shadow:!0}));const n=e?.textContent?.trim();if("computer"!==n&&"light_mode"!==n&&"dark_mode"!==n)continue;const o=r,i=Boolean(o.selected||o.active||0===o.tabIndex);t.push({icon:n,selected:i});}const n=t.find(e=>e.selected);return n?"computer"===n.icon?"system":"dark_mode"===n.icon?"dark":"light":null}case yo:return "light";case ko:{const e=localStorage.getItem("yb_web_theme_mode");return "light"===e||"dark"===e||"system"===e?e:null}default:return null}}catch{return null}}applyTheme(e){const t=e||this.mode;!this.isHostThemeSyncActive()||this.adapter&&this.adapter.hasCustomToggleTheme()||this.applyGenericHostThemeFallback(t),this.syncPluginUiTheme(t);}getCurrentPreset(){const e="dark"===this.mode?this.darkPresetId:this.lightPresetId;return Gm(e,this.mode)}setPresets(e,t){this.lightPresetId=e,this.darkPresetId=t,this.syncPluginUiTheme();}setCustomStyles(e){this.customStyles=e||[];const t="dark"===this.mode?this.darkPresetId:this.lightPresetId;this.customStyles.some(e=>e.id===t)&&this.syncPluginUiTheme();}syncPluginUiTheme(e){const t=e||this.mode,n=document.documentElement,r="dark"===t?this.darkPresetId:this.lightPresetId,o=this.customStyles.find(e=>e.id===r);let i=null;if(o);else try{i=Gm(r,t).variables;}catch(c){return void console.error("[ThemeManager] getPreset FAILED:",c)}const a=null!==this.hostThemeObserver;if(a&&this.hostThemeObserver?.disconnect(),"dark"===t?document.body.dataset.ghMode="dark":delete document.body.dataset.ghMode,i)for(const[d,u]of Object.entries(i))n.style.setProperty(d,u);let s="";if(o)s=o.css;else if(i){const e=(l=i,Object.entries(l).map(([e,t])=>`${e}: ${t} !important;`).join("\n "));s=`:host {\n${e}\ncolor-scheme: ${t};\n}\n\n:host([data-theme="dark"]),\n:host .gh-root[data-theme="dark"] {\n${e}\n}\n`;}var l;if(document.querySelectorAll("plasmo-csui, #ophel-userscript-root").forEach(e=>{const n=e.shadowRoot;if(n){let r=n.querySelector("#gh-theme-vars");r||(r=document.createElement("style"),r.id="gh-theme-vars"),s&&(r.textContent=s),e.dataset.theme=t,n.append(r);}}),s)try{const e="undefined"!=typeof chrome&&chrome.runtime?.id?"ophel_ext_theme_cache":"ophel_us_theme_cache";localStorage.setItem(e,s);}catch{}a&&this.hostThemeObserver&&(this.hostThemeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.hostThemeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme","yb-theme-mode"]}));}startThemeMonitoring(){if(!this.isHostThemeSyncActive())return this.stopThemeMonitoring(),void this.syncPluginUiTheme(this.mode);const e=()=>{if(this.skipNextDetection)return void(this.skipNextDetection=false);const e=this.detectHostThemeMode(),t=this.detectHostThemePreference()??e,n="system"===t?this.getSystemMode():t;"system"===t?(this.ensureSystemListener(),e!==n?this.syncHostTheme(n,"system"):this.syncPluginUiTheme(n)):this.syncPluginUiTheme(n),this.mode===n&&this.preference===t||(this.mode=n,this.preference=t,this.emitChange(),this.onModeChange&&this.onModeChange(n,t));};e(),this.hostThemeObserver||(this.hostThemeObserver=new MutationObserver(()=>{e();}),this.hostThemeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.hostThemeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme","yb-theme-mode"]}));}stopThemeMonitoring(){this.hostThemeObserver&&(this.hostThemeObserver.disconnect(),this.hostThemeObserver=null);}getTransitionOrigin(e){let t=95,n=5;if(e&&void 0!==e.clientX)return t=e.clientX/window.innerWidth*100,n=e.clientY/window.innerHeight*100,{x:t,y:n};const r=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(r){const e=r.getBoundingClientRect();t=(e.left+e.width/2)/window.innerWidth*100,n=(e.top+e.height/2)/window.innerHeight*100;}return {x:t,y:n}}prepareTransitionSnapshotTarget(){if(this.adapter?.getSiteId()!==go||!document.body)return {pseudoElement:"::view-transition-new(root)",cleanup:()=>{}};const e=document.body.style.getPropertyValue("view-transition-name");return document.body.style.setProperty("view-transition-name","gh-page"),{pseudoElement:"::view-transition-new(gh-page)",cleanup:()=>{e?document.body.style.setProperty("view-transition-name",e):document.body.style.removeProperty("view-transition-name");}}}async applyWithTransition(e,t){const{x:n,y:r}=this.getTransitionOrigin(t);document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopThemeMonitoring();const o=window.matchMedia("(prefers-reduced-motion: reduce)").matches;if(!document.startViewTransition||o){try{e();}finally{this.startThemeMonitoring();}return false}const i=this.prepareTransitionSnapshotTarget();try{const t=document.startViewTransition(()=>{e();});t.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),a=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:a},{duration:500,easing:"ease-in",pseudoElement:i.pseudoElement,fill:"forwards"});}),await t.finished.catch(()=>{});}catch{return e(),i.cleanup(),this.startThemeMonitoring(),false}return i.cleanup(),this.skipNextDetection=true,this.startThemeMonitoring(),true}async toggle(e){const t="dark"===("system"!==this.preference&&this.isHostThemeSyncActive()?this.detectHostThemeMode():this.mode)?"light":"dark";this.preference=t;let n=95,r=5;if(e&&void 0!==e.clientX)n=e.clientX/window.innerWidth*100,r=e.clientY/window.innerHeight*100;else {const e=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(e){const t=e.getBoundingClientRect();n=(t.left+t.width/2)/window.innerWidth*100,r=(t.top+t.height/2)/window.innerHeight*100;}}document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopThemeMonitoring();const o=()=>{this.isHostThemeSyncActive()&&this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{}),this.applyTheme(t);};if(!document.startViewTransition||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return o(),this.mode=t,this.emitChange(),this.startThemeMonitoring(),t;const i=this.prepareTransitionSnapshotTarget();let a;try{a=document.startViewTransition(()=>{o();});}catch{return i.cleanup(),o(),this.mode=t,this.emitChange(),this.startThemeMonitoring(),t}return a.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),a=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:a},{duration:500,easing:"ease-in",pseudoElement:i.pseudoElement,fill:"forwards"});}),await a.finished.catch(()=>{}),i.cleanup(),this.skipNextDetection=true,this.isHostThemeSyncActive()?(this.onModeChange&&this.onModeChange(t,this.preference),this.startThemeMonitoring(),this.mode=t,this.emitChange(),t):(this.mode=t,this.emitChange(),this.onModeChange&&this.onModeChange(t,this.preference),this.startThemeMonitoring(),t)}async setMode(e,t){const n="system"===e?"system":"dark"===e?"dark":"light";if("system"===n){this.preference="system",this.ensureSystemListener();const e=this.getSystemMode(),n=this.mode!==e;let r=false;return Boolean(t)&&n?r=await this.applyWithTransition(()=>{this.syncHostTheme(e,"system");},t):this.syncHostTheme(e,"system"),n&&(this.mode=e,this.emitChange(),this.isHostThemeSyncActive()||this.syncPluginUiTheme(e)),this.onModeChange&&this.onModeChange(e,this.preference),{mode:e,animated:r}}if((this.isHostThemeSyncActive()?this.detectHostThemeMode():this.mode)===n)return this.preference=n,this.syncHostTheme(n,n),this.onModeChange&&this.onModeChange(n,this.preference),{mode:n,animated:false};return {mode:await this.toggle(t),animated:true}}getMode(){return this.mode}getPreference(){return this.preference}getSnapshot=()=>this.mode;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e);});emitChange(){for(const e of this.listeners)e();}destroy(){this.stopThemeMonitoring(),this.listeners.clear();}}function Ym(e){const{mode:t,onModeChange:n,adapter:r,lightPresetId:o=Vm,darkPresetId:i=Qm,syncNativePageTheme:a=true,apply:s=false}=e,l=window.__ophelThemeManager||new Zm(t,n,r,o,i,a);window.__ophelThemeManager||(window.__ophelThemeManager=l),l.setAdapter(r??null),l.setNativeThemeOverrideEnabled(a),l.setPresets(o,i),void 0!==n&&l.setOnModeChange(n);const c="system"===t?"system":"dark"===t?"dark":"light";return l.getPreference()!==c?l.applyModePreference(c):s&&l.applyTheme(),l}const Xm=new Set(["outline-search-input","conversations-search-input","prompt-search-input"]),Jm=e=>{const t=e.composedPath().find(e=>e instanceof HTMLElement);return t||(e.target instanceof HTMLElement?e.target:null)};function ef({edgeSnapState:e,panelMode:t,isPanelExpanded:n,findUiElement:r,getQueryRoots:o,isSettingsOpenRef:i}){const[a,s]=_(false),l=$(null),c=$(null),d=$(false),u=$(false),h=$(false),g=$(false),p=$(e),m=$(t);L(()=>{p.current=e,m.current=t;},[e,t]);const f=E(()=>{l.current&&(clearTimeout(l.current),l.current=null);},[]),b=E(()=>{c.current&&(clearTimeout(c.current),c.current=null);},[]),y=E(()=>{s(true);},[]),v=E(()=>{s(false);},[]),x=E(()=>os(o()),[o]),w=E(()=>{if(!p.current||"edge-snap"!==m.current)return;if(i.current||d.current||u.current)return;if(x())return;const e=r(".gh-main-panel");e&&s(e.matches(":hover"));},[r,x,i]),S=E((e=0)=>{f(),l.current=setTimeout(()=>{l.current=null,w();},e);},[f,w]),C=E(()=>{y(),b(),c.current=setTimeout(()=>{w(),c.current=null;},3e3);},[b,y,w]),k=E((e=true)=>{h.current=e;},[]),T=E(()=>{g.current=true;},[]),A=E(e=>{d.current=e;},[]),M=E(()=>{f(),b(),e&&"edge-snap"===t&&!a&&y();},[b,f,e,a,t,y]),I=E(()=>{f(),l.current=setTimeout(()=>{i.current||u.current||w();},200);},[f,i,w]);return L(()=>()=>{f(),b();},[b,f]),L(()=>{if(!e||"edge-snap"!==t)return;const n=()=>x();let r=n();const i=new MutationObserver(()=>{const e=n();e&&!r?(y(),f()):!e&&r&&S(500),r=e;});for(const e of o())i.observe(e,{childList:true,subtree:e!==document.body});return h.current?h.current=false:n()&&y(),()=>{i.disconnect(),h.current=false;}},[f,e,o,x,t,S,y]),L(()=>{if(!e||"edge-snap"!==t)return;const n=o().filter(e=>e instanceof ShadowRoot);if(0===n.length)return;const r=e=>{const t=Jm(e);t&&is(t)&&(t.closest(".settings-modal-overlay, .settings-modal")||(u.current=true,y(),f()));},a=e=>{const t=Jm(e);t&&is(t)&&(t.closest(".settings-modal-overlay, .settings-modal")||(u.current=false,f(),l.current=setTimeout(()=>{u.current||i.current||d.current||w();},300)));},s=e=>{if("Escape"!==e.key)return;const t=(e=>e.composedPath().find(e=>e instanceof HTMLInputElement&&Array.from(Xm).some(t=>e.classList.contains(t)))??null)(e);t&&(e.preventDefault(),e.stopImmediatePropagation(),u.current=false,t.blur(),window.setTimeout(w,0));};return n.forEach(e=>{e.addEventListener("focusin",r,true),e.addEventListener("focusout",a,true),e.addEventListener("keydown",s,true);}),()=>{n.forEach(e=>{e.removeEventListener("focusin",r,true),e.removeEventListener("focusout",a,true),e.removeEventListener("keydown",s,true);});}},[f,e,o,i,t,y,w]),L(()=>{g.current&&n&&e&&"edge-snap"===t&&(g.current=false,S(1500));},[e,n,t,S]),{isEdgePeeking:a,showEdgePeek:y,hideEdgePeek:v,syncEdgePeekVisibility:w,scheduleEdgePeekSync:S,showEdgePeekFromShortcut:C,markSuppressOverlayInit:k,markSyncAfterOpen:T,handlePanelMouseEnter:M,handlePanelMouseLeave:I,handleInteractionChange:A}}class tf{handlers=new Map;settings=null;isMac=ur();isListening=false;processedEvents=new WeakSet;updateSettings(e){this.settings=cr(e)||null;}register(e,t){this.handlers.set(e,t);}registerAll(e){for(const[t,n]of Object.entries(e))n&&this.handlers.set(t,n);}unregister(e){this.handlers.delete(e);}clearAll(){this.handlers.clear();}startListening(){this.isListening||(window.addEventListener("keydown",this.handleKeyDown,true),document.addEventListener("keydown",this.handleKeyDown,true),this.isListening=true);}stopListening(){this.isListening&&(window.removeEventListener("keydown",this.handleKeyDown,true),document.removeEventListener("keydown",this.handleKeyDown,true),this.isListening=false);}shouldIgnoreEvent(e){const t=e.target;if(!(t&&t instanceof Element))return false;return !("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName&&!t.isContentEditable&&"true"!==t.getAttribute("contenteditable")&&!t.classList.contains("ProseMirror")||e.ctrlKey||e.metaKey||e.altKey)}matchesBinding(e,t){const n=lr(t);if(!n)return false;const r=sr(e.key,e.code).toLowerCase(),o=n.key.toLowerCase();let i=r===o||"arrowup"===o&&"arrowup"===r||"arrowdown"===o&&"arrowdown"===r||"arrowleft"===o&&"arrowleft"===r||"arrowright"===o&&"arrowright"===r;if(!i&&n.shift&&/^[0-9]$/.test(o)&&e.code===`Digit${o}`&&(i=true),!i)return false;const a=!!n.alt===e.altKey,s=!!n.shift===e.shiftKey;let l;if(this.isMac){l=!!n.ctrl===e.metaKey&&!e.ctrlKey;}else l=!!n.ctrl===e.ctrlKey;return a&&s&&l}handleKeyDown=e=>{if(this.processedEvents.has(e))return;if(this.processedEvents.add(e),false===e.isTrusted)return;if(!this.settings?.enabled)return;if(!this.isMac&&e.getModifierState("AltGraph"))return;if(this.shouldIgnoreEvent(e))return;const t={...rr,...this.settings.keybindings};for(const[n,r]of Object.entries(t))if(null!==r&&this.matchesBinding(e,r)){const t=this.handlers.get(n);if(t)return e.preventDefault(),e.stopPropagation(),void t()}};trigger(e){const t=this.handlers.get(e);t&&t();}destroy(){this.stopListening(),this.clearAll();}}let nf=null;let rf=null;const of=new Set,af=()=>rf,sf=e=>{rf=e,of.forEach(e=>e());},lf=e=>(of.add(e),()=>of.delete(e)),cf=()=>rf;function df(e,t){return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(t).flexDirection}function uf(e,t){return t?Math.min(0,e.clientHeight-e.scrollHeight):0}function hf(e,t){return t?0:e.scrollHeight}function gf(){const e=(window.unsafeWindow?window.unsafeWindow:window).document.querySelectorAll("iframe");for(const t of e)try{const e=t.contentDocument||t.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]');if(t&&t.scrollHeight>t.clientHeight)return t}}catch{}return null}function pf(e,t){{const n=gf();if(!n)return Promise.resolve({success:false,reason:"no_flutter_container"});let r;switch(e){case "scrollToTop":n.scrollTop=0,r={success:true,scrollTop:n.scrollTop};break;case "scrollToBottom":n.scrollTop=n.scrollHeight,r={success:true,scrollTop:n.scrollTop};break;case "scrollTo":"number"==typeof t&&(n.scrollTop=t),r={success:true,scrollTop:n.scrollTop};break;case "getScrollInfo":r={success:true,scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};break;default:r={success:false};}return Promise.resolve(r)}}async function mf(e){const t=await pf("getScrollInfo");if(t.success){const e=t.scrollTop||0,n=t.scrollHeight||0;return await pf("scrollToTop"),{container:xf(),previousScrollTop:e,scrollHeight:n}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=n.scrollHeight,o=df(e,n);return n.scrollTo({top:uf(n,o),behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t,scrollHeight:r}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop,scrollHeight:r.scrollHeight}}async function ff(e){const t=await pf("getScrollInfo");if(t.success){const e=t.scrollTop||0;return await pf("scrollToBottom"),{container:xf(),previousScrollTop:e}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=df(e,n);return n.scrollTo({top:hf(n,r),behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop}}async function bf(e,t){const n=await pf("scrollTo",t);if(n.success)return yf(n.scrollTop||0),{success:true,currentScrollTop:n.scrollTop||0};const r=e?.getScrollContainer();return r&&r.scrollHeight>r.clientHeight?(r.scrollTo({top:t,behavior:"instant",__bypassLock:true}),yf(r.scrollTop),{success:true,currentScrollTop:r.scrollTop}):(document.documentElement.scrollTo({top:t,behavior:"instant",__bypassLock:true}),yf(document.documentElement.scrollTop),{success:true,currentScrollTop:document.documentElement.scrollTop})}function yf(e){ void 0!==document.documentElement.dataset.ophelPositionLock&&(document.documentElement.dataset.ophelPositionLock=String(e));}async function vf(e){const t=await pf("getScrollInfo");if(t.success)return {scrollTop:t.scrollTop||0,scrollHeight:t.scrollHeight||0,clientHeight:0,isFlutterMode:true};const n=e?.getScrollContainer();return n&&n.scrollHeight>n.clientHeight?{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,isFlutterMode:false}:{scrollTop:document.documentElement.scrollTop,scrollHeight:document.documentElement.scrollHeight,clientHeight:document.documentElement.clientHeight,isFlutterMode:false}}function xf(){const e=document.createElement("div");return Object.defineProperty(e,"__isFlutterProxy",{value:true}),e}function wf(e){return true===e.__isFlutterProxy}const Sf=1200,Cf=2,kf=10,Tf=50;function Ef(e,t){return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(t).flexDirection?Math.min(0,t.clientHeight-t.scrollHeight):0}async function Af(e){const{adapter:t,targetHeight:n,loadAll:r=false,onProgress:o,signal:i,allowShortCircuit:a=false}=e;let{previousScrollTop:s,container:l}=await mf(t);if(wf(l)){return {success:true,finalHeight:(await vf(t)).scrollHeight,heightAdded:0,previousScrollTop:s,isFlutterMode:true,silent:true}}let c=l.scrollHeight,d=c,u=0,h=0;for(;;){if(i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(h++,h>=Tf)return {success:true,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(l.scrollTop=Ef(t,l),l.dispatchEvent(new WheelEvent("wheel",{deltaY:-100,bubbles:true})),await Mf(Sf),i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(t&&("HTML"===l.tagName||"BODY"===l.tagName)){const e=t.getScrollContainer();e&&e!==l&&"HTML"!==e.tagName&&"BODY"!==e.tagName&&(l=e,c=l.scrollHeight,d=l.scrollHeight,l.scrollTop=Ef(t,l));}const e=l.scrollHeight;if(void 0!==n&&e>=n)return {success:true,finalHeight:e,heightAdded:e-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(e>d)d=e,u=0,o?.(`${Math.round(e/1e3)}k`);else {u++;const t=l.scrollHeight>l.clientHeight+100,n=1===h&&e===c;if(n&&a)return {success:true,finalHeight:e,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(n&&t)return {success:true,finalHeight:e,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(u>=(t?Cf:kf))return {success:true,finalHeight:e,heightAdded:e-c,previousScrollTop:s,isFlutterMode:false,silent:false}}}}function Mf(e){return new Promise(t=>setTimeout(t,e))}function If(e,t,n){if(!t)return;const r=t.getSessionId(),o=e.getConversations();if(0===o.length)return void Pi(le("noConversations"));const i=[...o].sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)),a=i.findIndex(e=>e.id===r);let s;s=-1===a?0:"prev"===n?a>0?a-1:i.length-1:a(nf||(nf=new tf),nf),[]),f=E(async()=>{if(!t)return;const e=await vf(t);sf(e.scrollTop),await Af({adapter:t,loadAll:true,allowShortCircuit:true}),await mf(t),Pi(le("scrolledToTop"));},[t]),b=E(async()=>{if(!t)return;const e=await vf(t);sf(e.scrollTop),await ff(t),Pi(le("scrolledToBottom"));},[t]),y=E(async()=>{if(!t)return;const e=af();if(null===e)return void Pi(le("noAnchor"));const n=(await vf(t)).scrollTop;await bf(t,e),sf(n);},[t]),v=E(()=>{n&&(n.refresh(),Pi(le("outlineRefreshed")));},[n]),x=E(()=>{if(!n)return;n.getState().isAllExpanded?n.collapseAll():n.expandAll();},[n]),w=E(e=>{n?.setLevel(e);},[n]),S=E(()=>{n?.toggleGroupMode();},[n]),C=E(()=>{n?.toggleBookmarkMode();},[n]),k=E(()=>{n?.setShowUserQueries(true),n?.setLevel(0);},[n]),T=$(null),A=E(async e=>{if(!n)return;const t=n.getState().tree;if(!t||0===t.length)return;const r=e=>{const t=[];for(const n of e)t.push(n),n.children&&n.children.length>0&&!n.collapsed&&t.push(...r(n.children));return t},o=r(t);if(0===o.length)return;let i,a=-1;if(null!==T.current){const e=o.findIndex(e=>e.index===T.current);if(-1!==e){const t=o[e];let r=t.element;if(r&&r.isConnected||(r=await n.resolveOutlineTarget(t,t.queryIndex)),r&&r.isConnected){const t=r.getBoundingClientRect(),n=window.innerHeight;Math.abs(t.top-n/2)<2*n&&(a=e);}}}if(-1===a){const e=n.getScrollContainer();if(e){const t=n.findVisibleItemIndex(e.scrollTop,e.clientHeight);null!==t&&(a=o.findIndex(e=>e.index===t));}}i=-1===a?"prev"===e?o.length-1:0:"prev"===e?Math.max(0,a-1):Math.min(o.length-1,a+1);const s=o[i];if(s){T.current=s.index,n.revealNode(s.index);let e=s.element;if(e&&e.isConnected||(e=await n.resolveOutlineTarget(s,s.queryIndex),e&&(s.element=e)),e&&e.isConnected){e.scrollIntoView({behavior:"smooth",block:"start"});Pi(s.text?.replace(/\s+/g," ").trim()||le("locatingOutline"),1e3,{className:"gh-toast--outline-nav",maxWidth:360});}}},[n]),M=E(()=>A("prev"),[A]),I=E(()=>A("next"),[A]),N=E(()=>{Pi(le("syncingConversations")),window.dispatchEvent(new CustomEvent("ophel:refreshConversations"));},[]),R=E(()=>{s();},[s]),D=E(()=>{l?.();},[l]),P=E(e=>{d?u&&h&&h():i(),window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:e}}));},[d,i,u,h]),B=E(()=>P(0),[P]),_=E(()=>P(1),[P]),O=E(()=>P(2),[P]),z=E(()=>{if(!e?.features?.outline?.enabled)return void Pi(le("outlineDisabled"));!d?i():u&&h&&h(),window.__ophelPendingLocateOutline=true,window.dispatchEvent(new CustomEvent("ophel:locateOutline")),Pi(le("locatingOutline"));},[e,d,u,i,h]),F=E(()=>{if(!e?.features?.outline?.enabled)return void Pi(le("outlineDisabled"));!d?i():u&&h&&h(),window.__ophelPendingSearchOutline=true,setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:searchOutline"));},50);},[e,d,u,i,h]),U=E(()=>{if(!e?.features?.conversations?.enabled)return void Pi(le("conversationsDisabled"));if(t?.isSharePage()||t?.isNewConversation())return void Pi(le("noConversationToLocate"));!d?i():u&&h&&h(),window.__ophelPendingLocateConversation=true,window.dispatchEvent(new CustomEvent("ophel:locateConversation")),Pi(le("locatingConversation"));},[t,e,d,u,i,h]),H=E(()=>{if(t?.startNewConversation())return;const e=ur(),n=new KeyboardEvent("keydown",{key:"o",code:"KeyO",ctrlKey:!e,metaKey:e,shiftKey:true,bubbles:true});document.dispatchEvent(n);},[t]),W=E(async()=>{if(!r||!t)return;const e=t.getSessionId();if(e)try{await r.exportConversation(e,"markdown")||Pi(le("exportFailed"));}catch(RS){console.error("Export failed:",RS),Pi(le("exportFailed"));}else Pi(le("exportNeedOpenFirst"));},[r,t]),j=E(async()=>{if(!t)return;const e=t.getLatestReplyText();if(e)try{await navigator.clipboard.writeText(e),Pi(le("replyCopied"));}catch{Pi(le("copyFailed"));}else Pi(le("noReplyToCopy"));},[t]),G=E(()=>{g?g():Pi(le("scrollLockToggled"));},[g]),V=E(()=>{if(p)p();else {const{settings:e,updateNestedSetting:t}=Mi.getState();t("panel","panelMode","edge-snap"===(e?.panel?.panelMode??"edge-snap")?"floating":"edge-snap");}},[p]),Q=E(()=>{if(!t)return;const e=t.getSiteId(),n=ai(Mi.getState().settings,e),r=!n.enabled;Mi.getState().updateDeepSetting("layout","zenMode",e,{...n,enabled:r}),Pi(le(r?"zenModeEnabledToast":"zenModeDisabledToast"));},[t]),K=E(()=>{if(!t)return;const e=t.findTextarea();e?(e.focus(),Pi(le("inputFocused"))):Pi(le("noTextarea"));},[t]),Z=E(()=>{if(!t)return;if(t.stopGeneration())return void Pi(le("generationStopped"));const e=['[data-testid="stop-button"]','button[aria-label*="Stop"]','button[aria-label*="停止"]',".stop-button",'md-icon-button[aria-label*="Stop"]'];for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return e.click(),void Pi(le("generationStopped"))}Pi(le("notGenerating"));},[t]),Y=E(()=>{r&&If(r,t,"prev");},[r,t]),X=E(()=>{r&&If(r,t,"next");},[r,t]),J=E(async()=>{const e=t?.getLastCodeBlockText?.()||"";if(e.trim()){try{await navigator.clipboard.writeText(e),Pi(le("codeBlockCopied"));}catch{Pi(le("copyFailed"));}return}const n=Array.from(document.querySelectorAll("pre code, pre, pre.code-block, .code-block code")).filter(e=>!e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview"));if(0===n.length)return void Pi(le("noCodeBlock"));const r=n[n.length-1].cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=(r.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"");if(o.trim())try{await navigator.clipboard.writeText(o),Pi(le("codeBlockCopied"));}catch{Pi(le("copyFailed"));}else Pi(le("noCodeBlock"));},[t]),ee=E(()=>{c?c():(R(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"shortcuts"}}));},100));},[c,R]),te=E(()=>{if(!t)return;t.clickModelSelector()||Pi(le("modelSelectorNotFound"));},[t]),ne=E(()=>{window.dispatchEvent(new CustomEvent("ophel:togglePromptQueue"));},[]),re=E((e,t)=>{R(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:e,subTab:t}}));},100);},[R]),oe=E(()=>re("siteSettings","claude"),[re]),ie=E(()=>re("siteSettings","gemini"),[re]),ae=E(()=>re("appearance"),[re]),se=E(()=>re("siteSettings","modelLock"),[re]),ce=E(async()=>{if(location.hostname.includes("claude.ai")||location.hostname.includes("claude.com"))try{const{platform:e}=await o(async()=>{const{platform:e}=await Promise.resolve().then(()=>_i);return {platform:e}},void 0),t=await e.switchNextClaudeKey();if(t.success)Pi(le("claudeKeySwitched")+`: ${t.keyName}`,2e3);else if("claudeOnlyOneKey"===t.error)Pi(le("claudeOnlyOneKeyTip"),2e3);else if("noClaudeKeys"===t.error)Pi(le("noClaudeKeys"),2e3);else {const e=le(t.error);Pi(e!==t.error?e:t.error||le("operationFailed"),2e3);}}catch{Pi(le("operationFailed"),2e3);}else Pi(le("claudeShortcutOnlyOnSite"),2e3);},[]);return L(()=>{const e=()=>{if("visible"===document.visibilityState&&!document.hasFocus())try{window.focus();}catch{}},t=window.setTimeout(e,150);return window.addEventListener("pageshow",e),()=>{window.clearTimeout(t),window.removeEventListener("pageshow",e);}},[]),L(()=>{m.updateSettings(e?.shortcuts);},[m,e?.shortcuts]),L(()=>{const e={[cn]:f,[dn]:b,[un]:y,[hn]:i,[gn]:V,[pn]:a,[mn]:R,[fn]:B,[bn]:_,[yn]:O,[kn]:v,[An]:x,[Mn]:()=>w(1),[In]:()=>w(2),[Ln]:()=>w(3),[Nn]:()=>w(4),[Rn]:()=>w(5),[Dn]:()=>w(6),[vn]:S,[wn]:C,[xn]:k,[Tn]:M,[En]:I,[Sn]:z,[Cn]:F,[Pn]:H,[qn]:N,[Bn]:U,[$n]:Y,[_n]:X,[On]:W,[zn]:j,[Fn]:J,[Un]:G,[Hn]:Q,[Wn]:K,[jn]:D,[Gn]:Z,[Qn]:ee,[Kn]:te,[Zn]:oe,[Yn]:ce,[Xn]:ie,[Jn]:ae,[er]:se,[Vn]:ne};return m.registerAll(e),m.startListening(),()=>{m.stopListening(),m.clearAll();}},[m,f,b,y,i,a,V,R,B,_,O,v,x,w,S,C,k,M,I,z,F,H,N,U,Y,X,W,j,J,G,Q,K,D,Z,ee,oe,te,ce,ie,ae,se,ne]),m}const Nf="ophel",Rf="Ophel Atlas",Df=GM_info?.script?.version??"1.0.0",Pf="undefined"!=typeof window&&window.__OPHEL_USERSCRIPT_ASSET_URLS__?.icon||"",qf=({checked:e,onChange:t,disabled:n=false,size:r="md"})=>{const o="sm"===r?{w:32,h:18,thumb:14}:{w:36,h:20,thumb:16}; return De("label",{style:{position:"relative",display:"inline-block",width:`${o.w}px`,height:`${o.h}px`,flexShrink:0},children:[ Re("input",{type:"checkbox",checked:e,onChange:()=>t(!e),disabled:n,style:{opacity:0,width:0,height:0,position:"absolute"}}), Re("span",{style:{position:"absolute",cursor:n?"not-allowed":"pointer",top:0,left:0,right:0,bottom:0,backgroundColor:e?"var(--gh-primary, #4285f4)":"var(--gh-input-border, #d1d5db)",borderRadius:`${o.h}px`,transition:"background-color 0.3s"},children:Re("span",{style:{position:"absolute",height:`${o.thumb}px`,width:`${o.thumb}px`,left:e?o.w-o.thumb-2+"px":"2px",bottom:(o.h-o.thumb)/2+"px",backgroundColor:"var(--gh-bg, #ffffff)",borderRadius:"50%",transition:"left 0.3s"}})})]})};let Bf=false;const $f=({children:e,onClose:t,closeOnOverlayClick:n=true,closeOnEscape:r=true,dialogClassName:o,dialogStyle:i})=>{const a=$(null);L(()=>{(()=>{if(Bf)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .gh-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 2147483647;\n }\n .gh-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 280px;\n max-width: 400px;\n box-shadow: var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3));\n }\n .gh-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 12px;\n }\n .gh-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-wrap;\n }\n .gh-dialog-buttons {\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n }\n .gh-dialog-btn {\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 14px;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n }\n .gh-dialog-btn-secondary {\n border: 1px solid var(--gh-border, #d1d5db);\n background: var(--gh-bg, white);\n color: var(--gh-text, #374151);\n }\n .gh-dialog-btn-secondary:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n .gh-dialog-btn-primary {\n background: var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%));\n color: white;\n }\n .gh-dialog-btn-danger {\n background: var(--gh-text-danger, #ef4444);\n color: white;\n }\n .gh-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-border, #d1d5db);\n border-radius: 6px;\n font-size: 14px;\n box-sizing: border-box;\n margin-bottom: 20px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .gh-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n }\n",document.head.appendChild(e),Bf=true;})();const e=e=>{r&&"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r,t]),L(()=>{const e=a.current;if(e)return as(e,{capture:false})},[]);const s=Re("div",{ref:a,className:"gh-dialog-overlay gh-interactive",...ns,onClick:n?t:void 0,children:Re("div",{className:o?`gh-dialog ${o}`:"gh-dialog",style:i,onClick:e=>e.stopPropagation(),children:e})});return Kc(s,document.body)},_f=({title:e,message:t,confirmText:n,cancelText:r,danger:o=false,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s,extraAction:l})=>De($f,{onClose:s,closeOnOverlayClick:i,children:[ Re("div",{className:"gh-dialog-title",children:e}), Re("div",{className:"gh-dialog-message",children:t}), De("div",{className:"gh-dialog-buttons",style:{justifyContent:l?"space-between":"flex-end"},children:[l&&De("button",{className:"gh-dialog-btn",style:{background:"transparent",color:"var(--gh-primary, #4285f4)",padding:"8px 12px",textDecoration:"underline"},onClick:l.onClick,children:["↗ ",l.text]}), De("div",{style:{display:"flex",gap:"8px"},children:[ Re("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:r||le("cancel")}), Re("button",{className:"gh-dialog-btn "+(o?"gh-dialog-btn-danger":"gh-dialog-btn-primary"),onClick:a,children:n||le("confirm")})]})]})]}),Of=({title:e,defaultValue:t="",placeholder:n,confirmText:r,cancelText:o,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s})=>{const[l,c]=_(t),d=$(null);L(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{a(l);}; return De($f,{onClose:s,closeOnOverlayClick:i,children:[ Re("div",{className:"gh-dialog-title",children:e}), Re("input",{ref:d,type:"text",className:"gh-dialog-input",value:l,onChange:e=>c(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&u()}), De("div",{className:"gh-dialog-buttons",children:[ Re("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:o||le("cancel")}), Re("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:u,children:r||le("confirm")})]})]})},zf=({variant:e="secondary",size:t="md",style:n,children:r,...o})=>{const i="sm"===t?{padding:"4px 8px",fontSize:"12px"}:{padding:"8px 16px",fontSize:"14px"}; return Re("button",{...o,style:{borderRadius:"6px",cursor:o.disabled?"not-allowed":"pointer",transition:"all 0.2s",fontWeight:500,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"4px",opacity:o.disabled?.5:1,...i,...{primary:{background:"var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%))",color:"white",border:"none"},secondary:{background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",border:"1px solid var(--gh-input-border, #d1d5db)"},danger:{background:"var(--gh-text-danger, #ef4444)",color:"white",border:"none"},ghost:{background:"transparent",color:"var(--gh-text-secondary, #6b7280)",border:"none"}}[e],...n},children:r})},Ff=({value:e,onChange:t,min:n,max:r,defaultValue:o,disabled:i=false,style:a,className:s="settings-input",step:l=1})=>{const[c,d]=_(e.toString()),u=$(false),h=$(null),g=$(null);L(()=>{u.current||d(e.toString());},[e]);const p=E(i=>{let a=parseInt(i);isNaN(a)&&(a=o??e??0),void 0!==n&&ar&&(a=r),d(a.toString()),a!==e&&t(a);},[n,r,o,e,t]),m=E(t=>{if(i)return;let n=parseInt(c);isNaN(n)&&(n=o??e??0);p((n+t).toString());},[c,o,e,i,p]);L(()=>()=>{h.current&&clearTimeout(h.current);},[]);const[f,b]=_(false); return De("div",{className:s,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),style:{...a,position:"relative",display:"inline-flex",alignItems:"center"},children:[ Re("input",{ref:g,type:"text",inputMode:"numeric",pattern:"[0-9]*",style:{width:"100%",paddingRight:"20px",height:"100%",border:"none",background:"transparent",outline:"none",color:"inherit",fontSize:"inherit",fontFamily:"inherit",paddingLeft:"8px",textAlign:"left"},value:c,disabled:i,onChange:e=>{const t=e.target.value.replace(/[^0-9-]/g,"");d(t);},onFocus:()=>{h.current&&(clearTimeout(h.current),h.current=null),u.current=true;},onBlur:()=>{h.current=setTimeout(()=>{document.activeElement!==g.current&&(u.current=false,p(c));},100);},onKeyDown:e=>{"Enter"===e.key?(p(c),g.current?.blur()):"ArrowUp"===e.key?(e.preventDefault(),m(l)):"ArrowDown"===e.key&&(e.preventDefault(),m(-l));}}),!i&&De("div",{style:{position:"absolute",right:"2px",top:"2px",bottom:"2px",display:"flex",flexDirection:"column",width:"16px",background:"transparent",opacity:f?1:.2,transition:"opacity 0.2s ease",pointerEvents:f?"auto":"none"},children:[ Re("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"3px 3px 0 0",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)",marginBottom:"1px"},children:Re(Rt,{size:8})}), Re("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(-l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"0 0 3px 3px",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)"},children:Re(Dt,{size:8})})]})]})},Uf=(e,t,n)=>Math.min(n,Math.max(t,e)),Hf=({value:e,onChange:t,onPreviewChange:n,onCancelPreview:r,min:o,max:i,step:a=1,unit:s,defaultValue:l,disabled:c=false,style:d,className:u="",formatValue:h,ariaLabel:g})=>{const p=Uf(Number.isFinite(e)?e:o,o,i),[m,f]=_(p),[b,y]=_(false),v=$(false),x=$(p),w=$(r);L(()=>{w.current=r;},[r]),L(()=>{x.current=m;},[m]),L(()=>()=>{v.current&&(v.current=false,w.current?.());},[]),L(()=>{b||(f(p),x.current=p);},[p,b]);const S=i===o?0:(m-o)/(i-o)*100,C=h?h(m):`${m}${s||""}`,k=void 0===l?void 0:Uf(l,o,i),T=void 0!==k&&m===k,A=E((e=x.current)=>{v.current&&!c&&(v.current=false,t(Uf(e,o,i)));},[c,i,o,t]);L(()=>{if(!b)return;const e=()=>{y(false),A();};return window.addEventListener("pointerup",e),window.addEventListener("mouseup",e),window.addEventListener("touchend",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e);}},[A,b]); return Re("div",{className:`settings-slider ${c?"disabled":""} ${u}`.trim(),style:{...d,"--slider-progress":`${S}%`},children:De("div",{className:"settings-slider-main",children:[ De("div",{className:"settings-slider-track",children:[ Re("input",{type:"range",className:"settings-slider-input",min:o,max:i,step:a,value:m,onChange:e=>{const t=Uf(Number.parseFloat(e.target.value),o,i);f(t),x.current=t,v.current=true,n?.(t);},onPointerDown:()=>y(true),onMouseDown:()=>y(true),onTouchStart:()=>y(true),onBlur:()=>{y(false),A();},onKeyUp:e=>{["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)&&A();},disabled:c,"aria-label":g,"aria-valuemin":o,"aria-valuemax":i,"aria-valuenow":m,"aria-valuetext":C}), De("div",{className:"settings-slider-boundary",children:[ Re("span",{children:h?h(o):`${o}${s||""}`}), Re("span",{children:h?h(i):`${i}${s||""}`})]})]}), Re("span",{className:"settings-slider-value",children:C}),void 0!==k&&Re("button",{type:"button",className:"settings-slider-reset",onClick:()=>{ void 0===k||c||(v.current=false,f(k),x.current=k,t(k));},disabled:c||T,title:le("restore"),"aria-label":le("restore"),children:Re(Tt,{size:14})})]})})},Wf=({options:e,value:t,onChange:n,placeholder:r,disabled:o=false,emptyText:i,maxMenuHeight:a=260,className:s,buttonClassName:l,menuClassName:c,optionClassName:d,ariaLabel:u,onOpenChange:h})=>{const[g,p]=_(false),[m,f]=_(-1),b=$(null),y=$(null),v=$([]),x=q(()=>e.findIndex(e=>e.value===t),[e,t]),w=x>=0?e[x]:null;L(()=>{h?.(g);},[g,h]),L(()=>{if(!g)return;const t=x>=0?x:e.findIndex(e=>!e.disabled);f(t);},[g,e,x]),L(()=>{if(!g||m<0)return;const e=v.current[m];e?.scrollIntoView({block:"nearest"});},[g,m]),L(()=>{if(!g)return;const e=e=>{const t=b.current;if(!t)return;const n=(e=>{const t=e.composedPath;return "function"==typeof t?t.call(e):[]})(e);if(n.length>0)return void(n.includes(t)||p(false));const r=e.target;r&&!t.contains(r)&&p(false);},t=()=>{p(false);};return window.addEventListener("pointerdown",e,true),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,true),window.removeEventListener("blur",t);}},[g]);const S=e=>{p(false),e&&window.requestAnimationFrame(()=>{y.current?.focus({preventScroll:true});});},C=(t,n)=>{if(0===e.length)return -1;let r=t;for(let o=0;o=e.length&&(r=0),r<0&&(r=e.length-1),!e[r]?.disabled)return r;return -1},k=t=>{const r=e[t];r&&!r.disabled&&(n(r.value),S(true));}; return De("div",{ref:b,className:s,style:{position:"relative",width:"100%"},children:[ De("button",{ref:y,type:"button",className:l,disabled:o,"aria-label":u,"aria-haspopup":"listbox","aria-expanded":g,onClick:()=>!o&&p(e=>!e),onKeyDown:e=>{if(!o){if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!g)return void p(true);const t=C(m<0?x:m,"ArrowDown"===e.key?1:-1);return void(t>=0&&f(t))}if("Enter"===e.key||" "===e.key)return e.preventDefault(),void p(e=>!e);"Escape"===e.key&&g&&(e.preventDefault(),p(false));}},title:w?.title,style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",textAlign:"left"},children:[ Re("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:"8px"},children:w?.label||r}), Re(Dt,{size:16,style:{flexShrink:0,transition:"transform 0.2s ease",transform:g?"rotate(180deg)":"rotate(0deg)"}})]}),g&&Re("div",{role:"listbox",tabIndex:-1,className:c,...ns,onKeyDown:t=>{if("ArrowDown"===t.key){t.preventDefault();const e=C(m,1);return void(e>=0&&f(e))}if("ArrowUp"===t.key){t.preventDefault();const e=C(m,-1);return void(e>=0&&f(e))}if("Home"===t.key){t.preventDefault();const n=e.findIndex(e=>!e.disabled);return void(n>=0&&f(n))}if("End"===t.key){t.preventDefault();const n=[...e].reverse().findIndex(e=>!e.disabled);return void(n>=0&&f(e.length-n-1))}return "Enter"===t.key?(t.preventDefault(),void(m>=0&&k(m))):"Escape"===t.key?(t.preventDefault(),void S(true)):void("Tab"===t.key&&S(false))},style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,maxHeight:`${a}px`,overflowY:"auto",zIndex:100,borderRadius:"8px",border:"1px solid var(--gh-input-border, #d1d5db)",boxShadow:"var(--gh-shadow-md, 0 8px 16px rgba(0,0,0,0.12))",background:"var(--gh-bg, #ffffff)",padding:"4px"},children:0===e.length?Re("div",{style:{padding:"8px 10px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"13px",textAlign:"left"},children:i||"No options"}):e.map((e,n)=>{const r=e.value===t,o=n===m; return Re("button",{ref:e=>{v.current[n]=e;},type:"button",role:"option","aria-selected":r,className:d,disabled:e.disabled,title:e.title,onMouseEnter:()=>{e.disabled||f(n);},onClick:()=>k(n),style:{width:"100%",border:"none",borderRadius:"6px",padding:"7px 10px",textAlign:"left",background:r?"var(--gh-border-active, #3b82f6)":o?"var(--gh-hover, #f3f4f6)":"transparent",color:r?"#ffffff":"var(--gh-text, #1f2937)",cursor:e.disabled?"not-allowed":"pointer",display:"flex",alignItems:"center",gap:"8px",fontSize:"14px",lineHeight:1.4},children:e.label},e.value)})})]})};function jf(e,t){if(!e)return null;const n=function(e){const t=e.filter(Boolean).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return 0===t.length?null:new RegExp(`(${t.join("|")})`,"g")}(t);if(!n)return e;const r=[];let o,i=0;for(;null!==(o=n.exec(e));)o.index>i&&r.push(e.slice(i,o.index)),r.push( Re("span",{className:"placeholder-input-chip",children:o[0]},`${o[0]}-${o.index}`)),i=n.lastIndex;return i{const s=$(null),l=$(null),c=$(e),d=$({start:e.length,end:e.length});L(()=>{c.current=e;const t=e.length;d.current={start:Math.min(d.current.start,t),end:Math.min(d.current.end,t)};},[e]);const u=E(()=>{const e=s.current;if(!e)return;const t=e.selectionStart??c.current.length,n=e.selectionEnd??t;d.current={start:t,end:n};},[]),h=E(e=>{const t=s.current;t&&(t.focus(),t.setSelectionRange(e,e),d.current={start:e,end:e});},[]),g=E(()=>{const e=s.current,t=l.current;e&&t&&(t.style.transform=`translateX(-${e.scrollLeft}px)`);},[]);L(()=>{g();},[g,e]);const p=E(e=>{c.current=e.target.value,t(e.target.value),u(),requestAnimationFrame(g);},[t,u,g]),m=E(e=>{if(a)return;const n=s.current,r=c.current,o=n?.selectionStart??d.current.start,i=n?.selectionEnd??d.current.end,l=`${r.slice(0,o)}${e}${r.slice(i)}`,u=o+e.length;c.current=l,t(l),requestAnimationFrame(()=>{h(u),g();});},[a,t,h,g]),f=["placeholder-input-native",o].filter(Boolean).join(" "); return De("div",{className:"placeholder-input-field "+(a?"placeholder-input-disabled":""),style:i,children:[ De("div",{className:"placeholder-input-surface",children:[ Re("div",{className:"placeholder-input-mirror","aria-hidden":"true",children:Re("span",{ref:l,className:"placeholder-input-mirror-scroll",children:jf(e,n)})}), Re("input",{ref:s,type:"text",dir:"ltr",className:f,value:e,onChange:p,onSelect:u,onClick:u,onKeyUp:u,onScroll:g,placeholder:r,disabled:a})]}), Re("div",{className:"placeholder-input-list","aria-label":"Title format placeholders",children:n.map(e=>Re("button",{type:"button",className:"placeholder-input-button",disabled:a,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:e,children:e},e))})]})};let Vf=false;const Qf=e=>{if("inbox"===e.id)return (()=>{const e=le("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},Kf=({children:e,onClose:t})=>{L(()=>{(()=>{if(Vf)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .conversations-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n z-index: 1000003;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .conversations-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 320px;\n max-width: min(480px, calc(100vw - 40px));\n box-shadow: var(--gh-shadow-lg, 0 10px 40px rgba(0,0,0,0.2));\n }\n .conversations-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 16px;\n }\n .conversations-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #4b5563);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-line;\n word-break: break-word;\n overflow-wrap: break-word;\n }\n .conversations-dialog-section {\n margin-bottom: 16px;\n }\n .conversations-dialog-section label {\n display: block;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 8px;\n }\n .conversations-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-input-border, #d1d5db);\n border-radius: 8px;\n font-size: 14px;\n box-sizing: border-box;\n background: var(--gh-input-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .conversations-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n box-shadow: var(--gh-input-focus-shadow, 0 0 0 2px rgba(66,133,244,0.1));\n }\n .conversations-dialog-buttons {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n margin-top: 20px;\n }\n .emoji-grid-hidden-scrollbar::-webkit-scrollbar {\n display: none;\n width: 0;\n height: 0;\n }\n @keyframes gh-highlight-fade {\n 0% { background-color: var(--gh-highlight-pulse, rgba(59, 130, 246, 0.3)); }\n 100% { background-color: transparent; }\n }\n .conversations-folder-select-highlight {\n animation: gh-highlight-fade 2s ease-out;\n }\n",document.head.appendChild(e),Vf=true;})();const e=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t]);const n=Re("div",{className:"conversations-dialog-overlay",...ns,onClick:t,children:Re("div",{className:"conversations-dialog",onClick:e=>e.stopPropagation(),children:e})});return Kc(n,document.body)},Zf=({title:e,message:t,confirmText:n,cancelText:r,danger:o,onConfirm:i,onCancel:a})=>De(Kf,{onClose:a,children:[ Re("div",{className:"conversations-dialog-title",children:e}), Re("div",{className:"conversations-dialog-message",children:t}), De("div",{className:"conversations-dialog-buttons",children:[ Re(zf,{variant:"secondary",onClick:a,children:r||le("cancel")}), Re(zf,{variant:o?"danger":"primary",onClick:i,children:n||le("confirm")})]})]}),Yf=({folder:e,onConfirm:t,onCancel:n})=>{const r=e?.icon||"📁",[o,i]=_(e?.name.replace(e.icon,"").trim()||""),[a,s]=_(r),[l,c]=_(Qr.includes(r)?r:null),d=$(null);L(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{const e=o.trim();e&&t(e,a);}; return De(Kf,{onClose:n,children:[ Re("div",{className:"conversations-dialog-title",children:le(e?"conversationsRename":"conversationsAddFolder")}), De("div",{className:"conversations-dialog-section",children:[ Re("label",{children:le("conversationsIcon")}), De("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"4px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"4px",border:"1px solid var(--gh-border, #e5e7eb)",marginBottom:"8px"},children:[ Re("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:le("conversationsCustomIcon")}), Re("input",{type:"text",value:a,onChange:e=>{let t=e.target.value;const n=/[^\p{Extended_Pictographic}\u200d\ufe0f]/gu;t&&n.test(t)&&(t=t.replace(n,"")),s(t),t&&!Qr.includes(t)?c(null):Qr.includes(t)&&c(t);},maxLength:4,placeholder:"☺",style:{width:"60px",textAlign:"center",border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",padding:"2px",fontSize:"16px",background:"var(--gh-input-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), Re("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:"4px",maxHeight:"120px",overflowY:"auto",padding:"2px",scrollbarWidth:"none",msOverflowStyle:"none"},className:"emoji-grid-hidden-scrollbar",children:Qr.map(e=>Re("button",{type:"button",onClick:()=>(e=>{c(e),s(e);})(e),style:{width:"24px",height:"24px",padding:0,display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:l===e?"#dbeafe":"transparent",cursor:"pointer",borderRadius:"4px",fontSize:"16px",transition:"background 0.15s"},onMouseEnter:t=>{l!==e&&(t.currentTarget.style.background="var(--gh-hover, #f3f4f6)");},onMouseLeave:t=>{l!==e&&(t.currentTarget.style.background="transparent");},children:e},e))})]}), De("div",{className:"conversations-dialog-section",children:[ Re("label",{children:le("conversationsFolderName")}), Re("input",{ref:d,type:"text",className:"conversations-dialog-input",value:o,onChange:e=>i(e.target.value),placeholder:le("conversationsFolderNamePlaceholder"),onKeyDown:e=>"Enter"===e.key&&u()})]}), De("div",{className:"conversations-dialog-buttons",children:[ Re(zf,{variant:"secondary",onClick:n,children:le("cancel")}), Re(zf,{variant:"primary",onClick:u,children:le("confirm")})]})]})},Xf=({title:e,currentValue:t,placeholder:n,onConfirm:r,onCancel:o})=>{const[i,a]=_(t),s=$(null);L(()=>{s.current?.focus(),s.current?.select();},[]);const l=()=>{const e=i.trim();e&&e!==t?r(e):o();}; return De(Kf,{onClose:o,children:[ Re("div",{className:"conversations-dialog-title",children:e}), Re("div",{className:"conversations-dialog-section",children:Re("input",{ref:s,type:"text",className:"conversations-dialog-input",value:i,onChange:e=>a(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&l()})}), De("div",{className:"conversations-dialog-buttons",children:[ Re(zf,{variant:"secondary",onClick:o,children:le("cancel")}), Re(zf,{variant:"primary",onClick:l,children:le("confirm")})]})]})},Jf=({folders:e,excludeFolderId:t,activeFolderId:n,title:r,onSelect:o,onCancel:i,onCreateFolder:a})=>{const[s,l]=_(""),c=$(null);L(()=>{c.current?.focus();},[]),L(()=>{n&&setTimeout(()=>{const e=document.getElementById(`folder-select-${n}`);e&&(e.scrollIntoView({block:"center",behavior:"smooth"}),e.classList.add("conversations-folder-select-highlight"));},150);},[n]);const d=e.filter(e=>e.id!==t&&(!s||Qf(e).toLowerCase().includes(s.toLowerCase()))); return De(Kf,{onClose:i,children:[ Re("div",{className:"conversations-dialog-title",children:r||le("conversationsMoveTo")}), De("div",{style:{display:"flex",gap:"8px",marginBottom:"12px"},children:[ Re("input",{ref:c,type:"text",className:"conversations-dialog-input",style:{flex:1},placeholder:le("conversationsSearchFolder"),value:s,onChange:e=>l(e.target.value)}),a&&Re(zf,{variant:"primary",style:{padding:"8px 12px"},onClick:()=>{i(),a();},title:le("conversationsAddFolder"),children:"+"})]}), De("div",{className:"conversations-folder-select-list",children:[d.map(e=>De("div",{id:`folder-select-${e.id}`,className:"conversations-folder-select-item",onClick:()=>o(e.id),children:[e.icon," ",Qf(e)]},e.id)),0===d.length&&Re("div",{style:{padding:"16px",textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)"},children:le("conversationsNoSearchResult")})]}), Re("div",{className:"conversations-dialog-buttons",children:Re(zf,{variant:"secondary",onClick:i,children:le("cancel")})})]})},eb=({tags:e,conv:t,onCancel:n,onCreateTag:r,onUpdateTag:o,onDeleteTag:i,onSetConversationTags:a,onRefresh:s})=>{const[l,c]=_(null),[d,u]=_(""),[h,g]=_(Kr[0]),[p,m]=_(Kr[0]),[f,b]=_(false),[y,v]=_(false),[x,w]=_(false),[S,C]=_(null),[k,T]=_(new Set(t?.tagIds||[])),E=$(null),A=$(null);L(()=>{E.current?.focus();},[]),L(()=>{T(new Set(t?.tagIds||[]));},[t?.id,t?.tagIds]);const M=(e,t="click")=>{let n=e.startsWith("#")?e:`#${e}`;g(n),"input"!==t&&(m(n),b(false));},I=async()=>{const e=d.trim();if(!e)return;v(true);let t=null;l?(t=await o(l,e,h),t&&(c(null),u(""))):(t=await r(e,h),t&&u("")),v(false),s();}; return De(Kf,{onClose:n,children:[ De("div",{className:"conversations-dialog-title",style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("span",{children:le("conversationsManageTags")}), Re(od,{content:le("close"),children:Re("span",{style:{cursor:"pointer",padding:"4px",fontSize:"20px",color:"var(--gh-text-secondary, #9ca3af)",lineHeight:1,width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px"},onClick:n,children:Re($e,{size:18})})})]}), De("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",marginBottom:"16px",background:"var(--gh-bg-secondary, #fafafa)"},children:[ De("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",fontWeight:500,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("span",{children:le(t?"conversationsSelectTag":"conversationsExistingTags")}), De("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #9ca3af)"},children:[e.length," 个"]})]}), Re("div",{style:{maxHeight:"320px",overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none"},children:0===e.length?Re("div",{style:{padding:"24px 16px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)"},children:le("conversationsNoTags")}):e.map(e=>{const n=k.has(e.id),r=l===e.id; return De("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderBottom:"1px solid var(--gh-border, #f3f4f6)",cursor:t?"pointer":"default",background:r?"var(--gh-bg-warning-light, #fffbeb)":n?"var(--gh-folder-bg-default)":"transparent",transition:"background 0.15s"},onClick:()=>{t&&(async(e,n)=>{if(!t||!a)return;const r=new Set(k);n?r.add(e):r.delete(e),T(r),await a(t.id,Array.from(r)),s();})(e.id,!n);},onMouseEnter:e=>{r||n||(e.currentTarget.style.background="var(--gh-hover, #f9fafb)");},onMouseLeave:e=>{r||n||(e.currentTarget.style.background="transparent");},children:[ De("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t&&Re("input",{type:"checkbox",checked:n,onChange:()=>{},onClick:e=>e.stopPropagation(),style:{cursor:"pointer",width:"16px",height:"16px",accentColor:e.color}}), De("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 10px",borderRadius:"4px",fontSize:"13px",color:"white",backgroundColor:e.color,fontWeight:n?500:400,boxShadow:n?"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.2))":"none"},children:[e.name,r&&Re(zt,{size:10})]})]}), De("div",{style:{display:"flex",gap:"2px"},children:[ Re(od,{content:le("edit"),children:Re("button",{style:{background:r?"#fed7aa":"transparent",border:"none",color:r?"#ea580c":"#9ca3af",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{t.stopPropagation(),(e=>{c(e.id),u(e.name),M(e.color),E.current?.focus();})(e);},onMouseEnter:e=>{r||(e.currentTarget.style.background="#e0f2fe",e.currentTarget.style.color="#0284c7");},onMouseLeave:e=>{r||(e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af");},children:Re(zt,{size:14})})}), Re(od,{content:le("delete"),children:Re("button",{style:{background:"transparent",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{var n;t.stopPropagation(),n=e.id,C(n);},onMouseEnter:e=>{e.currentTarget.style.background="#fee2e2",e.currentTarget.style.color="#dc2626";},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af";},children:Re($e,{size:18})})})]})]},e.id)})})]}), De("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",background:l?"var(--gh-bg-warning-light, #fffbeb)":"var(--gh-bg, #ffffff)",transition:"background 0.2s"},children:[ De("div",{style:{fontSize:"12px",color:l?"var(--gh-text-warning, #b45309)":"var(--gh-text-secondary, #6b7280)",fontWeight:500,marginBottom:"10px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("span",{children:le(l?"conversationsEditTag":"conversationsNewTag")}),l&&Re("button",{style:{background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"11px",padding:"2px 6px"},onClick:()=>{c(null),u(""),M(Kr[0]);},children:le("conversationsCancelEdit")})]}), Re("input",{ref:E,type:"text",className:"conversations-dialog-input",placeholder:le("conversationsTagName"),value:d,onChange:e=>u(e.target.value),onKeyDown:e=>"Enter"===e.key&&I(),style:{marginBottom:"12px",borderColor:l?"#fbbf24":void 0}}), De("div",{style:{marginBottom:"12px",position:"relative"},children:[ De("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 10px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",cursor:"pointer",background:"var(--gh-bg-secondary, #fafafa)",transition:"border-radius 0.15s, background-color 0.2s",userSelect:"none"},onClick:()=>w(!x),onMouseEnter:e=>e.currentTarget.style.backgroundColor="var(--gh-hover, #f3f4f6)",onMouseLeave:e=>e.currentTarget.style.backgroundColor="var(--gh-bg-secondary, #fafafa)",children:[ Re("div",{style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h,border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",flexShrink:0}}), Re("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #666)",flex:1},children:le(x?"conversationsCollapseColor":"conversationsSelectColor")}), Re(Dt,{size:16,color:"#9ca3af",style:{transition:"transform 0.2s",transform:x?"rotate(180deg)":"rotate(0deg)"}})]}),x&&De("div",{style:{position:"absolute",top:"100%",left:0,right:0,marginTop:"4px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"10px",background:"var(--gh-bg, #ffffff)",zIndex:10,boxShadow:"var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15))"},children:[ Re("div",{style:{display:"grid",gridTemplateColumns:"repeat(10, 1fr)",gap:"6px",marginBottom:"12px"},children:Kr.map(e=>Re(od,{content:e,children:Re("div",{style:{width:"100%",aspectRatio:"1",borderRadius:"4px",backgroundColor:e,cursor:"pointer",border:h.toLowerCase()===e.toLowerCase()?"2px solid #333":"1px solid rgba(0,0,0,0.05)",transition:"transform 0.1s",boxSizing:"border-box"},onClick:()=>{M(e),w(false);},onMouseEnter:e=>e.currentTarget.style.transform="scale(1.15)",onMouseLeave:e=>e.currentTarget.style.transform="scale(1)"})},e))}), De("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ De("div",{style:{position:"relative",width:"28px",height:"28px",borderRadius:"50%",overflow:"hidden",cursor:"pointer",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",border:Kr.includes(h.toUpperCase())?"2px solid transparent":"2px solid #666",flexShrink:0},children:[ Re("div",{style:{width:"100%",height:"100%",background:Kr.includes(h.toUpperCase())?"conic-gradient(from 180deg, red, yellow, lime, aqua, blue, magenta, red)":h}}), Re("input",{ref:A,type:"color",value:h,onChange:e=>{M(e.target.value,"picker"),w(false);},style:{position:"absolute",left:"-50%",top:"-50%",width:"200%",height:"200%",opacity:0,cursor:"pointer"}})]}), De("div",{style:{display:"flex",alignItems:"center",flex:1,background:"var(--gh-bg-secondary, #f3f4f6)",border:"1px solid "+(f?"#ef4444":"var(--gh-border, #e5e7eb)"),borderRadius:"6px",padding:"4px 8px",height:"30px",boxSizing:"border-box"},children:[ Re("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #6b7280)",marginRight:"6px",fontFamily:"monospace",fontWeight:600},children:"HEX"}), Re("input",{type:"text",value:p,onChange:e=>(e=>{if(m(e),/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(e)){b(false);let t=e;4===e.length&&(t=`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`),M(t,"input");}else b(true);})(e.target.value),onBlur:()=>{f&&(m(h),b(false));},style:{border:"none",background:"transparent",outline:"none",fontSize:"13px",fontFamily:"monospace",width:"100%",color:"var(--gh-text, #374151)",textTransform:"uppercase"}})]})]})]})]}), Re(zf,{variant:"primary",style:{width:"100%",...l&&{background:"var(--gh-warning-gradient, linear-gradient(135deg, #f59e0b 0%, #d97706 100%))"}},disabled:!d.trim()||y,onClick:I,children:le(l?"conversationsUpdateTag":"conversationsNewTag")})]}),S&&Re(Zf,{title:le("conversationsDeleteTag"),message:le("confirmDelete"),confirmText:le("delete"),cancelText:le("cancel"),danger:true,onConfirm:async()=>{S&&(await i(S),C(null),s());},onCancel:()=>C(null)})]})},tb=()=>({url:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",icon:Re(_t,{size:14}),label:le("reviewBtn")}),nb=()=>{const{settings:e,setSettings:t}=Mi();if(!Ii()||!e||e.hasAgreedToTerms)return null; return De("div",{className:"disclaimer-modal-overlay",children:[ De("div",{className:"disclaimer-modal",children:[ De("div",{className:"disclaimer-header",children:[ Re("img",{src:Pf,alt:"Ophel",className:"disclaimer-icon-img"}), De("div",{className:"disclaimer-slogan-container",children:[ Re("span",{className:"sparkle","aria-hidden":"true",children:"✨"}), Re("h2",{className:"disclaimer-title",children:le("welcomeSlogan")}), Re("span",{className:"sparkle","aria-hidden":"true",children:"✨"})]})]}), De("div",{className:"disclaimer-content",children:[ De("div",{className:"disclaimer-section",children:[ Re("p",{children:le("disclaimerText")}), Re("p",{className:"disclaimer-warning",children:le("disclaimerWarning")})]}), De("div",{className:"disclaimer-section privacy-section",children:[ De("div",{className:"privacy-header",children:[ Re(pt,{size:20,className:"privacy-icon"}), Re("h3",{className:"privacy-title",children:le("privacyTitle")})]}), Re("p",{className:"privacy-content",children:le("privacyText")})]}), De("div",{className:"disclaimer-section quote-section",children:[ Re("p",{className:"disclaimer-quote-text",children:le("communityMotto")}), De("div",{className:"action-row",children:[ De("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"star-btn",children:[ Re(ut,{size:18}), Re("span",{children:le("giveStar")})]}), De("a",{href:tb().url,target:"_blank",rel:"noopener noreferrer",className:"star-btn review-btn",children:[tb().icon, Re("span",{children:tb().label})]})]}), De("div",{className:"secondary-links",children:[ Re("a",{href:"https://github.com/urzeye/ophel/pulls",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"PR"}), Re("span",{className:"divider",children:"/"}), Re("a",{href:"https://github.com/urzeye/ophel/issues",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"Issue"})]})]})]}), Re("div",{className:"disclaimer-footer",children:Re("button",{className:"disclaimer-agree-btn",onClick:()=>{t({hasAgreedToTerms:true});},children:le("agreeButton")})})]}), Re("style",{children:`\n .disclaimer-modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${me};\n pointer-events: auto;\n }\n\n .disclaimer-modal {\n background: var(--gh-bg, #ffffff);\n border-radius: 16px;\n width: 90%;\n max-width: 600px;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n overflow: hidden;\n color: var(--gh-text, #1f2937);\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n animation: modal-pop 0.3s cubic-bezier(0.16, 1, 0.3, 1);\n }\n\n .disclaimer-header {\n padding: 24px 24px 0;\n text-align: center;\n }\n\n .disclaimer-icon-img {\n width: 64px;\n height: 64px;\n margin-bottom: 20px;\n object-fit: contain;\n border-radius: 50%;\n background: var(--gh-bg, #ffffff);\n padding: 6px;\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n transition: transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);\n /* Ensure centering if parent is flex or block */\n display: inline-block;\n }\n\n .disclaimer-icon-img:hover {\n transform: rotate(360deg) scale(1.1);\n border-color: #3b82f6;\n box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.2);\n }\n\n .disclaimer-slogan-container {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n }\n\n .sparkle {\n font-size: 18px;\n }\n\n .disclaimer-title {\n font-size: 20px;\n font-weight: 700;\n margin: 0;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n }\n\n .disclaimer-content {\n padding: 24px;\n }\n\n .disclaimer-section {\n margin-bottom: 20px;\n }\n\n .disclaimer-section h3 {\n font-size: 16px;\n font-weight: 600;\n margin: 0 0 8px;\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .disclaimer-section p {\n font-size: 14px;\n line-height: 1.6;\n margin: 0;\n color: var(--gh-text-secondary, #4b5563);\n }\n\n .disclaimer-warning {\n margin-top: 8px !important;\n color: #ef4444 !important;\n font-weight: 500;\n background: rgba(239, 68, 68, 0.1);\n padding: 8px 12px;\n border-radius: 6px;\n }\n\n .quote-section {\n text-align: center;\n background: var(--gh-bg-secondary, #f3f4f6);\n padding: 20px;\n border-radius: 12px;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n margin-bottom: 0;\n }\n\n .privacy-section {\n background: rgba(16, 185, 129, 0.1);\n border: 1px solid rgba(16, 185, 129, 0.2);\n border-radius: 12px;\n padding: 16px;\n margin-bottom: 20px;\n }\n\n .privacy-header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n color: #10b981;\n }\n\n .privacy-title {\n font-size: 15px;\n font-weight: 600;\n margin: 0;\n }\n\n .privacy-content {\n font-size: 13px !important;\n color: #059669 !important;\n line-height: 1.5 !important;\n margin: 0;\n }\n\n :host-context([data-gh-mode="dark"]) .privacy-content {\n color: #34d399 !important;\n }\n\n .disclaimer-quote-text {\n font-size: 15px;\n font-weight: 600;\n line-height: 1.5;\n color: var(--gh-text, #1f2937) !important;\n margin: 0 !important;\n font-style: italic;\n }\n\n .action-row {\n display: flex;\n align-items: center;\n gap: 12px;\n flex-wrap: wrap;\n justify-content: center;\n }\n\n .star-btn {\n display: flex;\n align-items: center;\n gap: 8px;\n background: #24292e; /* GitHub Dark */\n color: white;\n padding: 8px 20px;\n border-radius: 20px;\n text-decoration: none;\n font-weight: 600;\n font-size: 14px;\n transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n border: 1px solid rgba(255,255,255,0.1);\n }\n\n .star-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2);\n background: #2f363d;\n border-color: rgba(255,255,255,0.2);\n color: white;\n }\n\n .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .star-btn:active {\n transform: scale(0.96);\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn {\n background: #3b82f6;\n border: none;\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn:hover {\n background: #2563eb;\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .secondary-links {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .sec-link {\n color: var(--gh-text-secondary, #6b7280);\n text-decoration: none;\n transition: color 0.2s;\n }\n\n .sec-link:hover {\n color: #3b82f6;\n text-decoration: underline;\n }\n\n .divider {\n opacity: 0.5;\n }\n\n .disclaimer-footer {\n padding: 0 24px 24px;\n }\n\n .disclaimer-agree-btn {\n width: 100%;\n padding: 12px;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: transform 0.1s, opacity 0.2s;\n }\n\n .disclaimer-agree-btn:hover {\n opacity: 0.9;\n }\n\n .disclaimer-agree-btn:active {\n transform: scale(0.98);\n }\n\n @keyframes modal-pop {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n }\n `})]})},rb=({isVisible:e,text:t,hint:n,tone:r="default",blockPageInteraction:o=false,onStop:i})=>{if(L(()=>{if(!e||!o)return;const t=e=>{e.isTrusted&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation());},n=["keydown","keyup","keypress","beforeinput","input","wheel","pointerdown","pointerup","mousedown","mouseup","click","dblclick","contextmenu","touchstart","touchmove","touchend","dragstart","drop"],r={capture:true,passive:false};return n.forEach(e=>{window.addEventListener(e,t,r);}),()=>{n.forEach(e=>{window.removeEventListener(e,t,r);});}},[o,e]),!e)return null;const a="export"===r,s={background:a?"color-mix(in srgb, var(--gh-bg, #ffffff) 94%, transparent)":"var(--gh-bg, #fff)",padding:a?"20px 24px":"24px 32px",borderRadius:a?"10px":"12px",display:"flex",flexDirection:"column",alignItems:"center",gap:a?"10px":"12px",boxShadow:a?"0 18px 48px rgba(15, 23, 42, 0.22), 0 0 0 1px color-mix(in srgb, var(--gh-primary, #4285f4) 18%, var(--gh-border, #d1d5db))":"0 4px 20px rgba(0, 0, 0, 0.15)",minWidth:a?"260px":"200px",maxWidth:"min(360px, calc(100vw - 40px))",border:a?"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 16%, var(--gh-border, #e5e7eb))":void 0},l=a?{width:"28px",height:"28px",border:"3px solid color-mix(in srgb, var(--gh-primary, #4285f4) 18%, transparent)",borderTopColor:"var(--gh-primary, #4285f4)",borderRadius:"999px",animation:"gh-loading-spin 0.8s linear infinite"}:{fontSize:"32px"},c={color:"var(--gh-text, #333)",fontSize:"14px",fontWeight:a?650:500,textAlign:"center"},d=De("div",{className:"gh-loading-mask "+(a?"gh-loading-mask--export":""),style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:a?"rgba(15, 23, 42, 0.34)":"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,pointerEvents:"auto",backdropFilter:a?"blur(2px)":void 0,WebkitBackdropFilter:a?"blur(2px)":void 0},role:"status","aria-live":"polite","aria-busy":"true",children:[a&&Re("style",{children:"\n @keyframes gh-loading-spin {\n to { transform: rotate(360deg); }\n }\n "}), De("div",{className:"gh-loading-content",style:s,children:[ Re("div",{className:"gh-loading-spinner",style:l,"aria-hidden":"true",children:a?null:"⏳"}), Re("div",{className:"gh-loading-text",style:c,children:t||le("loadingHistory")}), Re("div",{className:"gh-loading-hint",style:{color:"var(--gh-text-secondary, #9ca3af)",fontSize:"12px",textAlign:"center",lineHeight:1.5},children:n||le("loadingHint")}),i&&Re("button",{className:"gh-loading-stop-btn",style:{marginTop:"8px",padding:"8px 20px",background:"var(--gh-primary, #4285f4)",color:"white",border:"none",borderRadius:"6px",fontSize:"13px",cursor:"pointer"},onClick:i,children:le("stopLoading")})]})]});return document?.body?Kc(d,document.body):d},ob=({isOpen:e,onClose:t,tips:n,isStatic:r=false,onMouseEnter:o,onMouseLeave:i})=>{const a=$(null);return L(()=>{if(!e||r)return;const n=e=>{"Escape"===e.key&&(e.stopPropagation(),t());};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n);}},[e,r,t]),L(()=>{if(!e||r)return;const n=e=>{const n="function"==typeof e.composedPath?e.composedPath()[0]:e.target;a.current&&!a.current.contains(n)&&t();},o=window.setTimeout(()=>{document.addEventListener("click",n);},10);return ()=>{window.clearTimeout(o),document.removeEventListener("click",n);}},[e,r,t]),e?Re("div",{ref:a,role:"dialog","aria-label":le("featureTipsCategory"),className:"gh-magic-codex-popover "+(r?"static":"floating"),onPointerDown:e=>e.stopPropagation(),onPointerUp:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onMouseEnter:o,onMouseLeave:i,style:{position:r?"relative":"absolute",top:r?"auto":"36px",left:r?"auto":"-4px",width:r?"100%":"max-content",margin:r?"0 auto":"0",maxWidth:r?"100%":"calc(var(--panel-width, 320px) - 24px)",textAlign:"left",backgroundColor:r?"var(--gh-bg-secondary, #f9fafb)":"var(--gh-bg, #ffffff)",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.1)":"var(--gh-shadow-lg, 0 12px 32px -4px rgba(0,0,0,0.15))",zIndex:1e4,overflow:"hidden",display:"flex",flexDirection:"column",animation:"gh-popover-enter 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)"},children:Re("div",{className:"gh-hide-scrollbar",style:{padding:"10px",display:"flex",flexDirection:"column",gap:"2px",maxHeight:"420px",overflowY:"auto",userSelect:"none"},children:n.map((e,t)=>De("div",{className:"gh-interactive",style:{display:"flex",alignItems:"flex-start",gap:"12px",padding:"7px 12px",borderRadius:"10px",fontSize:"13px",color:"var(--gh-text-secondary, #4b5563)",lineHeight:"1.5",backgroundColor:r?"transparent":"var(--gh-bg, transparent)",transition:"background-color 0.2s ease, transform 0.1s ease"},children:[ Re("div",{style:{fontSize:"18px",display:"flex",alignItems:"center",justifyContent:"center",width:"28px",height:"28px",flexShrink:0,borderRadius:"8px",backgroundColor:"var(--gh-bg-tertiary, rgba(0,0,0,0.04))",boxShadow:"inset 0 1px 0 rgba(255,255,255,0.2)"},children:e.icon}), Re("div",{style:{flex:1,display:"flex",flexDirection:"column",alignSelf:"center",gap:"2px"},children:Re("span",{style:{whiteSpace:"normal",wordBreak:"break-word",color:"var(--gh-text, #374151)"},children:e.text})})]},t))})}):null};function ib(e,t,n){const r=le(e,{[t]:"___SC___"}).split("___SC___");return 1===r.length?r[0]:De("span",{style:{display:"inline"},children:[r[0], Re("span",{style:{fontFamily:"monospace",background:"var(--gh-bg-secondary, #f3f4f6)",border:"1px solid var(--gh-border, #e5e7eb)",padding:"2px 6px",borderRadius:"4px",fontSize:"11px",fontWeight:500,color:"var(--gh-text, #1f2937)",display:"inline-flex",alignItems:"center",margin:"0 4px",verticalAlign:"bottom"},children:n}),r[1]]})}function ab(e,t,n){const r=e??rr,o=e=>{const o=r[e];if(void 0===o){const r=rr[e];return r?dr(r,t):n}return o?dr(o,t):n},i=(e=>{const n=r[e];if(void 0===n){const n=rr[e];return n?dr(n,t):null}return n?dr(n,t):null})("togglePanelMode");return [{icon:"👻",text:ib("tip1","modifier",t?"⌘ Cmd":"Ctrl")},{icon:"↔️",text:i?ib("featureTip-panel-mode-toggle-path","shortcut",i):le("featureTip-panel-mode-toggle-path-dblclick")},{icon:"🔍",text:ib("tip4","shortcut",o("openGlobalSearch"))},{icon:"🚀",text:ib("tip3","shortcut",o("showShortcuts"))},{icon:"📋",text:ib("tip5","shortcut",o("copyLatestReply"))},{icon:"🧭",text:ib("tip6","shortcut",o("prevHeading")+"/"+o("nextHeading"))}]}const sb=10;const lb=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:Re("path",{d:"M163.84 619.52l-57.6 219.52a38.4 38.4 0 0 0 8.96 35.84 37.76 37.76 0 0 0 25.6 10.24h14.72L355.84 832h6.4l551.68-576a92.8 92.8 0 0 0 24.32-74.24 112.64 112.64 0 0 0-32-78.08l-52.48-50.56a106.24 106.24 0 0 0-74.88-32.64 88.96 88.96 0 0 0-64 26.24l-550.4 571.52z m694.4-424.32l-54.4 56.32-88.96-93.44 53.12-56.96a25.6 25.6 0 0 1 34.56 0l53.12 53.76a30.72 30.72 0 0 1 8.32 20.48 22.4 22.4 0 0 1-5.76 16zM261.76 628.48l394.88-411.52 89.6 94.08-394.88 410.88z m-73.6 167.68l28.8-109.44L293.76 768z m693.12-376.32M938.88 1001.6h-832a35.2 35.2 0 0 1-35.2-35.2 34.56 34.56 0 0 1 35.2-35.2h832a35.2 35.2 0 0 1 35.2 35.2 35.2 35.2 0 0 1-35.2 35.2z",fill:t})});let cb=false;const db=({anchorEl:e,anchorPoint:t,onClose:n,children:r})=>{const o=$(null),[i,a]=_(null);if(L(()=>{if((()=>{if(cb)return;const e=document.createElement("style");e.id="gh-menu-styles",e.textContent="\n .conversations-folder-menu {\n background: var(--gh-bg, white);\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 6px;\n box-shadow: var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15));\n z-index: 10000000;\n padding: 3px;\n min-width: 80px;\n }\n .conversations-folder-menu button {\n display: block;\n width: 100%;\n padding: 6px 10px;\n border: none;\n background: none;\n text-align: left;\n font-size: 12px;\n color: var(--gh-text, #374151);\n cursor: pointer;\n border-radius: 4px;\n white-space: nowrap;\n }\n .conversations-folder-menu button:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n",document.head.appendChild(e),cb=true;})(),!e&&!t)return;const r=t=>{const r=t.composedPath(),i=o.current&&r.includes(o.current),a=!!e&&r.includes(e);i||a||n();},i=setTimeout(()=>{document.addEventListener("click",r,true);},0);return ()=>{clearTimeout(i),document.removeEventListener("click",r,true);}},[e,t,n]),L(()=>{if(!e&&!t||!o.current)return;const n=o.current.getBoundingClientRect(),r=window.innerWidth,i=window.innerHeight,s=n.width||150,l=n.height||200;let c=t?.left??10,d=t?.top??10;if(!t&&e){const t=e.getBoundingClientRect();c=t.left,d=t.bottom+4;}if(c+s>r-10)if(t)c=r-s-10;else if(e){c=e.getBoundingClientRect().right-s;}if(c<10&&(c=10),d+l>i-10)if(t)d=i-l-10;else if(e){d=e.getBoundingClientRect().top-l-4;}d<10&&(d=10),a({left:c,top:d});},[e,t]),!e&&!t)return null;const s=Re("div",{ref:o,className:"conversations-folder-menu",...ns,style:{position:"fixed",top:i?`${i.top}px`:"-9999px",left:i?`${i.left}px`:"-9999px",zIndex:2147483647,pointerEvents:"auto"},children:r});return Kc(s,document.body)},ub=({onClick:e,danger:t,children:n})=>Re("button",{onClick:e,style:t?{color:"var(--gh-text-danger, #ef4444)"}:void 0,children:n}),hb=({folder:e,anchorEl:t,onClose:n,onRename:r,onDelete:o})=>De(db,{anchorEl:t,onClose:n,children:[ Re(ub,{onClick:()=>{n(),r();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsRename")}), Re(lb,{size:13})]})}), Re(ub,{danger:true,onClick:()=>{n(),o();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsDelete")}), Re(Ft,{size:13})]})})]}),gb=({conversation:e,anchorEl:t,anchorPoint:n,onClose:r,onOpenInNewTab:o,onRename:i,onTogglePin:a,onSetTags:s,onMoveTo:l,onExport:c,onDelete:d})=>De(db,{anchorEl:t,anchorPoint:n,onClose:r,children:[ Re(ub,{onClick:()=>{r(),o();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsOpenInNewTab")}), Re(on,{size:13})]})}), Re(ub,{onClick:()=>{r(),i();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsRename")}), Re(lb,{size:13})]})}), Re(ub,{onClick:()=>{r(),a();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:e.pinned?le("conversationsUnpin"):le("conversationsPin")}), Re(Ut,{size:13,filled:e.pinned})]})}), Re(ub,{onClick:()=>{r(),s();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsSetTags")}), Re(qt,{size:13})]})}), Re(ub,{onClick:()=>{r(),l();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsMoveTo")}), Re(Oe,{size:13})]})}), Re(ub,{onClick:()=>{r(),c();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("export")}), Re(Ze,{size:13})]})}), Re(ub,{danger:true,onClick:()=>{r(),d();},children:De("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Re("span",{children:le("conversationsDelete")}), Re(Ft,{size:13})]})})]}),pb=({anchorEl:e,anchorPoint:t,onClose:n,onExportMarkdown:r,onExportJSON:o,onExportTXT:i})=>De(db,{anchorEl:e,anchorPoint:t,onClose:n,children:[ Re(ub,{onClick:()=>{n(),r();},children:De("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Re(jt,{size:14}), Re("span",{children:le("exportToMarkdown")})]})}), Re(ub,{onClick:()=>{n(),o();},children:De("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Re(Gt,{size:14}), Re("span",{children:le("exportToJSON")})]})}), Re(ub,{onClick:()=>{n(),i();},children:De("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Re(Vt,{size:14}), Re("span",{children:le("exportToTXT")})]})})]});e(".gh-panel-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-folder-item.expanded{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important;border-bottom:none!important}.conversations-list{width:100%!important;box-sizing:border-box!important;margin:0!important;border-top-left-radius:0!important;border-top-right-radius:0!important;border-top:none!important}.conversations-toolbar-btn{background:transparent!important;border:1px solid transparent!important;box-shadow:none!important;color:var(--gh-text-secondary, #6b7280)!important;border-radius:6px!important;transition:all .2s ease!important;min-width:28px!important;height:28px!important;margin:0!important;padding:0!important;cursor:pointer;display:flex;align-items:center;justify-content:center}.conversations-toolbar-btn:hover{background:#7f7f7f26!important;color:var(--gh-text, #374151)!important}.conversations-toolbar-btn.active{background:var(--gh-primary, #3b82f6)!important;color:#fff!important;border-color:var(--gh-primary, #3b82f6)!important}.conversations-toolbar-btn svg{fill:currentColor!important;width:16px!important;height:16px!important}.conversations-content{display:flex;flex-direction:column;flex:1;min-height:200px;overflow-x:hidden;overflow-y:auto}.conversations-content.is-dragging-any{-webkit-user-select:none;user-select:none}.conversations-content.is-dragging-any .conversations-folder-item,.conversations-content.is-dragging-any .conversations-item,.conversations-folder-item:active,.conversations-item:active{cursor:grabbing}.conversations-toolbar{display:flex;gap:6px;padding:8px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);flex-shrink:0;background:var(--gh-bg, #ffffff)}.conversations-toolbar-btn{padding:5px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center;min-width:32px;height:32px;flex-shrink:0}.conversations-toolbar-btn svg{width:16px;height:16px}.conversations-toolbar-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-text-secondary, #9ca3af)}.conversations-toolbar-btn.batch-mode.active{background:var(--gh-border-active);color:#fff;border-color:var(--gh-border-active)}.conversations-toolbar-btn:disabled{opacity:.6;cursor:wait}.conversations-folder-select-dropdown{width:100%}.conversations-folder-select{padding:4px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;min-width:80px;height:32px;width:100%;line-height:1.35;font-family:inherit;appearance:none;-webkit-appearance:none}.conversations-folder-select-icon{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;width:16px;min-width:16px;height:18px;font-size:15px;line-height:1}.conversations-folder-select:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-select:focus{outline:none;border-color:var(--gh-border-active)}.conversations-folder-select:disabled{opacity:.6;cursor:not-allowed}.conversations-folder-select-menu{scrollbar-width:thin}.conversations-folder-select-option{font-family:inherit}.conversations-folder-list{flex:1;overflow-y:auto;padding:8px;scrollbar-width:none;-ms-overflow-style:none}.conversations-folder-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-content{scrollbar-width:none;-ms-overflow-style:none}.conversations-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-unsupported-mask{position:absolute;inset:0;z-index:12;display:flex;align-items:center;justify-content:center;padding:16px;background:linear-gradient(180deg,#f8fafceb,#f8fafcd1);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);pointer-events:all}.conversations-unsupported-card{width:100%;max-width:280px;border-radius:16px;padding:16px 18px 18px;background:var(--gh-bg, #ffffff);border:1px solid rgba(148,163,184,.25);box-shadow:0 16px 32px #0f172a1f;text-align:center;color:var(--gh-text, #374151)}.conversations-unsupported-icon{width:44px;height:44px;margin:0 auto 10px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:20px;color:#6a3a00;background:linear-gradient(135deg,#ffd29a,#ffb86b);box-shadow:0 8px 18px #ffab5859}.conversations-unsupported-title{font-size:14px;font-weight:600;margin-bottom:6px}.conversations-unsupported-desc{font-size:12px;color:var(--gh-text-secondary, #6b7280);line-height:1.4}:host([data-theme=\"dark\"]) .conversations-unsupported-mask,.gh-root[data-theme=dark] .conversations-unsupported-mask,body[data-gh-mode=dark] .conversations-unsupported-mask,html[data-theme=dark] .conversations-unsupported-mask{background:linear-gradient(180deg,#0a0a0aeb,#0a0a0adb)}:host([data-theme=\"dark\"]) .conversations-unsupported-card,.gh-root[data-theme=dark] .conversations-unsupported-card,body[data-gh-mode=dark] .conversations-unsupported-card,html[data-theme=dark] .conversations-unsupported-card{background:#1b1b1b;border:1px solid rgba(255,255,255,.08);box-shadow:0 18px 36px #0000008c;color:var(--gh-text, #e3e3e3)}:host([data-theme=\"dark\"]) .conversations-unsupported-icon,.gh-root[data-theme=dark] .conversations-unsupported-icon,body[data-gh-mode=dark] .conversations-unsupported-icon,html[data-theme=dark] .conversations-unsupported-icon{color:#f7d6a8;background:linear-gradient(135deg,#6c420c,#c37a24);box-shadow:0 10px 20px #00000080}.conversations-folder-item{display:flex;align-items:center;justify-content:space-between;position:relative;padding:10px 12px;border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);cursor:pointer;transition:background-color .2s,border .2s,box-shadow .2s,outline .2s,transform .2s;flex-wrap:wrap}.conversations-folder-item+.conversations-folder-item,.conversations-list+.conversations-folder-item{margin-top:4px}.conversations-folder-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-item.default{background:var(--gh-folder-bg-default)}.conversations-folder-item.expanded{border:2px solid var(--gh-border-active);box-shadow:0 2px 8px var(--gh-shadow-sm);border-radius:8px 8px 0 0}.conversations-folder-info{display:flex;align-items:center;gap:8px;flex:1;min-width:0;position:relative}.conversations-folder-icon{font-size:18px;width:24px;height:24px;display:flex;align-items:center;justify-content:center;line-height:1;flex-shrink:0}.conversations-folder-name{font-size:14px;font-weight:500;color:var(--gh-text, #1f2937);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-user-select:none;user-select:none}.conversations-folder-count{font-size:12px;color:var(--gh-text-secondary, #6b7280);flex-shrink:0;-webkit-user-select:none;user-select:none}.conversations-folder-menu-btn{width:24px;height:24px;border:none;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;border-radius:4px;font-size:14px}.conversations-folder-menu-btn:hover{background:var(--gh-border, #e5e7eb)}.conversations-folder-controls{display:flex;align-items:center;gap:4px;flex-shrink:0}.conversations-folder-item.is-dragging{opacity:.74;background:color-mix(in srgb,var(--gh-primary, #4285f4) 9%,var(--gh-bg, #fff))!important;outline:1px dashed var(--gh-primary, #4285f4);outline-offset:-2px;box-shadow:0 8px 18px #4285f42e,inset 0 0 0 1px color-mix(in srgb,var(--gh-primary, #4285f4) 18%,transparent);transform:scale(.985)}.conversations-folder-item.is-drag-over{background:color-mix(in srgb,var(--gh-primary, #4285f4) 8%,var(--gh-bg, #fff))!important;outline:2px dashed color-mix(in srgb,var(--gh-primary, #4285f4) 70%,transparent);outline-offset:-3px;box-shadow:inset 0 3px 0 var(--gh-primary, #4285f4),0 6px 16px #4285f429;transform:translateY(-1px)}.conversations-folder-item.is-drag-over:after{content:\"\";position:absolute;top:-3px;left:50%;width:36px;height:5px;border-radius:999px;background:var(--gh-primary, #4285f4);box-shadow:0 2px 8px #4285f44d;pointer-events:none;transform:translate(-50%)}.conversations-folder-item.is-drag-over-conv{background:color-mix(in srgb,var(--gh-primary, #4285f4) 10%,var(--gh-bg, #fff))!important;outline:2px dashed var(--gh-primary, #4285f4)!important;outline-offset:-3px;box-shadow:0 0 0 3px color-mix(in srgb,var(--gh-primary, #4285f4) 12%,transparent),0 8px 18px #4285f42e;transform:translateY(-1px)}.conversations-folder-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:100px}.conversations-folder-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-folder-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-empty{text-align:center;padding:40px 20px;color:var(--gh-text-secondary, #9ca3af);font-size:14px}.conversations-search-bar{padding:6px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-search-wrapper{display:flex;align-items:center;gap:0;position:relative}.conversations-search-wrapper.has-filter .conversations-tag-search-btn{border-radius:0;border-right:none}.conversations-search-input-group{flex:1;position:relative;height:32px;min-width:0}.conversations-search-input{width:100%;height:100%;padding:0 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px 0 0 8px;font-size:14px;box-sizing:border-box;transition:all .2s;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-search-input:focus{outline:none;border-color:var(--gh-border-active);z-index:1;position:relative}.conversations-pin-filter-btn{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-pin-filter-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-pin-filter-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-result-bar{text-align:center;padding:6px;color:var(--gh-border-active);font-size:13px;background:var(--gh-folder-bg-default);border-radius:4px;margin-top:8px;display:none}.conversations-result-bar.visible{display:block}.conversations-tag{display:inline-flex;align-items:center;padding:2px 6px;border-radius:4px;font-size:11px;margin:0;color:#fff;background-color:var(--gh-text-secondary, #9ca3af);line-height:1.2;max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;flex-shrink:0}.conversations-tag-list{display:flex;align-items:center;gap:4px;border:none;padding:0;margin:0;flex-shrink:0;min-width:0;max-width:52%;overflow:hidden}.conversations-tag-list:empty{display:none}.conversations-tag-more{color:var(--gh-text-secondary, #6b7280);background:var(--gh-bg-secondary, #f3f4f6);border:1px solid var(--gh-border, #e5e7eb)}.conversations-hidden-tags-tooltip{display:flex;flex-direction:column;gap:6px;min-width:110px}.conversations-hidden-tag-item{display:flex;align-items:center;gap:6px;font-size:12px;line-height:1.25}.conversations-hidden-tag-dot{width:8px;height:8px;border-radius:999px;flex-shrink:0}.conversations-tag-search-btn{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-tag-search-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-tag-search-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-tag-search-btn.empty{opacity:.5}.conversations-search-clear{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:18px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0 8px 8px 0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s;-webkit-user-select:none;user-select:none}.conversations-search-clear:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #ef4444)}.conversations-search-clear.disabled{opacity:.3;cursor:default;background:var(--gh-bg-secondary, #f9fafb);pointer-events:none}.conversations-tag-filter-menu{position:absolute;top:calc(100% + 4px);right:0;width:200px;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;display:flex;flex-direction:column;overflow:hidden;animation:fadeIn .2s}.conversations-tag-filter-list{overflow-y:auto;flex:1;padding:4px;display:flex;flex-direction:column;gap:2px}.conversations-tag-filter-footer{padding:4px;border-top:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px;cursor:pointer;border-radius:6px;font-size:13px;color:var(--gh-text, #374151);width:100%;box-sizing:border-box;overflow:hidden}.conversations-tag-filter-item span:not(.conversations-tag-dot){white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}.conversations-tag-filter-item.selected{background:var(--gh-folder-bg-default);color:var(--gh-primary, #3b82f6);font-weight:500}.conversations-tag-filter-item.selected:after{content:\"✓\";margin-left:auto;font-size:14px;font-weight:700}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;display:inline-block;flex-shrink:0;border:1px solid rgba(0,0,0,.05)}.conversations-tag-filter-divider{height:1px;background:var(--gh-border, #e5e7eb);margin:4px 0;flex-shrink:0}.conversations-tag-filter-action{color:var(--gh-border-active);font-weight:500;justify-content:center}.conversations-tag-manager-list{max-height:250px;overflow-y:auto;border:1px solid var(--gh-border, #e5e7eb);border-radius:4px;margin-bottom:12px;padding:4px}.conversations-tag-manager-item{display:flex;align-items:center;justify-content:space-between;padding:8px;border-bottom:1px solid var(--gh-hover, #f3f4f6)}.conversations-tag-manager-item:last-child{border-bottom:none}.conversations-tag-manager-item:hover{background:var(--gh-bg-secondary, #f9fafb)}.conversations-tag-preview{padding:2px 8px;border-radius:4px;font-size:12px;color:#fff;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;display:inline-block}.conversations-tag-actions{display:flex;gap:4px;flex-shrink:0}.conversations-tag-btn{width:24px;height:24px;border:none;background:transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;color:var(--gh-text-tertiary, #9ca3af);border-radius:4px;transition:all .2s}.conversations-tag-btn:hover{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #ef4444)}.conversations-tag-btn.edit:hover{background:var(--gh-folder-bg-default, #e0f2fe);color:var(--gh-primary, #3b82f6)}.conversations-color-picker{display:grid;grid-template-columns:repeat(10,1fr);gap:6px;margin:12px 0}.conversations-color-item{width:24px;height:24px;border-radius:4px;cursor:pointer;border:2px solid transparent;transition:transform .1s}.conversations-color-item:hover{transform:scale(1.1)}.conversations-color-item.selected{border-color:var(--gh-text, #374151);transform:scale(1.1);box-shadow:0 2px 4px #0003}.conversations-list{width:calc(100% - 8px);margin-left:4px;margin-right:4px;padding:8px;background:var(--gh-bg-secondary);border:2px solid var(--gh-border-active);border-top:none;border-radius:0 0 8px 8px;margin-top:-4px;max-height:300px;overflow-y:auto;overflow-x:hidden;scrollbar-width:none;-ms-overflow-style:none}.conversations-list::-webkit-scrollbar{display:none}.conversations-list-empty{padding:12px;color:var(--gh-text-secondary, #9ca3af);font-size:13px;text-align:center}.conversations-item{display:flex;align-items:center;padding:8px 34px 8px 12px;margin-bottom:4px;border-radius:6px;background:var(--gh-bg, white);cursor:pointer;transition:background-color .2s;gap:8px;position:relative}.conversations-item.is-dragging{opacity:.5}.conversations-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item:before{content:\"\";position:absolute;left:0;top:50%;transform:translateY(-50%) scaleY(0);width:4px;height:80%;background-color:var(--gh-primary, #428cf1);border-radius:0 4px 4px 0;transition:transform .2s}.conversations-item:hover:before{transform:translateY(-50%) scaleY(1)}.conversations-item-title{display:block;font-size:14px;color:var(--gh-text, #374151);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.35}.conversations-item-main{flex:1;min-width:0}.conversations-item-headline{display:flex;align-items:center;gap:6px;min-width:0}.conversations-item-meta{display:flex;align-items:center;gap:6px;position:absolute;top:50%;right:8px;transform:translateY(-50%)}.conversations-item-time{display:none}.conversations-item-menu-btn{width:26px;height:26px;border:none;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;border-radius:6px;font-size:12px;opacity:0;pointer-events:none;transform:translate(4px);transition:opacity .18s ease,transform .18s ease,background-color .2s,color .2s;flex-shrink:0;display:flex;align-items:center;justify-content:center}.conversations-folder-checkbox,.conversations-item-checkbox{appearance:none;-webkit-appearance:none;width:16px;height:16px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:4px;background-color:var(--gh-bg, #ffffff);cursor:pointer;position:relative;margin:0;padding:0;display:inline-flex;align-items:center;justify-content:center;transition:all .2s}.conversations-folder-checkbox:checked,.conversations-item-checkbox:checked{background-color:var(--gh-primary, #4285f4);border-color:var(--gh-primary, #4285f4)}.conversations-folder-checkbox:checked:after,.conversations-item-checkbox:checked:after{content:\"\";width:10px;height:10px;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E\");background-size:contain;background-repeat:no-repeat;background-position:center;display:block}.conversations-folder-checkbox:hover,.conversations-item-checkbox:hover{border-color:var(--gh-primary, #4285f4)}.conversations-item:hover .conversations-item-menu-btn,.conversations-item:focus-within .conversations-item-menu-btn{opacity:1;pointer-events:auto;transform:translate(0);background:var(--gh-active-bg, rgba(0, 0, 0, .07));color:var(--gh-text-secondary, #6b7280)}.conversations-item-menu-btn:hover{background:var(--gh-hover, rgba(0, 0, 0, .12))!important;color:var(--gh-primary, #4285f4)!important}.conversations-content.is-narrow .conversations-item{padding-right:34px}.conversations-content.is-narrow .conversations-item-title{font-size:13px}.conversations-content.is-narrow .conversations-tag{max-width:72px}.conversations-content.is-narrow .conversations-tag-list{max-width:46%}@media(hover:none){.conversations-item-menu-btn{opacity:.72;pointer-events:auto;transform:none}}.conversations-item-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:120px}.conversations-item-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-item-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item-menu button.danger{color:var(--gh-text-danger, #dc2626)}.conversations-item-menu button.danger:hover{background:var(--gh-bg-danger, #fef2f2)}.conversations-item.locate-highlight{background:var(--gh-outline-locate-bg)!important;border:2px solid var(--gh-outline-locate-border)!important;border-radius:6px;box-shadow:inset 0 0 8px var(--gh-outline-locate-shadow);animation:conversationsLocatePulse .6s ease-in-out 2}@keyframes conversationsLocatePulse{0%,to{transform:scale(1)}50%{transform:scale(1.01)}}.conversations-folder-checkbox{margin-right:8px;width:16px;height:16px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-item-checkbox{width:16px;height:16px;margin-right:8px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-batch-bar{position:sticky;bottom:0;left:0;right:0;background:var(--gh-bg, white);padding:8px 12px;display:flex;align-items:center;justify-content:space-between;border-radius:8px;margin-top:8px;border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 -2px 10px #0000000d}.conversations-batch-info{color:var(--gh-text, #374151);font-size:13px;font-weight:500}.conversations-batch-btns{display:flex;gap:8px}.conversations-batch-btn{padding:4px 10px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;font-size:12px;cursor:pointer;transition:all .2s;background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-batch-btn:hover{background:var(--gh-border, #e5e7eb);border-color:var(--gh-text-tertiary, #9ca3af)}.conversations-batch-btn.danger{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #dc2626);border-color:var(--gh-bg-danger-hover, #fecaca)}.conversations-batch-btn.danger:hover{background:var(--gh-bg-danger-hover, #fecaca);border-color:var(--gh-text-danger, #f87171)}.conversations-batch-btn.cancel{background:transparent;border:none;color:var(--gh-text-secondary, #6b7280)}.conversations-batch-btn.cancel:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151);border:none}.conversations-dialog-overlay{position:fixed;inset:0;background:#00000080;z-index:1000003;display:flex;align-items:center;justify-content:center}.conversations-dialog{background:var(--gh-bg, white);border-radius:12px;padding:20px;min-width:320px;box-shadow:0 10px 40px #0003}.conversations-dialog-title{font-size:16px;font-weight:600;color:var(--gh-text, #1f2937);margin-bottom:16px}.conversations-dialog-message{font-size:14px;color:var(--gh-badge-text, #4b5563);margin-bottom:20px;line-height:1.5;white-space:pre-line}.conversations-dialog-section{margin-bottom:16px}.conversations-dialog-section label{display:block;font-size:13px;color:var(--gh-text-secondary, #6b7280);margin-bottom:8px}.conversations-dialog-input{width:100%;padding:10px 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px;font-size:14px;box-sizing:border-box;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-dialog-input:focus{outline:none;border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f41a}.conversations-dialog-buttons{display:flex;justify-content:flex-end;gap:8px;margin-top:20px}.conversations-folder-select-list{max-height:250px;overflow-y:auto;margin:12px 0}.conversations-folder-select-item{padding:12px 16px;border-radius:8px;cursor:pointer;transition:all .2s;font-size:14px}.conversations-folder-select-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-emoji-picker{display:flex;flex-wrap:wrap;gap:4px}.conversations-emoji-btn{width:36px;height:36px;border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);font-size:18px;cursor:pointer;transition:all .2s}.conversations-emoji-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-input-border, #d1d5db)}.conversations-emoji-btn.selected{background:var(--gh-selected-gradient, #e0e7ff);border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f433}.conversations-highlight{background:#ffd50066;padding:0 2px;border-radius:2px}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.conversations-tag-filter-list,.conversations-tag-manager-list{max-height:200px;overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none}.conversations-tag-filter-list::-webkit-scrollbar,.conversations-tag-manager-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-tag-filter-menu{position:absolute;top:100%;right:0;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:150px;max-height:250px;overflow:hidden}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:pointer;font-size:13px;color:var(--gh-text, #374151)}.conversations-tag-filter-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-tag-filter-item.selected{background:#3b82f61a}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}.conversations-tag-filter-footer{border-top:1px solid var(--gh-border, #e5e7eb)}.conversations-tag-filter-action{color:var(--gh-primary, #3b82f6)!important}");const mb=30,fb=()=>{const e=le("conversationsInbox");return "conversationsInbox"===e?"Inbox":e},bb=e=>{if("inbox"===e.id)return fb();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},yb=(e,t)=>{if(!t)return e;return e.split(new RegExp(`(${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`,"gi")).map((e,n)=>e.toLowerCase()===t.toLowerCase()?Re("span",{className:"conversations-highlight",children:e},n):e)},vb=({manager:e,onInteractionStateChange:t})=>{const n={[po]:"ChatGLM",[To]:"Z.ai",[So]:"Qianwen",[Co]:"Qwen Studio",[vo]:"ima"},{settings:r}=Mi(),[o,a]=_([]),[s,l]=_({}),[c,d]=_([]),[u,h]=_("inbox"),[g,p]=_(null),[m,f]=_(false),[b,y]=_(new Set),[v,x]=_(false),[w,S]=_(false),[C,k]=_(""),[T,A]=_(false),[M,I]=_(new Set),[N,R]=_(null),[D,P]=_(false),[B,O]=_(false),[z,F]=_(false),U=de(),H=e.siteAdapter?.getSiteId?.(),W=!(!H||!n[H]),j=H?n[H]||H:"",G=le("conversationsUnsupportedTitle",{site:j}),V=le("conversationsUnsupportedDesc"),Q=le("conversationsUnsupportedSync",{site:j}),K=W,[Z,Y]=_(null),[X,J]=_(null),[ee,te]=_(null),[ne,re]=_(null),[oe,ie]=_(null),[ae,se]=_(null),ce=$(null),ue=$(null),he=$(null),ge=$(null),pe=$(null),me=$(null),fe=$(null);L(()=>{const e=he.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>{F(e.clientWidth<=340);};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);const be=E(async()=>{a([...e.getFolders()]),l({...e.getAllConversations()}),d([...e.getTags()]),h(e.getLastUsedFolderId());},[e]);L(()=>{be();},[be]),L(()=>{const t=e.onDataChange(()=>{be();});return ()=>t()},[e,be]);const ye=E(e=>{if(!e&&!T&&0===M.size)return void R(null);const t=new Set,n=new Set,r=new Map,i=e.toLowerCase();o.forEach(n=>{e&&bb(n).toLowerCase().includes(i)&&t.add(n.id);}),Object.values(s).forEach(t=>{let o=true;if(e&&!t.title.toLowerCase().includes(i)&&(o=false),T&&!t.pinned&&(o=false),M.size>0){const e=t.tagIds?.some(e=>M.has(e));e||(o=false);}o&&(n.add(t.id),r.set(t.id,t.folderId));}),R({folderMatches:t,conversationMatches:n,conversationFolderMap:r,totalCount:n.size});},[o,s,T,M]);L(()=>{ye(C);},[T,M,ye,C]),L(()=>{if(!D)return;const e=e=>{const t=e.composedPath(),n=me.current&&t.includes(me.current),r=fe.current&&t.includes(fe.current);n||r||P(false);},t=setTimeout(()=>{document.addEventListener("click",e,true);},0);return ()=>{clearTimeout(t),document.removeEventListener("click",e,true);}},[D]),L(()=>{const e=!!(X||Z||D||B||w);t?.(e);},[X,Z,D,B,w,t]);const ve=q(()=>{const e=new Map;return c.forEach(t=>e.set(t.id,t)),e},[c]),xe=q(()=>{const t=e.getSidebarConversationOrder(),n=new Map;for(let e=0;eN.conversationMatches.has(e.id)):a;t.sort((e,t)=>{if(e.pinned&&!t.pinned)return -1;if(!e.pinned&&t.pinned)return 1;const r=n.get(e.id)??-1,o=n.get(t.id)??-1;return -1===r&&-1===o?(t.updatedAt||0)-(e.updatedAt||0):-1===r?1:-1===o?-1:r-o}),i.set(e,t);}return i},[s,N,e]),we=$(xe);we.current=xe;const Se=e=>xe.get(e)||[],[Ce,ke]=_({}),Te=$(new Map),Ee=E(async()=>{if(W)Pi(Q);else {x(true);try{const t=!1!==await(e.siteAdapter?.loadAllConversations?.()),n=e.siteAdapter?.getConversationList?.()?.length||0,{newCount:r,updatedCount:o,deletedCount:i}=await e.syncConversations(u,!1,{syncDeleted:t});be(),Pi(0===n?le("conversationsSyncNoSidebarItems"):le("conversationsSyncResult").replace("{scanned}",String(n)).replace("{added}",String(r)).replace("{updated}",String(o)).replace("{deleted}",String(i)));}finally{x(false);}}},[W,Q,e,u,be]),Ae=E(()=>{if(e.siteAdapter?.isSharePage?.()||e.siteAdapter?.isNewConversation?.())return;const t=e.siteAdapter?.getSessionId?.();if(!t||"default"===t||"app"===t)return;const n=e.getConversation(t);if(!n)return void Ee();p(n.folderId);const r=(xe.get(n.folderId)||[]).findIndex(e=>e.id===t);if(r>=0){const e=r+1;ke(t=>({...t,[n.folderId]:Math.max(t[n.folderId]||mb,e)}));}setTimeout(()=>{const e=he.current;if(!e)return;const n=e.querySelector(`.conversations-item[data-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("locate-highlight"),setTimeout(()=>n.classList.remove("locate-highlight"),2e3));},100);},[e,Ee,xe]);L(()=>{const e=()=>{window.__ophelPendingLocateConversation=false,Ae();};return window.__ophelPendingLocateConversation&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateConversation",e),()=>{window.removeEventListener("ophel:locateConversation",e);}},[Ae]),L(()=>{const e=()=>{Ee();};return window.addEventListener("ophel:refreshConversations",e),()=>{window.removeEventListener("ophel:refreshConversations",e);}},[Ee]);const Me=()=>{y(new Set),f(false);},Ie=C||T||M.size>0,Le=$(null);L(()=>{g!==Le.current&&(Le.current=g,g&&ke(e=>({...e,[g]:Math.max(e[g]??0,mb)})));},[g]),L(()=>{if(N){const e=new Set(N.conversationFolderMap.values());ke(t=>{const n={...t};for(const r of e)r in n||(n[r]=mb);return n});}},[N]);const Pe=$(null);L(()=>{if("undefined"==typeof IntersectionObserver)return;const e=new IntersectionObserver(t=>{for(const n of t)if(n.isIntersecting){const t=n.target.dataset.folderId;if(t){const r=we.current.get(t)?.length||0;ke(e=>{const n=e[t]||mb,o=Math.min(n+mb,r);return o===n?e:{...e,[t]:o}}),e.unobserve(n.target);}}},{rootMargin:"100px"});Pe.current=e;for(const[,t]of Te.current)t&&e.observe(t);return ()=>e.disconnect()},[]);const qe=E(t=>{m?y(e=>{const n=new Set(e);return n.has(t.id)?n.delete(t.id):n.add(t.id),n}):e.siteAdapter?.navigateToConversation(t.id,t.url);},[m,e]),Be=E(e=>{const t=(e=>{const t=(e.url||"").trim();if(!t)return null;try{const e=new URL(t,window.location.origin);return "http:"!==e.protocol&&"https:"!==e.protocol?null:e.toString()}catch{return null}})(e);t?$i.openTab(t):Pi(le("operationFailed"));},[]),_e=e=>{const t=Se(e);return t.length>0&&t.every(e=>b.has(e.id))},ze=e=>{if(!N)return true;const t=N.folderMatches.has(e.id),n=Array.from(N.conversationFolderMap.values()).includes(e.id);return t||n},Fe=q(()=>o.map(e=>{const t=bb(e),n=`${e.icon?`${e.icon} `:""}${t}`.trim();return {value:e.id,title:n,label:De(Ne,{children:[e.icon&&Re("span",{className:"conversations-folder-select-icon",children:e.icon}), Re("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}}),[o,U]); return De(Ne,{children:[ Re(rb,{isVisible:w,text:`${le("delete")}...`}), De("div",{ref:he,className:`conversations-content ${z?"is-narrow":""} ${oe||ee?"is-dragging-any":""}`,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[K&&Re("div",{className:"conversations-unsupported-mask","aria-hidden":"true",children:De("div",{className:"conversations-unsupported-card",children:[ Re("div",{className:"conversations-unsupported-icon",children:"!"}), Re("div",{className:"conversations-unsupported-title",children:G}), Re("div",{className:"conversations-unsupported-desc",children:V})]})}), De("div",{className:"conversations-toolbar",children:[ Re(od,{content:le("conversationsSelectFolder"),triggerStyle:{flex:1,minWidth:0},children:Re(Wf,{className:"conversations-folder-select-dropdown",buttonClassName:"conversations-folder-select",menuClassName:"conversations-folder-select-menu",optionClassName:"conversations-folder-select-option",options:Fe,value:u,ariaLabel:le("conversationsSelectFolder"),onOpenChange:O,onChange:t=>{h(t),e.setLastUsedFolder(t);}})}), Re(od,{content:le("conversationsSync"),children:Re("button",{className:"conversations-toolbar-btn sync",disabled:v||W,onClick:Ee,children:Re(v?St:Ct,{size:18})})}), Re(od,{content:le("conversationsLocate"),children:Re("button",{className:"conversations-toolbar-btn locate",onClick:Ae,children:Re(nt,{size:18})})}), Re(od,{content:le("conversationsBatchMode"),children:Re("button",{className:"conversations-toolbar-btn batch-mode "+(m?"active":""),onClick:()=>{m&&y(new Set),f(!m);},children:Re(xt,{size:18})})}), Re(od,{content:le("conversationsAddFolder"),children:Re("button",{className:"conversations-toolbar-btn add-folder",onClick:()=>{t?.(true),Y({type:"folder"});},children:Re(wt,{size:18})})})]}), De("div",{className:"conversations-search-bar",children:[ De("div",{className:"conversations-search-wrapper",style:{position:"relative"},children:[ Re("div",{className:"conversations-search-input-group",children:Re("input",{ref:ge,type:"text",className:"conversations-search-input",placeholder:le("conversationsSearchPlaceholder"),value:C,onChange:e=>{return t=e.target.value,k(t),pe.current&&clearTimeout(pe.current),void(pe.current=setTimeout(()=>ye(t),150));var t;}})}), Re(od,{content:le("conversationsFilterPinned"),children:Re("div",{className:"conversations-pin-filter-btn "+(T?"active":""),style:{userSelect:"none"},onClick:()=>A(!T),children:Re(Ut,{size:16})})}), Re(od,{content:le("conversationsFilterByTags"),children:Re("div",{ref:fe,className:"conversations-tag-search-btn "+(M.size>0?"active":""),style:{userSelect:"none"},onClick:()=>{const e=!D;e&&t?.(true),P(e);},children:Re(qt,{size:16})})}),D&&De("div",{ref:me,className:"conversations-tag-filter-menu",children:[ Re("div",{className:"conversations-tag-filter-list",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:0===c.length?Re("div",{className:"conversations-tag-filter-item",style:{color:"var(--gh-text-tertiary, #9ca3af)",cursor:"default"},children:le("conversationsNoTags")}):c.map(e=>De("div",{className:"conversations-tag-filter-item "+(M.has(e.id)?"selected":""),onClick:()=>{const t=new Set(M);t.has(e.id)?t.delete(e.id):t.add(e.id),I(t);},children:[ Re("span",{className:"conversations-tag-dot",style:{backgroundColor:e.color}}), Re("span",{children:e.name})]},e.id))}), Re("div",{className:"conversations-tag-filter-footer",children:Re("div",{className:"conversations-tag-filter-item conversations-tag-filter-action",onClick:()=>{P(false),t?.(true),Y({type:"tagManager",conv:void 0});},children:le("conversationsManageTags")})})]}), Re(od,{content:le("conversationsClearAll"),children:Re("div",{className:"conversations-search-clear "+(Ie?"":"disabled"),onClick:Ie?()=>{k(""),A(false),I(new Set),R(null);}:void 0,children:Re($e,{size:14})})})]}),C&&N&&De("div",{className:"conversations-result-bar visible",children:[N.totalCount," ",le("conversationsSearchResult")]})]}), Re("div",{className:"conversations-folder-list",children:0===o.filter(ze).length?Re("div",{className:"conversations-empty",children:le(N?"conversationsNoSearchResult":"conversationsEmpty")}):o.filter(ze).map((n,a)=>{const l=(c=n.id,N?Array.from(N.conversationFolderMap.values()).includes(c):g===c);var c;const d=(e=>Se(e).length)(n.id),u=bb(n),h=r?.features?.conversations?.folderRainbow??false;let f="transparent";return n.isDefault?f="var(--gh-folder-bg-default)":h?f=`var(--gh-folder-bg-${a%8})`:l&&(f="var(--gh-folder-bg-expanded, rgba(59, 130, 246, 0.08))"),De(i.Fragment,{children:[ De("div",{className:["conversations-folder-item",l?"expanded":"",n.isDefault?"default":"",ee===n.id?"is-dragging":"",ne===n.id&&ee!==n.id?"is-drag-over":"",ae===n.id?"is-drag-over-conv":""].filter(Boolean).join(" "),"data-folder-id":n.id,style:{background:f},draggable:!n.isDefault,onDragStart:e=>{if(n.isDefault)return void e.preventDefault();e.target.closest('button, input, textarea, select, [role="button"], [data-no-row-drag="true"]')?e.preventDefault():(te(n.id),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",n.id));},onDragEnd:()=>{te(null),re(null),ue.current=null;},onClick:()=>(e=>{p(g===e?null:e);})(n.id),onDragEnter:e=>{if(ee){if(n.isDefault||n.id===ee)return;e.preventDefault(),ue.current=n.id,re(n.id);}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.preventDefault(),ce.current=n.id,se(n.id));}},onDragOver:e=>{if(ee){if(n.isDefault||n.id===ee)return;e.preventDefault(),e.dataTransfer.dropEffect="move",ue.current=n.id,re(n.id);}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.preventDefault(),e.dataTransfer.dropEffect="move",ce.current=n.id,se(n.id));}},onDragLeave:e=>{const t=e.relatedTarget;if(!t||!e.currentTarget.contains(t))if(ee){const e=n.id;setTimeout(()=>{ue.current===e&&re(null);},0);}else if(oe){const e=n.id;setTimeout(()=>{ce.current===e&&se(null);},0);}},onDrop:t=>{if(t.preventDefault(),ee){if(n.isDefault||n.id===ee)return;const t=o.filter(ze).filter(e=>!e.isDefault),r=t.findIndex(e=>e.id===ee),i=t.findIndex(e=>e.id===n.id);if(-1===r||-1===i)return;const a=[...t],[s]=a.splice(r,1);a.splice(i,0,s);const l=o.filter(e=>!e.isDefault).filter(e=>!a.some(t=>t.id===e.id));e.reorderFolders([...a,...l].map(e=>e.id)),be(),te(null),re(null),ue.current=null;}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.moveConversation(oe,n.id),be()),ie(null),se(null),ce.current=null;}},children:[ De("div",{className:"conversations-folder-info",children:[m&&Re("input",{type:"checkbox",className:"conversations-folder-checkbox",checked:_e(n.id),ref:e=>{e&&(e.indeterminate=(e=>{const t=Se(e),n=t.filter(e=>b.has(e.id));return n.length>0&&n.length((e,t)=>{const n=Se(e),r=new Set(b);t?n.forEach(e=>r.add(e.id)):n.forEach(e=>r.delete(e.id)),y(r);})(n.id,e.target.checked),onClick:e=>e.stopPropagation()}), Re("span",{className:"conversations-folder-icon",style:{userSelect:"none"},children:n.icon}), Re(od,{content:u,children:Re("span",{className:"conversations-folder-name",children:C&&N?.folderMatches.has(n.id)?yb(u,C):u})})]}), De("div",{className:"conversations-folder-controls",children:[ De("span",{className:"conversations-folder-count",children:["(",d,")"]}), Re("button",{className:"conversations-folder-menu-btn",style:{userSelect:"none",visibility:n.isDefault?"hidden":"visible",pointerEvents:n.isDefault?"none":"auto"},onClick:e=>{e.stopPropagation(),t?.(true),J({type:"folder",folder:n,anchorEl:e.currentTarget});},children:Re(Nt,{size:20})})]})]}),l&&Re("div",{className:"conversations-list","data-folder-id":n.id,children:(()=>{const e=Se(n.id);if(0===e.length) return Re("div",{className:"conversations-list-empty",children:le("conversationsEmpty")});const r=Ce[n.id]||mb,o=e.slice(0,r),i=e.length>r; return De(Ne,{children:[o.map(e=>Re(xb,{conv:e,batchMode:m,isSelected:b.has(e.id),isNarrowLayout:z,searchQuery:C,searchResult:N,tagMap:ve,draggedConvId:oe,onConversationClick:qe,onSelectionChange:y,onInteractionStateChange:t,onMenuChange:J,onDragStart:e=>{ie(e),ce.current=null;},onDragEnd:()=>{ie(null),se(null),ce.current=null;}},e.id)),i&&Re("div",{className:"conversations-load-more-sentinel","data-folder-id":n.id,ref:e=>{const t=Te.current.get(n.id);t&&t!==e&&Pe.current?.unobserve(t),e?(Te.current.set(n.id,e),Pe.current?.observe(e)):Te.current.delete(n.id);},style:{height:"1px",margin:0,padding:0}})]})})()})]},n.id)})}),m&&b.size>0&&De("div",{className:"conversations-batch-bar",children:[ Re("span",{className:"conversations-batch-info",children:le("batchSelected").replace("{n}",String(b.size))}), De("div",{className:"conversations-batch-btns",children:[ Re(od,{content:le("exportToClipboard"),children:Re("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:async()=>{const t=Array.from(b)[0];await e.exportConversation(t,"clipboard");},children:Re(It,{size:16})})}), Re(od,{content:le("batchExport"),children:Re("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:e=>{t?.(true),J({type:"export",anchorEl:e.currentTarget});},children:Re(Ze,{size:16})})}), Re(od,{content:le("batchMove"),children:Re("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"folderSelect",convIds:Array.from(b)});},children:Re(Oe,{size:16})})}), Re(od,{content:le("batchDelete"),children:Re("button",{className:"conversations-batch-btn danger",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"confirm",title:le("batchDelete"),message:le("confirmDeleteSelectedConvs",{count:String(b.size)}),danger:true,onConfirm:async()=>{if(!w){Y(null),S(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversations(Array.from(b));if(0===t.localDeletedCount)return void Pi(le("deleteError"));t.remoteAttemptedCount>0&&t.remoteFailedCount>0&&Pi(`已删除 ${t.localDeletedCount} 个,本地成功,云端失败 ${t.remoteFailedCount} 个`),Me(),await be();}finally{S(false);}}}});},children:Re(Ft,{size:16})})}), Re(od,{content:le("batchExit"),children:Re("button",{className:"conversations-batch-btn cancel",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:Me,children:Re($e,{size:16})})})]})]})]}),"confirm"===Z?.type&&Re(Zf,{title:Z.title,message:Z.message,danger:Z.danger,onConfirm:Z.onConfirm,onCancel:()=>Y(null)}),"folder"===Z?.type&&Re(Yf,{folder:Z.folder,onConfirm:async(t,n)=>{let r=null;if(Z.folder)await e.updateFolder(Z.folder.id,{name:t,icon:n});else {const o=await e.createFolder(t,n);o&&(r=o.id);}be(),Z.returnToSelect?Y({type:"folderSelect",conv:Z.returnToSelect.conv,convIds:Z.returnToSelect.convIds,activeFolderId:r||void 0}):Y(null);},onCancel:()=>Y(null)}),"rename"===Z?.type&&Re(Xf,{title:le("conversationsRename"),currentValue:Z.conv.title,onConfirm:async t=>{await e.renameConversation(Z.conv.id,t),be(),Y(null);},onCancel:()=>Y(null)}),"folderSelect"===Z?.type&&Re(Jf,{folders:o,excludeFolderId:Z.conv?.folderId,activeFolderId:Z.activeFolderId,onSelect:async t=>{if(Z.conv)await e.moveConversation(Z.conv.id,t);else if(Z.convIds){for(const n of Z.convIds)await e.moveConversation(n,t);Me();}be(),Y(null);},onCancel:()=>Y(null),onCreateFolder:()=>Y({type:"folder",returnToSelect:{conv:Z.conv,convIds:Z.convIds}})}),"tagManager"===Z?.type&&Re(eb,{tags:c,conv:Z.conv,onCancel:()=>Y(null),onCreateTag:async(t,n)=>e.createTag(t,n),onUpdateTag:async(t,n,r)=>e.updateTag(t,n,r),onDeleteTag:async t=>e.deleteTag(t),onSetConversationTags:async(t,n)=>e.setConversationTags(t,n),onRefresh:()=>be()}),"folder"===X?.type&&Re(hb,{folder:X.folder,anchorEl:X.anchorEl,onClose:()=>J(null),onRename:()=>{J(null),Y({type:"folder",folder:X.folder});},onDelete:()=>{J(null);const t=bb(X.folder),n=fb(),r=le("conversationsDeleteConfirm",{folder:t,inbox:n});Y({type:"confirm",title:le("conversationsDelete"),message:"conversationsDeleteConfirm"===r?`Delete folder "${t}"? Conversations will be moved to ${n}.`:r,danger:true,onConfirm:async()=>{await e.deleteFolder(X.folder.id),be(),Y(null);}});}}),"conversation"===X?.type&&Re(gb,{conversation:X.conv,anchorEl:X.anchorEl,anchorPoint:X.anchorPoint,onClose:()=>J(null),onOpenInNewTab:()=>Be(X.conv),onRename:()=>{J(null),Y({type:"rename",conv:X.conv});},onTogglePin:async()=>{J(null),await e.togglePin(X.conv.id),be();},onSetTags:()=>{J(null),Y({type:"tagManager",conv:X.conv});},onMoveTo:()=>{J(null),Y({type:"folderSelect",conv:X.conv});},onExport:()=>{const e=X.conv,t=X.anchorEl,n=X.anchorPoint;J({type:"export-conv",conv:e,anchorEl:t,anchorPoint:n});},onDelete:()=>{J(null),Y({type:"confirm",title:le("conversationsDelete"),message:le("conversationsDeleteConvMsg",{title:X.conv.title}),danger:true,onConfirm:async()=>{if(!w){Y(null),S(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversation(X.conv.id);if(!t.localDeleted)return void Pi(le("deleteError"));t.remoteAttempted&&!t.remoteSuccess&&Pi(le("deleteConvRemoteError")),await be();}finally{S(false);}}}});}}),"export"===X?.type&&Re(pb,{anchorEl:X.anchorEl,onClose:()=>J(null),onExportMarkdown:async()=>{J(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"markdown");},onExportJSON:async()=>{J(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"json");},onExportTXT:async()=>{J(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"txt");}}),"export-conv"===X?.type&&Re(pb,{anchorEl:X.anchorEl,anchorPoint:X.anchorPoint,onClose:()=>J(null),onExportMarkdown:async()=>{J(null),await e.exportConversation(X.conv.id,"markdown");},onExportJSON:async()=>{J(null),await e.exportConversation(X.conv.id,"json");},onExportTXT:async()=>{J(null),await e.exportConversation(X.conv.id,"txt");}})]})},xb=i.memo(({conv:e,batchMode:t,isSelected:n,isNarrowLayout:r,searchQuery:o,searchResult:i,tagMap:a,draggedConvId:s,onConversationClick:l,onSelectionChange:c,onInteractionStateChange:d,onMenuChange:u,onDragStart:h,onDragEnd:g})=>{const p=e.tagIds||[],m=r?1:2,f=p.map(e=>a.get(e)).filter(e=>!!e),b=f.slice(0,m),y=f.slice(m).length; return De("div",{className:"conversations-item "+(s===e.id?"is-dragging":""),"data-id":e.id,draggable:true,onDragStart:t=>{h(e.id),t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.id);},onDragEnd:g,onClick:()=>l(e),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),d?.(true),u({type:"conversation",conv:e,anchorEl:null,anchorPoint:{left:t.clientX,top:t.clientY}});},children:[t&&Re("input",{type:"checkbox",className:"conversations-item-checkbox",checked:n,onChange:()=>{},onClick:t=>{t.stopPropagation(),c(t=>{const n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n});}}), Re("div",{className:"conversations-item-main",children:De("div",{className:"conversations-item-headline",children:[ Re(od,{content:e.title,triggerStyle:{flex:1,minWidth:0,overflow:"hidden",display:"block"},children:De("span",{className:"conversations-item-title",style:{userSelect:"none"},children:[e.pinned&&Re(Ut,{size:12,color:"var(--gh-primary, #3b82f6)",style:{display:"inline-block",marginRight:"4px",verticalAlign:"middle"}}),o&&i?.conversationMatches.has(e.id)?yb(e.title||"无标题",o):e.title||"无标题"]})}),p.length>0&&De("div",{className:"conversations-tag-list",children:[b.map(e=>Re("span",{className:"conversations-tag",style:{backgroundColor:e.color},children:e.name},e.id)),y>0&&Re(od,{content:Re("div",{className:"conversations-hidden-tags-tooltip",children:f.map(e=>De("div",{className:"conversations-hidden-tag-item",children:[ Re("span",{className:"conversations-hidden-tag-dot",style:{backgroundColor:e.color}}), Re("span",{children:e.name})]},e.id))}),delay:120,triggerStyle:{display:"inline-flex"},children:De("span",{className:"conversations-tag conversations-tag-more",children:["+",y]})})]})]})}), Re("div",{className:"conversations-item-meta",children:Re("button",{className:"conversations-item-menu-btn",title:le("more"),onClick:t=>{t.stopPropagation(),d?.(true),u({type:"conversation",conv:e,anchorEl:t.currentTarget});},children:Re(Nt,{size:20})})})]})});function wb(e){return e.replace(/(^|\n)\s*>+\s?/g,"$1")}function Sb(e,t){const n=function(e){return wb(e).replace(/^\s{0,3}#{1,6}\s+/,"").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\\([\\`*_[\]{}()#+\-.!|>])/g,"$1").replace(/[`*_~]/g,"").replace(/\s+/g," ").trim()}(wb(e.replace(/\r\n?/g,"\n")).replace(/\n+/g," "));return !t||n.length<=t?n:`${n.slice(0,t).trim()}...`}function Cb(e){const t=[],n=e.replace(/\r\n?/g,"\n").split("\n");let r=null;for(const o of n){const e=/^\s{0,3}(```+|~~~+)/.exec(o);if(e){const t=e[1],n=t[0];r?r.char===n&&t.length>=r.length&&(r=null):r={char:n,length:t.length};continue}if(r)continue;const n=/^\s{0,3}(#{1,6})(?:\s+|$)(.*?)(?:\s+#+\s*)?$/.exec(o);if(!n)continue;const i=n[1].length,a=Sb(n[2]);a&&t.push({level:i,text:a});}return t}function kb(e){return "#".repeat(Math.min(6,Math.max(1,e)))}function Tb(e,t){return 0===e.length||t<1?[]:e.flatMap(e=>e.level>t?[]:[`${kb(e.level)} ${e.text}`])}function Eb(e,t){return `${kb(1)} Q${t}. ${e}`}function Ab(e,t){const n="number"==typeof(r=t.maxHeadingLevel)&&Number.isFinite(r)?Math.min(6,Math.max(0,Math.floor(r))):6;var r;const o=[];let i=0;for(const a of e){if("user"===a.role.toLowerCase()){if(!t.includeUserQueries)continue;const e=Sb(a.content,120);e&&(i+=1,o.push(Eb(e,i)));continue}const e=Cb(a.content);o.push(...Tb(e,n));}return 0===o.length?{text:"",count:0}:{text:o.join("\n\n"),count:o.length}}function Mb(e,t){if(e<1e3)return e.toString();if("zh-CN"===t||"zh-TW"===t){if(e>=1e4)return (e/1e4).toFixed(1).replace(/\.0$/,"")+"w";if(e>=1e3)return (e/1e3).toFixed(1).replace(/\.0$/,"")+"k"}return e>=1e3?e>=1e6?(e/1e6).toFixed(1).replace(/\.0$/,"")+"m":(e/1e3).toFixed(1).replace(/\.0$/,"")+"k":e.toString()}const Ib=e=>{let t=0;for(const n of e)t+=1,n.children.length>0&&(t+=Ib(n.children));return t},Lb=e=>"conversation"===e.kind?le("outlineSourceConversation"):"document"===e.kind?le("outlineSourceDocument"):e.label,Nb=(e,t,n,r,o,i)=>{const a={},s={},l=new Map,c=e=>{const t=l.get(e.index);if(void 0!==t)return t;let n=!!e.isBookmarked;if(!n&&e.children&&e.children.length>0)for(const r of e.children)if(c(r)){n=true;break}return l.set(e.index,n),n},d=(e,l,u,h,g)=>{a[e.index]=l;const p=c(e);let m;if(i)if(p||g){const t=!r||e.isMatch||e.hasMatchedDescendant;m=!u&&t;}else m=false;else {const i=e.relativeLevel===n,a=e.relativeLevel<=t||h;if(i)m=!r||(e.isMatch||e.hasMatchedDescendant);else {const t=!r||e.isMatch||e.hasMatchedDescendant||h;m=r&&!o?t&&!u:r&&o?t&&a&&!u:a&&!u;}u&&(m=false);}e.forceVisible&&(m=true),s[e.index]=m;const f=e.collapsed||u,b=e.forceExpanded||h,y=g||e.isBookmarked&&!(e=>!(!e.children||0===e.children.length)&&e.children.some(c))(e);e.children&&e.children.length>0&&e.children.forEach(t=>d(t,e.index,f,b,y));};return e.forEach(e=>d(e,null,false,false,false)),{parentMap:a,visibleMap:s}},Rb=(e,t)=>t?e:Math.max(1,e),Db=({node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,setItemRef:i,visibleMap:a,searchQuery:s,extractUserQueryText:l})=>{const c=e.children&&e.children.length>0,d=c&&!e.collapsed,u=a[e.index]??true,h=["outline-item",`outline-level-${e.relativeLevel}`,e.isUserQuery?"user-query-node":"",e.isGhost?"ghost-node":"",u?"":"outline-hidden"].filter(Boolean).join(" "),[g,p]=_(false),[m,f]=_(false); return De(Ne,{children:[ Re(od,{content:e.wordCount&&e.wordCount>0?De("div",{children:[e.text, De("div",{style:{fontSize:"12px",opacity:.8,marginTop:"2px"},children:["(",Mb(e.wordCount,de())," ",le("words"),")"]})]}):e.text,disabled:m,triggerStyle:{width:"100%",display:"block"},triggerClassName:u?"":"outline-hidden",delay:500,children:De("div",{className:h,"data-index":e.index,"data-level":e.relativeLevel,ref:t=>i(e.index,t),onClick:()=>n(e),children:[ Re("span",{className:"outline-item-toggle "+(c?d?"expanded":"":"invisible"),onClick:n=>{c&&(n.stopPropagation(),t(e));},children:Re(Dt,{size:16,style:{transform:"rotate(-90deg)"}})}),e.isUserQuery&&De("span",{className:"user-query-badge",children:[ Re("span",{className:"user-query-badge-icon",children:"💬"}), Re("span",{className:"user-query-badge-number",children:e.queryIndex})]}), Re("span",{className:"outline-item-text "+(e.isGhost?"ghost-text":""),children:(()=>{if(s&&e.isMatch)try{const t=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(${t})`,"gi"),r=e.text.split(n); return Re(Ne,{children:r.map((e,t)=>e.toLowerCase()===s.toLowerCase()?Re("mark",{style:{backgroundColor:"var(--gh-search-highlight-bg)",color:"inherit",padding:0,borderRadius:"2px"},children:e},t):e)})}catch{return e.text}return e.text})()}), Re("span",{className:"outline-item-bookmark-wrapper "+(e.isBookmarked?"active":""),children:Re(od,{content:e.isBookmarked?le("removeBookmark"):le("addBookmark"),children:Re("span",{className:"outline-item-bookmark-btn "+(e.isBookmarked?"active":""),onClick:t=>o(t,e),onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),children:Re(mt,{size:14,filled:e.isBookmarked,color:e.isBookmarked?"#f59e0b":"currentColor"})})})}), Re(od,{content:le("copy"),children:Re("span",{className:"outline-item-copy-btn",onClick:async t=>{t.stopPropagation(),t.preventDefault();let n=e.text;if(e.element&&e.element.isConnected)if(e.isUserQuery&&l){const t=l(e.element);t&&(n=t);}else {const t=e.element.textContent;t&&(n=t.trim());}try{await navigator.clipboard.writeText(n),p(!0),setTimeout(()=>p(!1),1500);}catch(r){console.error("[DEBUG] Clipboard API failed, trying fallback:",r);try{const e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),p(!0),setTimeout(()=>p(!1),1500);}catch(o){console.error("[DEBUG] Fallback copy also failed:",o);}}},onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),children:g? Re(Xt,{size:14,color:"#10b981"}): Re(It,{size:14})})})]})}),c&&e.children.map((e,c)=>Re(Db,{node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,setItemRef:i,visibleMap:a,searchQuery:s,extractUserQueryText:l},`${e.level}-${e.text}-${c}`))]})},Pb=({manager:e,conversationManager:t,onJumpBefore:n,isCodexOpen:r=false})=>{const{settings:o}=Mi(),a=o,s=i.useMemo(()=>ur(),[]),l=le("shortcutNotSet"),c=i.useMemo(()=>ab(a.shortcuts?.keybindings,s,l),[a.shortcuts?.keybindings,a.language,s,l]),d=e.getState(),[u,h]=_(d.tree),[g,p]=_(e.getSearchQuery()),[m,f]=_(d.isAllExpanded),[b,y]=_(d.includeUserQueries),[v,x]=_("bottom"),[w,S]=_(d.expandLevel??6),[C,k]=_(d.levelCounts),[T,A]=_(d.displayLevel),[M,I]=_(d.minRelativeLevel),[N,R]=_(d.searchLevelManual),[D,P]=_(d.matchCount),[B,O]=_(d.bookmarkMode),[z,F]=_(d.sources),[U,H]=_(d.activeSourceId),[W,j]=_(false),[G,V]=_(false),Q=$(null),K=$(null),Z=$(0),Y=$(false),X=$(null),J=$(null),ee=$(new Map),te=$(0),ne=$(null),re=$(0),oe=$(false),ie=$(null),ae=$({parentMap:{},visibleMap:{},hasData:false});L(()=>(e.setActive(true),()=>{e.setActive(false);}),[e]),L(()=>{const e=()=>{K.current&&(K.current.focus(),K.current.select());};return window.addEventListener("ophel:searchOutline",e),window.__ophelPendingSearchOutline&&(delete window.__ophelPendingSearchOutline,setTimeout(e,100)),()=>{window.removeEventListener("ophel:searchOutline",e);}},[]),L(()=>{const t=()=>{const t=e.getState(),n=Ib(t.tree),r=Z.current;"latest"===(o?.features?.outline?.followMode||"current")&&n>r&&(Y.current=true),h([...t.tree]),p(e.getSearchQuery()),f(t.isAllExpanded),S(t.expandLevel??6),k(t.levelCounts||{}),y(t.includeUserQueries),A(t.displayLevel),I(t.minRelativeLevel),R(t.searchLevelManual),P(t.matchCount),O(t.bookmarkMode),F(t.sources),H(t.activeSourceId),Z.current=n;};return t(),e.subscribe(t)},[e,o?.features?.outline?.followMode]),L(()=>{if(Y.current&&Q.current){const e=Q.current;requestAnimationFrame(()=>{e.scrollTo({top:e.scrollHeight,behavior:"smooth"});}),Y.current=false;}},[u]);const se=E((...e)=>{if(0===e.length)return;const t=t=>{t.classList.remove(...e);};ee.current.forEach(t);const n=e.map(e=>`.outline-item.${e}`).join(", ");Q.current?.querySelectorAll(n).forEach(t);},[]),ce=E(e=>{se(e);},[se]),de=E(e=>{const t=null!==e&&ee.current.get(e)||null;ee.current.forEach(e=>{e!==t&&e.classList.remove("sync-highlight","sync-highlight-visible");}),Q.current?.querySelectorAll(".outline-item.sync-highlight, .outline-item.sync-highlight-visible").forEach(e=>{e!==t&&e.classList.remove("sync-highlight","sync-highlight-visible");}),t&&(t.classList.remove("sync-highlight-visible"),t.classList.add("sync-highlight"));},[]),ue=E(e=>{X.current=e;},[]),he=E(e=>{de(e),J.current=e;},[de]),ge=E((e,t)=>{const n=ee.current;t?(n.set(e,t),e!==J.current&&t.classList.remove("sync-highlight","sync-highlight-visible"),e===J.current&&de(e)):n.delete(e);},[de]),pe=E(t=>{re.current+=1;const n=ne.current;n&&(clearTimeout(n.timer),ne.current=null),ce("highlight"),t?.clearForceVisible&&e.clearForceVisible();},[e,ce]),me=E(e=>{if(null===e)return null;const{parentMap:t,visibleMap:n,hasData:r}=ae.current;if(!r)return e;let o=e;for(;null!=o;){if(n[o])return o;o=t[o];}return null},[]),fe=q(()=>Nb(u,T,M,g,N,B),[u,T,M,g,N,B]),{parentMap:be,visibleMap:ye}=fe,ve=q(()=>z.filter(e=>e.available),[z]),xe=q(()=>{const e=t=>{for(const n of t){if(ye[n.index])return true;if(n.children&&n.children.length>0&&e(n.children))return true}return false};return e(u)},[u,ye]);ae.current={parentMap:be,visibleMap:ye,hasData:u.length>0},L(()=>{const e=me(X.current);he(e);},[be,ye,u.length,me,he]),L(()=>{if("current"!==(o?.features?.outline?.followMode||"current"))return ue(null),void he(null);let t,n=null,r=0,i=0,a=null,s=null,l=null;const c=new Map,d=()=>{e.markScrollPositionsStale();},u=t=>{if(c.has(t))return;const n=new MutationObserver(()=>{s||(s=setTimeout(()=>{s=null;const t="undefined"!=typeof window?window.requestIdleCallback?.bind(window):void 0;if(t){if(null!==l)return;l=t(()=>{l=null,e.markScrollPositionsStale();},{timeout:500});}else e.markScrollPositionsStale();},300));});n.observe(t,{childList:true,subtree:true,characterData:true}),c.set(t,n);},h=()=>{if(!n)return;const t=n.scrollTop,r=n.clientHeight,o=n.scrollHeight;o!==i&&(i=o,e.markScrollPositionsStale());const a=e.findVisibleItemIndex(t,r);if(null===a)return ue(null),void he(null);ue(a);const s=me(a);he(s),null!==s&&requestAnimationFrame(()=>{if(oe.current)return;const e=Q.current;if(!e)return;const t=ee.current.get(s)||null;if(!t)return;const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(r.topn.bottom){const t=r.top-n.top-n.height/2+r.height/2;e.scrollBy({top:t,behavior:"instant"});}});},g=()=>{const o=e.getScrollContainer();o?(n=o,i=o.scrollHeight,n.addEventListener("scroll",h,{passive:true}),window.addEventListener("resize",d,{passive:true}),(e=>{try{u(e);}catch(t){console.warn("[OutlineTab] Failed to attach MutationObserver:",t);}})(o),"undefined"!=typeof ResizeObserver&&(a=new ResizeObserver(()=>{i=n?.scrollHeight||0,e.markScrollPositionsStale();}),a.observe(n)),h()):r<20?(r++,t=setTimeout(g,300)):console.warn("[OutlineTab] Failed to find scroll container after retries");};return g(),()=>{if(n&&n.removeEventListener("scroll",h),window.removeEventListener("resize",d),s&&clearTimeout(s),null!==l){const e="undefined"!=typeof window?window.cancelIdleCallback?.bind(window):void 0;e&&e(l),l=null;}c.forEach(e=>e.disconnect()),c.clear(),a&&(a.disconnect(),a=null),t&&clearTimeout(t);}},[e,u.length,o?.features?.outline?.followMode,me,ue,he]),L(()=>{const e=Q.current;if(!e)return;const t=()=>{const t=e.scrollTop+e.clientHeight>=e.scrollHeight-10;x(t?"top":"bottom");};return e.addEventListener("scroll",t),t(),()=>e.removeEventListener("scroll",t)},[]),L(()=>{const e=Q.current;if(!e)return;const t=()=>{oe.current=true,ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{oe.current=false;},1500);};return e.addEventListener("wheel",t,{passive:true}),()=>{e.removeEventListener("wheel",t),ie.current&&clearTimeout(ie.current);}},[]);const we=E(t=>{e.toggleNode(t);},[e]),Se=E(async t=>{const r=++te.current;pe({clearForceVisible:true}),he(me(X.current));let o=t.element,i=false;if(!o||!o.isConnected){n&&(await n(),i=true);const r=await e.resolveOutlineTarget(t,t.queryIndex);r&&(o=r,t.element=o);}if(r===te.current)if(o&&o.isConnected){if(n&&!i&&await n(),r!==te.current)return;if(e.scrollToOutlineTarget(o),ue(t.index),he(me(t.index)),void 0!==document.documentElement.dataset.ophelPositionLock){const t=e.getScrollContainer();t&&(document.documentElement.dataset.ophelPositionLock=String(t.scrollTop));}o.classList.add("outline-highlight"),setTimeout(()=>o?.classList.remove("outline-highlight"),2e3);}else if(t.isGhost&&void 0!==t.scrollTop){const n=e.getScrollContainer();n&&(n.scrollTo({top:t.scrollTop,behavior:"smooth"}),ue(t.index),he(me(t.index)),Pi(le("bookmarkContentMissing"),3e3));}},[pe,me,e,n,ue,he]),Ce=E((e,t)=>{e.stopPropagation();const n=t.text;navigator.clipboard.writeText(n);},[]),ke=E(async()=>{if(!W){j(true);try{let e;if("conversation"===U){const n=await t.collectCurrentConversationExportMessages();if(!n||0===n.length)return void Pi(le("outlineEmpty"));e=Ab(n,{includeUserQueries:b,maxHeadingLevel:Rb(w,b)});}else e=function(e,t){const n=[];let r=0;const o=e=>{if(!t.isIncluded||t.isIncluded(e)){const o=Sb(e.text,e.isUserQuery?120:void 0);o&&(e.isUserQuery?t.includeUserQueries&&(r+=1,n.push(Eb(o,r))):n.push(`${kb(e.level)} ${o}`));}e.children?.forEach(o);};return e.forEach(o),0===n.length?{text:"",count:0}:{text:n.join("\n\n"),count:n.length}}(u,{includeUserQueries:b,isIncluded:e=>ye[e.index??-1]??!0});if(!e.text)return void Pi(le("outlineEmpty"));await(async e=>{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e));const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{if(!document.execCommand("copy"))throw new Error("execCommand copy returned false")}finally{t.remove();}})(e.text),V(!0),Pi(le("outlineFullCopySuccess").replace("{count}",String(e.count))),window.setTimeout(()=>V(!1),1500);}catch(RS){console.error("[OutlineTab] Failed to copy outline:",RS),Pi(le("copyFailed"));}finally{j(false);}}},[U,t,w,W,b,u,ye]),Te=E(t=>e.extractUserQueryText(t),[e]),Ee=E(t=>{e.setSearchQuery(t.target.value);},[e]),Ae=E(()=>{e.setSearchQuery("");},[e]),Me=E(()=>{m?e.collapseAll():e.expandAll();},[e,m]),Ie=E((t,n)=>{t.stopPropagation(),e.toggleBookmark(n);},[e]),Le=E(()=>{e.toggleBookmarkMode();},[e]),Ne=E(()=>{e.toggleGroupMode();},[e]),Pe=E(()=>{const e=Q.current;e&&("bottom"===v?e.scrollTo({top:e.scrollHeight,behavior:"smooth"}):e.scrollTo({top:0,behavior:"smooth"}));},[v]),qe=E(()=>{const t=e.getScrollContainer();if(!t)return;g&&(e.setSearchQuery(""),p(""));const n=e=>{const t=[];return e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&t.push(...n(e.children));}),t},r=n(u),o=t.getBoundingClientRect(),i=o.top,a=o.bottom;let s=null;for(const e of r){if(!e.element||!e.element.isConnected)continue;const t=e.element.getBoundingClientRect();if(t.top>=i&&t.topi){s=e;break}}if(!s){let e=1/0;for(const t of r){if(!t.element||!t.element.isConnected)continue;const n=t.element.getBoundingClientRect(),r=Math.abs(n.top-i);r{if(l!==re.current)return;const t=Q.current;if(!t)return;const n=t.querySelector(`.outline-item[data-index="${s.index}"]`);if(!n)return;n.scrollIntoView({behavior:"instant",block:"center"}),n.classList.add("highlight");const r=setTimeout(()=>{n.classList.remove("highlight"),e.clearForceVisible(),ne.current=null;},3e3);ne.current={element:n,timer:r};},50);},[u,g,e,pe]);L(()=>()=>{pe({clearForceVisible:true});},[pe]);const Be=E(t=>{e.setLevel(t);},[e]);return L(()=>{const e=()=>{window.__ophelPendingLocateOutline=false,qe();};return window.__ophelPendingLocateOutline&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateOutline",e),()=>{window.removeEventListener("ophel:locateOutline",e);}},[qe]),De("div",{className:"gh-outline-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ De("div",{className:"outline-fixed-toolbar",style:{padding:"8px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",flexDirection:"column",gap:"8px",backgroundColor:"var(--gh-bg, #fff)"},children:[ De("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[ De("div",{style:{display:"flex",gap:"2px"},children:[ Re(od,{content:le("outlineShowUserQueries"),children:Re("button",{onClick:Ne,className:"outline-toolbar-btn "+(b?"active-subtle":""),children:Re(Yt,{size:15})})}), Re(od,{content:le("bookmarkMode"),children:Re("button",{onClick:Le,className:"outline-toolbar-btn "+(B?"active-subtle":""),children:Re(mt,{size:16,filled:B,color:"currentColor"})})}), Re(od,{content:le(B?"bookmarkModeDisabled":m?"outlineCollapseAll":"outlineExpandAll"),children:Re("button",{onClick:B?void 0:Me,disabled:B,className:"outline-toolbar-btn",children:Re(m?tt:et,{size:18})})}), Re(od,{content:le(W?"outlineCopyFullRunning":"outlineCopyFull"),children:Re("button",{onClick:ke,disabled:W,className:"outline-toolbar-btn "+(W?"is-busy":""),children:G?Re(Xt,{size:14,color:"#10b981"}):Re(Lt,{size:16})})}), Re(od,{content:le("outlineLocateCurrent"),children:Re("button",{onClick:qe,className:"outline-toolbar-btn",children:Re(nt,{size:16})})}), Re(od,{content:le("bottom"===v?"outlineScrollBottom":"outlineScrollTop"),children:Re("button",{onClick:Pe,className:"outline-toolbar-btn",children:Re("bottom"===v?ot:rt,{size:16})})})]}), De("div",{className:"outline-search-wrapper",style:{flex:1,position:"relative",display:"flex",alignItems:"center"},children:[ Re("input",{ref:K,type:"text",className:"outline-search-input",placeholder:le("outlineSearch"),value:g,onChange:Ee,style:{width:"100%",padding:"4px 24px 4px 8px",borderRadius:"4px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"12px",boxSizing:"border-box",height:"26px",backgroundColor:"var(--gh-input-bg, #fff)",color:"var(--gh-text, #374151)"}}),g&&Re("button",{className:"outline-search-clear",onClick:Ae,style:{position:"absolute",right:"4px",background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"14px",padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:Re($e,{size:14})})]})]}), Re("div",{className:"outline-level-slider-container",style:{padding:"0 4px"},children:De("div",{className:"outline-level-dots",style:{display:"flex",justifyContent:"space-between",position:"relative",padding:"6px 0",alignItems:"center"},children:[ Re("div",{className:"outline-level-line-bg",style:{position:"absolute",top:"50%",left:"4px",right:"4px",height:"4px",background:"var(--gh-border, #e5e7eb)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px"}}), Re("div",{className:"outline-level-progress",style:{position:"absolute",top:"50%",left:"4px",height:"4px",background:B?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px",width:`calc((${w} / 6) * (100% - 8px))`,transition:"width 0.2s ease"}}),[0,1,2,3,4,5,6].map(e=>{let t="";t=B?le("bookmarkModeDisabled"):0===e?le(b?"outlineUserQueryRoleLabel":"outlineCollapseAll"):`H${e}: ${C[e]||0}`;const n=e<=w; return Re(od,{content:t,children:Re("div",{className:`outline-level-dot ${n?"active":""} ${B?"disabled":""}`,"data-level":e,onClick:B?void 0:()=>Be(e),style:{width:"14px",height:"14px",borderRadius:"50%",backgroundColor:n?B?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)":"var(--gh-slider-dot-bg, #d1d5db)",border:n?"2px solid var(--gh-bg, #fff)":"none",zIndex:1,cursor:B?"not-allowed":"pointer",position:"relative",transition:"all 0.2s ease",boxSizing:"border-box",boxShadow:n?B?"0 0 0 1px var(--gh-text-disabled, #9ca3af)":"0 0 0 1px var(--gh-primary, #3b82f6)":"none",opacity:B?.5:1}})},e)})]})})]}),g&&De("div",{className:"outline-result-bar",style:{textAlign:"center",padding:"6px 8px",margin:"0 8px 0 8px",color:"var(--gh-border-active)",fontSize:"13px",background:D>0?"var(--gh-folder-bg-default)":"transparent",borderRadius:"4px",border:0===D?"1px dashed var(--gh-border, #e5e7eb)":"none",flexShrink:0},children:[D," ",le("outlineSearchResult")]}),ve.length>1&&!g&&Re("div",{className:"outline-source-switch","aria-label":le("outlineSourceSwitchLabel"),children:ve.map(t=>Re("button",{type:"button",className:"outline-source-switch-option "+(U===t.id?"active":""),onClick:()=>e.setActiveSource(t.id),children:Re("span",{children:Lb(t)})},t.id))}), Re("div",{ref:Q,className:`gh-outline-tree-container gh-panel-bookmark-mode-${o?.features?.outline?.panelBookmarkMode||"always"}`,style:{flex:1,overflowY:"auto",padding:g?"0 8px 8px 8px":"8px"},children:(()=>{const e=t=>t.some(t=>t.isBookmarked||t.children&&t.children.length>0&&e(t.children)),t=e(u),n=0===u.length,o=!g&&(n||!xe),i=le(b&&0===T?"outlineEmptyDescUserQueryOnly":"outlineEmptyDescDefault"),a=i.indexOf(","),s=i.indexOf(",");let l=-1;l=a>=0&&s>=0?Math.min(a,s):Math.max(a,s);const d=l>=0?i.slice(0,l).trim():i,h=l>=0?i.slice(l+1).trim():"";return !B||t||g?o?De("div",{className:"outline-empty-state",children:[ Re("div",{className:"outline-empty-state-icon","aria-hidden":"true",children:Re(je,{size:20,color:"currentColor"})}), Re("div",{className:"outline-empty-state-title",children:le("outlineEmpty")}), De("div",{className:"outline-empty-state-desc",children:[ Re("span",{className:"outline-empty-state-desc-line",children:d}),h&&Re("span",{className:"outline-empty-state-desc-line",children:h})]}), Re("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!r&&Re(ob,{isOpen:true,onClose:()=>{},tips:c,isStatic:true})})]}):Re("div",{className:"outline-list",children:u.map((e,t)=>Re(Db,{node:e,onToggle:we,onClick:Se,onCopy:Ce,onToggleBookmark:Ie,setItemRef:ge,visibleMap:ye,searchQuery:g,extractUserQueryText:Te},`${e.level}-${e.text}-${t}`))}):De("div",{className:"outline-empty-state",children:[ Re("div",{className:"outline-empty-state-icon",style:{background:"rgba(245, 158, 11, 0.1)",color:"#f59e0b"},"aria-hidden":"true",children:Re(mt,{size:20,filled:true,color:"#f59e0b"})}), Re("div",{className:"outline-empty-state-title",children:le("outlineNoBookmarks")}), Re("div",{className:"outline-empty-state-desc",children:le("outlineAddBookmarkHint")}), Re("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!r&&Re(ob,{isOpen:true,onClose:()=>{},tips:c,isStatic:true})})]})})()})]})},qb=({variables:e,onConfirm:t,onCancel:n})=>{const[r,o]=_(e.map(e=>({name:e.raw,value:e.options?e.options[0]:e.defaultValue??""}))),i=$(null);L(()=>{setTimeout(()=>{i.current?.focus();},100);},[]);const a=()=>{const e={};r.forEach(t=>{e[t.name]=t.value;}),t(e);},s=(e,t)=>{o(n=>{const r=[...n];return r[e]={...r[e],value:t},r});}; return Re($f,{onClose:n,closeOnOverlayClick:false,dialogClassName:"prompt-modal-content",dialogStyle:{width:"400px",maxWidth:"90%",maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)",animation:"slideUp 0.2s ease-out",padding:0},children:De("div",{onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),a()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),n());},style:{display:"flex",flexDirection:"column",flex:1,minHeight:0},children:[ De("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("h3",{style:{margin:0,fontSize:"16px",fontWeight:600,color:"var(--gh-text, #374151)"},children:le("promptVariableTitle")}), Re("button",{onClick:n,style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:Re($e,{size:18})})]}), Re("div",{style:{padding:"16px",overflowY:"auto",flex:1},children:e.map((e,t)=>De("div",{style:{marginBottom:"16px",display:"flex",flexDirection:"column",gap:"6px"},children:[ Re("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",wordBreak:"break-all"},children:e.name}),e.options? Re("select",{value:r[t]?.value??"",onChange:e=>s(t,e.target.value),style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",cursor:"pointer",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";},children:e.options.map(e=>Re("option",{value:e,children:e},e))}): Re("input",{ref:0===t?i:void 0,type:"text",value:r[t]?.value??"",onChange:e=>s(t,e.target.value),placeholder:e.defaultValue?`${le("promptVariablePlaceholder")} (${le("default")}: ${e.defaultValue})`:le("promptVariablePlaceholder"),style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";}})]},e.raw))}), De("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ Re("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"6px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",fontSize:"14px",cursor:"pointer"},children:le("cancel")}), Re("button",{onClick:a,style:{padding:"8px 16px",borderRadius:"6px",border:"none",background:"var(--gh-primary, #4285f4)",color:"white",fontSize:"14px",cursor:"pointer",fontWeight:500},children:le("confirm")})]})]})})},Bb=e=>{const t=e.indexOf(":");if(-1===t)return {raw:e,name:e};const n=e.substring(0,t),r=e.substring(t+1);if(r.includes("|")){return {raw:e,name:n,options:r.split("|").filter(e=>e.length>0)}}return {raw:e,name:n,defaultValue:r}},$b=e=>{const t=/\{\{([^\s{}]+)\}\}/g,n=new Set,r=[];let o;for(;null!==(o=t.exec(e));){const e=o[1];n.has(e)||(n.add(e),r.push(Bb(e)));}return r},_b=e=>e.replace(/\r\n?/g,"\n"),Ob=e=>_b(e).split("\n").map(e=>e.trim()).filter(Boolean),zb=e=>"object"==typeof e&&null!==e,Fb=e=>!!zb(e)&&!("string"!=typeof e.id||"string"!=typeof e.title||"string"!=typeof e.content||"string"!=typeof e.category||void 0!==e.pinned&&"boolean"!=typeof e.pinned||void 0!==e.lastUsedAt&&"number"!=typeof e.lastUsedAt),Ub=({manager:e,adapter:t,onPromptSelect:n,selectedPromptId:r})=>{const o=Mi(e=>e.settings.features?.prompts?.doubleClickToSend??false),i=Mi(e=>e.settings.features?.prompts?.submitShortcut??"enter"),a=Mi(e=>e.settings.features?.prompts?.promptQueue??false),[s,l]=_([]),[c,d]=_([]),[u,h]=_(Ao),[g,p]=_(""),[m,f]=_(false),[b,y]=_(null),[v,x]=_(false),[w,S]=_({show:false,title:"",message:"",onConfirm:()=>{}}),[C,k]=_({show:false,title:"",defaultValue:"",onConfirm:()=>{}}),[T,A]=_(null),M=$(null),I=$(null),[N,R]=_({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),[D,P]=_({show:false,prompts:[]}),[q,B]=_(false),[O,z]=_({show:false,prompt:null}),F=$(null),U=$(null),H=$(null),[W,j]=_(null),[G,V]=_(null),Q=$(null),K=$(null),Z=E(()=>{const t=e.getPrompts(),n=e.getCategories();l(t),d(n),h(e=>{if(e===Ao)return e;if(!n.includes(e))return Ao;return t.some(t=>t.category===e)?e:Ao});},[e]),Y=E((t,n=false)=>{const r=e.getPrompts().find(e=>e.id===t);if(!r)return false;const o=$b(r.content);return 0!==o.length&&(R({show:true,prompt:r,variables:o,submitAfterInsert:n,enqueueAfterResolve:false,enqueueSplitByLine:false}),true)},[e]),X=E(t=>{const r=e.getPrompts().find(e=>e.id===t);return !!r&&(h(Ao),p(""),n?.(null),j(r.id),true)},[e,n]);L(()=>{const e=window,t=t=>{const r=t.detail,o=r?.promptId;if(!o)return;Y(o,Boolean(r?.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);};window.addEventListener("ophel:openPromptVariableDialog",t);const r=e.__ophelPendingPromptVariableDialog;if(r?.promptId){Y(r.promptId,Boolean(r.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);}return ()=>{window.removeEventListener("ophel:openPromptVariableDialog",t);}},[n,Y]),L(()=>{const e=window,t=t=>{const n=t.detail,r=n?.promptId;if(!r)return;X(r)&&(e.__ophelPendingLocatePrompt=null);};window.addEventListener("ophel:locatePrompt",t);const n=e.__ophelPendingLocatePrompt;if(n?.promptId){X(n.promptId)&&(e.__ophelPendingLocatePrompt=null);}return ()=>{window.removeEventListener("ophel:locatePrompt",t);}},[X]),L(()=>{Z();},[Z]),L(()=>()=>{null!==F.current&&window.clearTimeout(F.current),null!==U.current&&window.clearTimeout(U.current);},[]),L(()=>{q&&Q.current&&cd(Q.current,{size:14,color:"#6b7280"});},[q,b?.content]),L(()=>{O.show&&K.current&&cd(K.current,{size:14,color:"#6b7280"});},[O.show,O.prompt]);const J=(e,t,n)=>{S({show:true,title:e,message:t,onConfirm:n});},ee=async(e,t=false)=>{const n=$b(e.content);if(n.length>0)R({show:true,prompt:e,variables:n,submitAfterInsert:t,enqueueAfterResolve:false,enqueueSplitByLine:false});else {if(t)return void(await ne(e,e.content));await te(e,e.content);}},te=async(t,r)=>{await e.insertPrompt(r)?(e.updateLastUsed(t.id),n?.(t),Pi(`${le("inserted")}: ${t.title}`)):Pi(le("insertFailed"));},ne=async(r,o)=>{const a=await(async({adapter:e,manager:t,content:n,submitShortcut:r})=>{const o=n.trim();if(!o)return {status:"insert-failed"};const i=Mi.getState().settings.features?.prompts?.promptQueue??false;return e?.isGenerating()&&i?(Um.getState().enqueue(o),{status:"queued",count:1}):await t.insertPrompt(o)?await t.submitPrompt(r)?{status:"sent"}:{status:"send-failed"}:{status:"insert-failed"}})({adapter:t,manager:e,content:o,submitShortcut:i});if("insert-failed"!==a.status){if(e.updateLastUsed(r.id),"send-failed"===a.status)return Pi(le("promptSendFailed")),void n?.(r);n?.(null),"queued"!==a.status?Pi(`${le("promptSent")}: ${r.title}`):Pi(le("promptQueued",{count:String(a.count)}),2500);}else Pi(le("insertFailed"));},re=(t,n,r=false)=>{const o=(({content:e,splitByLine:t=false,context:n})=>{if(!Mi.getState().settings.features?.prompts?.promptQueue)return {status:"disabled"};const r=t?Ob(e):[e.trim()].filter(Boolean);if(0===r.length)return {status:"empty"};const o=Um.getState().enqueueMany(r);return 0===o.length?{status:"empty"}:{status:"queued",count:o.length}})({content:n,splitByLine:r,context:{}});"disabled"!==o.status?"empty"!==o.status?(e.updateLastUsed(t.id),Pi(le("promptQueued",{count:String(o.count)}),2500)):Pi(le("promptEnqueueEmpty"),2500):Pi(le("promptQueueEnableHint"),3e3);},oe=(e,t=false)=>{if(!a)return void Pi(le("promptQueueEnableHint"),3e3);const n=$b(e.content);n.length>0?R({show:true,prompt:e,variables:n,submitAfterInsert:false,enqueueAfterResolve:true,enqueueSplitByLine:t}):re(e,e.content,t);},ie=()=>{const t=D.prompts;e.setPrompts(t),Z(),P({show:false,prompts:[]}),Pi(le("promptImportSuccess").replace("{count}",t.length.toString()));},ae=()=>{const t=D.prompts,n=e.getPrompts(),r=new Set(n.map(e=>e.id)),o=t.filter(e=>r.has(e.id)),i=t.filter(e=>!r.has(e.id));o.forEach(t=>{e.updatePrompt(t.id,{title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),i.forEach(t=>{e.addPrompt({title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),Z(),P({show:false,prompts:[]});const a=`已合并:更新 ${o.length} 个,新增 ${i.length} 个`;Pi(le("promptMergeSuccess")?.replace("{updated}",o.length.toString()).replace("{added}",i.length.toString())||a);},se=async()=>{if(!b?.title||!b?.content)return void Pi(le("fillTitleContent"));const t=b.category||le("uncategorized");let n=false;if(b.id){const r=s.find(e=>e.id===b.id),o=r?.category;if(o&&o!==t&&u===o){0===s.filter(e=>e.category===o&&e.id!==b.id).length&&(n=true);}await e.updatePrompt(b.id,{title:b.title,content:b.content,category:t}),Pi(le("promptUpdated")),n&&h(t);}else await e.addPrompt({title:b.title,content:b.content,category:t}),Pi(le("promptAdded"));ce(),Z();},ce=E(()=>{f(false),y(null);},[]),de=E(()=>{x(false);},[]),ue=E(()=>{S(e=>({...e,show:false}));},[]),he=E(()=>{k(e=>({...e,show:false}));},[]),ge=E(()=>{z({show:false,prompt:null});},[]),pe=E(()=>{P({show:false,prompts:[]});},[]),me=E(()=>{R({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false});},[]),fe=E(()=>{V(null);},[]),be=e=>{if(e)y({...e});else {const e=u===Ao||u===Mo?c[0]||le("uncategorized"):u;y({title:"",content:"",category:e});}f(true);},ye=(t,n)=>{var r;n.stopPropagation(),n.preventDefault(),r=le("newCategoryName"),k({show:true,title:r,defaultValue:t,onConfirm:async n=>{n&&n.trim()&&n!==t&&(await e.renameCategory(t,n.trim()),Pi(le("categoryRenamedTo").replace("{name}",n.trim())),u===t&&h(n.trim()),Z());}});},ve=E(()=>{const e=[I.current,M.current?.getRootNode(),document],t=new Set;e.forEach(e=>{e&&!t.has(e)&&(t.add(e),e.querySelectorAll(".drop-above, .drop-below").forEach(e=>{e.classList.remove("drop-above","drop-below");}));}),I.current=null;},[]),xe=()=>{M.current&&M.current.classList.remove("dragging"),ve(),A(null),M.current=null;},we=(()=>{let t;if(u===Mo){if(t=e.getPrompts().filter(e=>e.lastUsedAt).sort((e,t)=>(t.lastUsedAt||0)-(e.lastUsedAt||0)).slice(0,10),g){const e=g.toLowerCase();t=t.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e));}}else t=e.filterPrompts(g,u);return u!==Mo&&(t=t.sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:0)),t})();L(()=>{if(!(C.show||w.show||v||m||O.show||D.show||N.show))return;const e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.(),C.show?he():w.show?ue():N.show?me():v?de():m?ce():O.show?ge():D.show&&pe());};return document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);}},[de,ue,ce,pe,ge,he,me,w.show,D.show,v,m,O.show,C.show,N.show]),L(()=>{if(!W)return;const e=H.current;if(!e)return;const t="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(W):W.replace(/["\\]/g,"\\$&"),n=e.querySelector(`.prompt-item[data-prompt-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),null!==U.current&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{j(e=>e===W?null:e),U.current=null;},2200));},[W,s,g,u]); return De("div",{className:"gh-prompts-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ De("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",display:"flex",gap:"8px",alignItems:"center"},children:[ Re("input",{type:"text",className:"prompt-search-input",placeholder:le("searchPlaceholder"),value:g,onChange:e=>p(e.target.value),style:{flex:1,padding:"6px 10px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"8px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}), Re(od,{content:le("promptImport"),children:Re("button",{onClick:()=>{const e=document.createElement("input");e.type="file",e.accept=".json",e.onchange=async e=>{const t=e.target.files?.[0];if(t)try{const e=await t.text(),n=(e=>{const t=Array.isArray(e)?e:zb(e)?Array.isArray(e.prompts)?e.prompts:zb(e.data)&&Array.isArray(e.data.prompts)?e.data.prompts:zb(e.state)&&Array.isArray(e.state.prompts)?e.state.prompts:null:null;return t&&t.every(Fb)?t:null})(JSON.parse(e));if(!n)return console.error("[Ophel] prompt import failed: unsupported prompt file format"),void Pi(le("promptImportFailed"));P({show:!0,prompts:n});}catch(RS){console.error("[Ophel] prompt import failed:",RS),Pi(le("promptImportFailed"));}},e.click();},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:Re(Ke,{size:16})})}), Re(od,{content:le("promptExport"),children:Re("button",{onClick:()=>{const t=e.getPrompts(),n=JSON.stringify(t,null,2),r=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${Nf}-prompts-${(new Date).toISOString().split("T")[0]}.json`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o),Pi(le("promptExportSuccess"));},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:Re(Ze,{size:16})})})]}), De("div",{style:{display:"flex",alignItems:"center",background:"var(--gh-bg, white)",borderBottom:"1px solid var(--gh-border, #e5e7eb)",userSelect:"none"},children:[ De("div",{className:"prompt-category-bar",style:{flex:1,minWidth:0,padding:"6px 0 6px 10px",display:"flex",gap:"5px",flexWrap:"nowrap",overflowX:"auto",scrollbarWidth:"none"},onWheel:e=>{0!==e.deltaY&&(e.currentTarget.scrollLeft+=e.deltaY);},children:[ Re("span",{onClick:()=>h(Ao),style:{padding:"4px 10px",background:u===Ao?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"12px",fontSize:"12px",color:u===Ao?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:u===Ao?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:le("allCategory")}),c.map(e=>{const t=(e=>{let t=0;for(let n=0;nh(e),style:{padding:"4px 10px",background:u===e?"var(--gh-primary, #4285f4)":`var(--gh-category-${t})`,borderRadius:"12px",fontSize:"12px",color:u===e?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:u===e?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})},e)})]}), De("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"6px 8px",flexShrink:0,borderLeft:"1px solid var(--gh-border, #e5e7eb)"},children:[ Re(od,{content:le("promptRecentUsed"),children:Re("span",{onClick:()=>h(Mo),style:{padding:"3px 6px",display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1,background:u===Mo?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"10px",color:u===Mo?"white":"#4b5563",cursor:"pointer",border:u===Mo?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:Re(Kt,{size:14})})}),c.length>0&&Re(od,{content:le("manageCategory"),children:Re("button",{onClick:()=>x(true),style:{padding:"3px 6px",background:"transparent",border:"1px dashed var(--gh-border, #d1d5db)",borderRadius:"10px",color:"var(--gh-text-secondary, #9ca3af)",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Re(Fe,{size:13})})})]})]}), Re("div",{ref:H,style:{flex:1,overflowY:"auto",padding:"8px",scrollbarWidth:"none"},children:0===we.length?Re("div",{style:{textAlign:"center",padding:"40px 20px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"14px"},children:"暂无提示词"}):we.map(t=>{const n=r===t.id,i=W===t.id,a=n||i; return De("div",{"data-prompt-id":t.id,className:`prompt-item ${a?"selected":""} ${i?"located":""} ${T===t.id?"dragging":""}`,onClick:()=>{return e=t,j(null),void(o?(null!==F.current&&(window.clearTimeout(F.current),F.current=null),F.current=window.setTimeout(()=>{F.current=null,ee(e);},340)):ee(e));var e;},onDoubleClick:()=>{return e=t,null!==F.current&&(window.clearTimeout(F.current),F.current=null),void(o&&ee(e,true));var e;},draggable:true,onDragStart:e=>((e,t,n)=>{e.target.closest('button, input, textarea, select, [role="button"], [data-no-row-drag="true"]')?e.preventDefault():(A(t),M.current=n,I.current=n.getRootNode(),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",t),n.classList.add("dragging"));})(e,t.id,e.currentTarget),onDragOver:e=>((e,t)=>{if(e.preventDefault(),e.dataTransfer.dropEffect="move",!T||T===t)return;const n=e.currentTarget,r=n.getBoundingClientRect(),o=r.top+r.height/2,i=n.getRootNode();I.current=i,ve(),e.clientY(async(t,n)=>{if(t.preventDefault(),!T||T===n)return void xe();const r=e.getPrompts(),o=r.findIndex(e=>e.id===T),i=r.findIndex(e=>e.id===n);if(-1===o||-1===i)return void xe();const a=[...r],[s]=a.splice(o,1),l=t.currentTarget.getBoundingClientRect(),c=t.clientYe.id===n);oe.id)),Pi(le("orderUpdated")),Z(),xe();})(n,t.id),style:{background:a?"linear-gradient(135deg, #e8f0fe 0%, #f1f8e9 100%)":"var(--gh-bg, white)",border:a?"1px solid var(--gh-primary, #4285f4)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",marginBottom:"8px",cursor:"pointer",transition:"all 0.2s",position:"relative",userSelect:"none"},children:[ De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[ Re("div",{style:{fontWeight:600,fontSize:"14px",color:"var(--gh-text, #1f2937)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:"8px"},children:t.title}), Re("span",{style:{fontSize:"11px",padding:"2px 6px",background:"var(--gh-hover, #f3f4f6)",borderRadius:"4px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:t.category||le("uncategorized")})]}), Re("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #6b7280)",lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.content}), De("div",{className:"prompt-item-actions",style:{position:"absolute",top:"8px",right:"8px",gap:"2px"},children:[ Re(od,{content:t.pinned?le("promptUnpin"):le("promptPin"),children:Re("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),e.togglePin(t),Z();})(t.id,n),className:"prompt-action-btn"+(t.pinned?" active":""),children:Re(Ut,{size:16,filled:t.pinned})})}), Re(od,{content:le("promptMarkdownPreview"),children:Re("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),z({show:true,prompt:t});},className:"prompt-action-btn",children:Re(Ht,{size:16})})}), Re(od,{content:le("copy"),children:Re("button",{onClick:e=>(async(e,t)=>{t.stopPropagation(),t.preventDefault();try{await navigator.clipboard.writeText(e),Pi(le("copied"));}catch{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Pi(le("copied"));}})(t.content,e),className:"prompt-action-btn",children:Re(It,{size:16})})}), Re(od,{content:le("more"),children:Re("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),V({prompt:t,anchorEl:e.currentTarget});},className:"prompt-action-btn",children:Re(Nt,{size:16})})}), Re(od,{content:le("edit"),children:Re("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),be(t);},className:"prompt-action-btn",children:Re(zt,{size:16})})}), Re(od,{content:le("delete"),children:Re("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),J(le("confirmDelete"),"确定删除该提示词?",async()=>{await e.deletePrompt(t),Pi(le("deleted")),Z();});})(t.id,n),className:"prompt-action-btn danger",children:Re(Ft,{size:16})})})]})]},t.id)})}), Re("div",{style:{padding:"12px"},children:De("button",{onClick:()=>be(),style:{width:"100%",padding:"10px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",boxShadow:"var(--gh-btn-shadow)",transition:"transform 0.2s, box-shadow 0.2s"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Re("span",{children:"+"}), Re("span",{children:le("addPrompt")})]})}),m?Kc( Re("div",{className:"prompt-modal gh-interactive",...ns,style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:De("div",{className:"prompt-modal-content",onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"500px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow, 0 20px 50px rgba(0,0,0,0.3))"},children:[ Re("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:le(b?.id?"editPrompt":"addNewPrompt")}), De("div",{style:{marginBottom:"16px"},children:[ Re("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:le("title")}), Re("input",{type:"text",value:b?.title||"",onChange:e=>y({...b,title:e.target.value}),style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), De("div",{style:{marginBottom:"16px"},children:[ Re("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:le("category")}), Re("input",{type:"text",value:b?.category||"",onChange:e=>y({...b,category:e.target.value}),placeholder:le("categoryPlaceholder"),style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}),c.length>0&&Re("div",{style:{marginTop:"6px",display:"flex",gap:"4px",flexWrap:"wrap",userSelect:"none"},children:c.map(e=>Re("span",{onClick:()=>y({...b,category:e}),style:{padding:"2px 8px",fontSize:"11px",background:b?.category===e?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:b?.category===e?"var(--gh-text-on-primary, white)":"var(--gh-text-secondary, #6b7280)",borderRadius:"10px",cursor:"pointer",transition:"all 0.15s"},children:e},e))})]}), Re("div",{style:{marginBottom:"16px"},children:De("div",{children:[ De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[ Re("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)"},children:le("content")}), Re("button",{onClick:()=>B(!q),style:{padding:"2px 8px",fontSize:"12px",background:q?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:q?"white":"var(--gh-text-secondary, #6b7280)",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"4px",cursor:"pointer"},children:le("promptMarkdownPreview")})]}), Re("textarea",{value:b?.content||"",onChange:e=>y({...b,content:e.target.value}),style:{width:"100%",minHeight:"120px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)",display:q?"none":"block"}}),q&&De(Ne,{children:[ Re("div",{className:"gh-markdown-preview",style:{width:"100%",minHeight:"120px",maxHeight:"200px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text, #1f2937)",overflowY:"auto",lineHeight:1.6},ref:Q,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{ld(t,{size:14});});}},dangerouslySetInnerHTML:{__html:Ad($l(b?.content||""))}}), Re("style",{children:_l()})]})]})}), De("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end",marginTop:"24px"},children:[ Re(zf,{variant:"ghost",onClick:ce,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("cancel")}), Re(zf,{variant:"primary",onClick:se,children:le(b?.id?"save":"add")})]})]})}),document.body):null,v?Kc( Re("div",{className:"prompt-modal gh-interactive",...ns,style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:De("div",{onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"400px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3))"},children:[ Re("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:le("categoryManage")}), Re("div",{style:{maxHeight:"300px",overflowY:"auto"},children:0===c.length?Re("div",{style:{textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)",padding:"20px"},children:le("categoryEmpty")}):c.map(t=>{const n=s.filter(e=>e.category===t).length; return De("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ De("div",{children:[ Re("div",{style:{fontWeight:500,color:"var(--gh-text, #374151)"},children:t}), De("div",{style:{fontSize:"12px",color:"var(--gh-text-tertiary, #9ca3af)"},children:[n," ",le("promptCountSuffix")]})]}), De("div",{style:{display:"flex",gap:"8px"},children:[ Re(od,{content:le("rename"),children:Re(zf,{size:"sm",onClick:e=>ye(t,e),style:{color:"var(--gh-primary, #4285f4)"},children:le("rename")})}), Re(od,{content:le("delete"),children:Re(zf,{size:"sm",onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),J(le("confirmDeleteCategory"),le("confirmDeleteCategoryMsg").replace("{name}",t),async()=>{await e.deleteCategory(t),Pi(le("categoryDeletedMsg").replace("{name}",t)),u===t&&h(Ao),Z();});})(t,n),style:{border:"1px solid var(--gh-border-danger, #fecaca)",background:"var(--gh-bg-danger, #fef2f2)",color:"var(--gh-text-danger, #ef4444)"},children:le("delete")})})]})]},t)})}), Re("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:Re(zf,{variant:"ghost",onClick:de,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("close")})})]})}),document.body):null,O.show&&O.prompt?Kc( Re("div",{className:"prompt-preview-modal gh-interactive",...ns,onClick:e=>{e.target===e.currentTarget&&ge();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001,animation:"fadeIn 0.2s ease-out"},children:De("div",{style:{width:"90%",maxWidth:"600px",maxHeight:"80vh",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",overflow:"hidden",display:"flex",flexDirection:"column",animation:"slideUp 0.3s ease-out"},children:[ De("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ De("div",{children:[ Re("div",{style:{fontSize:"16px",fontWeight:600,color:"var(--gh-text, #1f2937)"},children:O.prompt.title}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:O.prompt.category})]}), Re("button",{onClick:ge,style:{width:"28px",height:"28px",border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"6px",cursor:"pointer",fontSize:"16px",display:"flex",alignItems:"center",justifyContent:"center"},children:Re($e,{size:16})})]}), Re("div",{className:"gh-markdown-preview",style:{flex:1,padding:"20px",overflowY:"auto"},ref:K,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{ld(t,{size:14});});}},dangerouslySetInnerHTML:{__html:Ad($l(O.prompt.content))}}), Re("style",{children:_l()})]})}),document.body):null,D.show?Kc( Re("div",{className:"import-dialog gh-interactive",...ns,onClick:e=>{e.target===e.currentTarget&&pe();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001},children:De("div",{style:{width:"90%",maxWidth:"400px",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",padding:"24px"},children:[ Re("div",{style:{fontSize:"16px",fontWeight:600,marginBottom:"12px",color:"var(--gh-text)"},children:le("promptImportTitle")}), De("div",{style:{fontSize:"14px",color:"var(--gh-text-secondary)",marginBottom:"20px",lineHeight:1.6},children:[le("promptImportMessage2").replace("{count}",D.prompts.length.toString()), De("ul",{style:{margin:"8px 0 0 0",paddingLeft:"20px"},children:[ Re("li",{children:le("promptImportOverwriteDesc")}), Re("li",{children:le("promptImportMergeDesc")})]})]}), De("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end"},children:[ Re(zf,{variant:"ghost",onClick:pe,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("cancel")}), Re(zf,{variant:"ghost",onClick:ae,style:{background:"var(--gh-primary-light, #e3f2fd)",color:"var(--gh-primary, #4285f4)"},children:le("promptMerge")}), Re(zf,{variant:"primary",onClick:ie,children:le("promptOverwrite")})]})]})}),document.body):null,w.show&&Re(_f,{title:w.title,message:w.message,danger:true,closeOnOverlayClick:false,onConfirm:()=>{ue(),w.onConfirm();},onCancel:ue}),C.show&&Re(Of,{title:C.title,defaultValue:C.defaultValue,closeOnOverlayClick:false,onConfirm:e=>{he(),C.onConfirm(e);},onCancel:he}),N.show&&Re(qb,{variables:N.variables,onConfirm:async e=>{const{prompt:t,submitAfterInsert:n,enqueueAfterResolve:r,enqueueSplitByLine:o}=N;if(!t)return;const i=((e,t)=>e.replace(/\{\{([^\s{}]+)\}\}/g,(e,n)=>n in t?t[n]:e))(t.content,e);R({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e());});}),n?await ne(t,i):r?re(t,i,o):await te(t,i);},onCancel:me}),G&&De(db,{anchorEl:G.anchorEl,onClose:fe,children:[ Re(ub,{onClick:()=>{oe(G.prompt),fe();},children:De("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re(sn,{size:14}), Re("span",{children:le("promptAddToQueue")})]})}), Re(ub,{onClick:()=>{oe(G.prompt,true),fe();},children:De("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re(ln,{size:14}), Re("span",{children:le("promptSplitLinesToQueue")})]})})]}), Re("style",{children:"\n @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n "})]})},Hb=({onClose:e,isOpen:t,isLauncherPeeking:n=false,launcherPeekAnchorRect:r=null,isScrolling:o,promptManager:i,conversationManager:a,outlineManager:s,adapter:l,onThemeToggle:c,themeMode:d,selectedPromptId:u,onPromptSelect:h,edgeSnapState:g,isEdgePeeking:p=false,onEdgeSnap:m,onUnsnap:f,onInteractionStateChange:b,onOpenSettings:y,onMouseEnter:v,onMouseLeave:x})=>{const w=E(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:S,updateNestedSetting:C,setSettings:k}=Mi(),T=S||ti,A=T.features?.order||ti.features.order,M=l?.getSiteId()||"_default",I=ni(T,M),N=d||("dark"===I.mode?"dark":"light"),R="light"===N?I.lightStyleId||"google-gradient":I.darkStyleId||"classic-dark",D="dark"===N?"brand":"currentColor",B=Array.isArray(T.theme?.customStyles)?T.theme.customStyles.find(e=>e.id===R):null,{panelRef:z,headerRef:F}=function(e={}){const{edgeSnapHide:t=false,edgeSnapState:n,snapThreshold:r=30,onEdgeSnap:o,onUnsnap:i}=e,a=$(null),s=$(null),l=$(false),c=$(false),d=$({x:0,y:0}),u=$(null),h=$(null),g=$(false),p=$(null),m=E((e,t,n,r)=>{const o=Math.max(r,t-n-r),i=Math.max(1,o-r);return Math.min(1,Math.max(0,(e-r)/i))},[]),f=E((e,t,n,r)=>{const o=Math.max(r,t-n-r);return r+e*Math.max(1,o-r)},[]),b=E((e,t=window.innerWidth,n=window.innerHeight)=>({xRatio:m(e.left,t,e.width,0),yRatio:m(e.top,n,e.height,sb)}),[m]),y=E(e=>{if(e.target.closest(".gh-panel-controls"))return;const t=a.current;if(!t)return;e.preventDefault(),u.current=n||null;const r=t.getBoundingClientRect();d.current={x:e.clientX-r.left,y:e.clientY-r.top},c.current=false,l.current=true,document.body.style.userSelect="none";},[n]),v=E(e=>{if(!l.current)return;const t=a.current;t&&(e.preventDefault(),c.current||(c.current=true,u.current&&(i?.(),u.current=null),t.classList.remove("edge-snapped-left","edge-snapped-right"),t.style.right="auto",t.style.transform="none",g.current=false,t.classList.add("dragging")),t.style.left=e.clientX-d.current.x+"px",t.style.top=e.clientY-d.current.y+"px");},[i]),x=E((e,t,n=300,r)=>{const o=a.current;if(!o)return;null!==h.current&&(cancelAnimationFrame(h.current),h.current=null);const i=parseFloat(o.style.left)||o.getBoundingClientRect().left,s=parseFloat(o.style.top)||o.getBoundingClientRect().top,l=performance.now(),c=a=>{const d=a-l;let u=Math.min(d/n,1);u=1-Math.pow(1-u,3);const g=i+(e-i)*u,p=s+(t-s)*u;o.style.left=`${g}px`,o.style.top=`${p}px`,u<1?h.current=requestAnimationFrame(c):(h.current=null,r?.());};h.current=requestAnimationFrame(c);},[]),w=E(()=>{if(!l.current)return;const e=a.current,n=c.current;if(l.current=false,u.current=null,document.body.style.userSelect="",e?.classList.remove("dragging"),n&&e&&!t){const t=e.getBoundingClientRect();p.current=b(t);}if(t&&n&&e){const t=e.getBoundingClientRect(),n=window.innerWidth,i=t.width,a=t.top;t.left{o?.("left");}):n-t.right{o?.("right");}):p.current=b(t,n,window.innerHeight);}},[t,o,r,x,b]),S=E(()=>{const e=a.current;if(!e)return;if(n)return;const t=window.innerWidth,r=window.innerHeight,o=e.getBoundingClientRect();if(!p.current){const n=e.style.left;if(!Boolean(n&&"auto"!==n&&"none"===e.style.transform)){const t="none"!==e.style.transform,n=o.height+20<=r;if((t||g.current)&&n)return void(g.current&&(e.style.top="50%",e.style.transform="translateY(-50%)",g.current=false));t&&(g.current=true);let i=o.top;return i+o.height+sb>r&&(i=r-o.height-sb),i.5&&(e.style.top=i+"px",e.style.transform="none"))}p.current=b(o,t,r);}const i=p.current;let s=i?f(i.xRatio,t,o.width,0):o.left,l=i?f(i.yRatio,r,o.height,sb):o.top;s+o.width+0>t&&(s=t-o.width-0),l+o.height+sb>r&&(l=r-o.height-sb),s<0&&(s=0),l.5||Math.abs(l-o.top)>.5)&&(e.style.left=s+"px",e.style.top=l+"px",e.style.right="auto",e.style.transform="none");},[n,f,b]);return L(()=>{n&&(p.current=null);},[n]),L(()=>{const e=s.current;if(e)return e.addEventListener("mousedown",y),document.addEventListener("mousemove",v),document.addEventListener("mouseup",w),window.addEventListener("resize",S),()=>{e.removeEventListener("mousedown",y),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",w),window.removeEventListener("resize",S),null!==h.current&&(cancelAnimationFrame(h.current),h.current=null);}},[y,v,w,S]),{panelRef:a,headerRef:s}}({edgeSnapHide:!n&&"edge-snap"===T.panel?.panelMode,edgeSnapState:n?null:g,snapThreshold:T.panel?.edgeSnapThreshold??30,onEdgeSnap:m,onUnsnap:f}),U=$(T.panel?.panelMode),H=$(null),W=$(null);P(()=>{const e=T.panel?.panelMode,t=U.current;if(U.current=e,t===e||!z.current)return;const n=z.current;if(n.classList.remove("dragging"),"edge-snap"===t&&"floating"===e){n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="";const e=H.current;H.current=null;const t=e??n.getBoundingClientRect(),r=t?Math.min(t.right,window.innerWidth)-Math.max(t.left,0):0;if(t.width>0&&r>=.5*t.width)n.style.left=`${t.left}px`,n.style.top=`${t.top}px`,n.style.right="auto",n.style.transform="none";else {const e=T.panel?.defaultPosition??"right",r=T.panel?.defaultEdgeDistance??0,o=t?t.top:null;null!==o&&o>=0&&o{n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="",W.current=null;},400);}return ()=>{W.current&&(clearTimeout(W.current),W.current=null),n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="";}},[T.panel?.panelMode,T.panel?.defaultEdgeDistance,T.panel?.defaultPosition,z]);const j=$(T.panel?.defaultEdgeDistance),G=$(T.panel?.defaultPosition);P(()=>{const e=T.panel?.defaultEdgeDistance,t=j.current;j.current=e;const n=T.panel?.defaultPosition,r=G.current;G.current=n;if((e!==t||n!==r)&&z.current&&"floating"===T.panel?.panelMode){const t=z.current,r=e??0;"left"===(n??"right")?(t.style.left=`${r}px`,t.style.right="auto"):(t.style.right=`${r}px`,t.style.left="auto"),t.style.top="50%",t.style.transform="translateY(-50%)";}},[T.panel?.defaultEdgeDistance,T.panel?.defaultPosition,T.panel?.panelMode,z]);const V=T.panel?.defaultPosition??"right",Q=T.panel?.defaultEdgeDistance??40,K="edge-snap"===(T.panel?.panelMode??"edge-snap"),Z=T.panel?.width??320,Y=T.panel?.height??85,X=q(()=>{if(!n||!r||"undefined"==typeof window)return {};const e=window.innerWidth,t=window.innerHeight,o=10,i=Math.max(500,t*Y/100),a=r.left+r.width/2,s=r.top+r.height/2,l=a>e/2?r.left-Z:r.right,c=Math.max(o,e-Z-o),d=Math.min(Math.max(l,o),c),u=s-i/2,h=Math.max(o,t-i-o);return {left:`${d}px`,right:"auto",top:`${Math.min(Math.max(u,o),h)}px`,transform:"none"}},[n,r,Y,Z]),J=n?X:K?{left:"",right:""}:"left"===V?{left:`${Q}px`,right:"auto"}:{right:`${Q}px`,left:"auto"},[ee,te]=_(false),[ne,re]=_(false),oe=T.hasSeenOphelAdvancedGuide??false,ie="shortcutNotSet",ae=le(ie),se=ae===ie?"未设置":ae,ce=e=>{e&&!oe&&k&&k({hasSeenOphelAdvancedGuide:true});},de=E(e=>!(e instanceof Element)||!e.closest('.gh-panel-controls, [data-no-header-press-hint="true"]'),[]),ue=E(()=>{re(false);},[]),he=E(e=>{de(e.target)?re(true):ue();},[ue,de]),ge=q(()=>ab(T.shortcuts?.keybindings,ur(),se),[T.shortcuts?.keybindings,T.language,se]),pe=$(null),fe=E(()=>{oe||(pe.current&&clearTimeout(pe.current),te(true),ce(true));},[oe,ce]),be=E(()=>{pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{te(false);},300);},[]),ye=E(e=>{const t=e.target;if(t instanceof Element&&t.closest(".gh-panel-controls"))return;const n=T.panel?.panelMode??"edge-snap";"edge-snap"===n&&z.current&&(H.current=z.current.getBoundingClientRect()),C("panel","panelMode","edge-snap"===n?"floating":"edge-snap");},[T.panel?.panelMode,C]);L(()=>()=>{pe.current&&clearTimeout(pe.current);},[]);const ve=E(()=>{te(false);},[]),xe=e=>e&&e.length>0?e[0]:hr,[we,Se]=_(hr),[Ce,ke]=_(false);L(()=>{S&&!Ce&&(Se(xe(S.features?.order)),ke(true));},[S,Ce]),L(()=>{Ce&&A&&A.length>0&&(A.includes(we)||Se(xe(A)));},[A,Ce,we]),L(()=>{const e=()=>{Se(gr);},t=()=>{Se(pr);},n=e=>{const t=e.detail?.index;"number"==typeof t&&A[t]&&Se(A[t]);};return window.addEventListener("ophel:locateOutline",e),window.addEventListener("ophel:searchOutline",e),window.addEventListener("ophel:locateConversation",t),window.addEventListener("ophel:switchTab",n),()=>{window.removeEventListener("ophel:locateOutline",e),window.removeEventListener("ophel:searchOutline",e),window.removeEventListener("ophel:locateConversation",t),window.removeEventListener("ophel:switchTab",n);}},[A]),L(()=>{if(!t)return;const e=z.current;return e?as(e):void 0},[t,z]);const Te=null!==O(lf,cf),[Ee,Ae]=_(0);L(()=>{if(0===Ee)return;const e=setTimeout(()=>Ae(0),400);return ()=>clearTimeout(e)},[Ee]);const[Me,Ie]=_(false),[Le,Be]=_(""),$e=$(false),Oe=E(async()=>{$e.current=false;const e=new AbortController,t=setInterval(()=>{$e.current&&e.abort();},100);let n=setTimeout(()=>{$e.current||(Ie(true),Be(le("loadingHistory")));},1600);try{const t=await Af({adapter:l||null,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{Be(`${le("loadingHistory")} ${e}`);}});sf(t.previousScrollTop),n&&(clearTimeout(n),n=null),Ie(!1),Be(""),t.success&&!t.silent&&Pi(le("historyLoaded"),2e3);}finally{clearInterval(t),n&&clearTimeout(n);}},[l]),Ue=E(()=>{$e.current=true;},[]),je=E(async()=>{const{previousScrollTop:e}=await ff(l||null);sf(e);},[l]),Ve=E(async()=>{const e=af();if(null===e)return;Ae(e=>e+1);const t=(await vf(l||null)).scrollTop;await bf(l||null,e),sf(t);},[l]),Ke=E(async()=>{const e=await vf(l||null);sf(e.scrollTop);},[l]);if(!t)return null;const Ze=A.filter(e=>e!==mr&&((e!==hr||false!==T.features?.prompts?.enabled)&&((e!==pr||false!==T.features?.conversations?.enabled)&&(e!==gr||false!==T.features?.outline?.enabled)))); return De(Ne,{children:[ Re(rb,{isVisible:Me,text:Le,onStop:Ue}), De("div",{ref:z,onMouseEnter:v,onMouseLeave:x,className:`gh-main-panel gh-interactive ${!n&&g?`edge-snapped-${g}`:""} ${n?"launcher-peek":""} ${p?"edge-peek":""} ${o?"scroll-hidden":""}`,style:{position:"fixed",top:"50%",...J,transform:n?"none":"translateY(-50%)",width:`${Z}px`,height:`${Y}vh`, // @ts-ignore - 注入 CSS 变量供吸附计算使用 "--panel-width":`${Z}px`,minHeight:"500px",backgroundColor:"var(--gh-bg, #ffffff)",backgroundImage:"var(--gh-bg-image, none)",backgroundBlendMode:"overlay",animation:"var(--gh-bg-animation, none)",borderRadius:"12px",boxShadow:"var(--gh-shadow, 0 10px 40px rgba(0,0,0,0.15))",display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)",zIndex:9999,fontFamily:me},children:[B?Re("style",{children:B.css}):null, De("div",{ref:F,onPointerDown:he,onPointerUp:ue,onPointerLeave:ue,onPointerCancel:ue,onDoubleClick:ye,className:"gh-panel-header",style:{position:"relative",padding:"10px 14px",borderRadius:"12px 12px 0 0",display:"flex",alignItems:"center",justifyContent:"space-between",userSelect:"none"},children:[ De("div",{style:{position:"relative"},onMouseEnter:fe,onMouseLeave:be,children:[ De("div",{className:"gh-interactive",role:"button",tabIndex:0,"aria-label":le("panelTitle"),"data-tip-target":"header-title","data-no-header-press-hint":"true",onClick:()=>{te(e=>!e),ce(true);},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),te(e=>!e));},style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer",position:"relative",border:"none",background:"transparent",padding:0,color:"inherit"},children:[ De("div",{style:{position:"relative",display:"flex",alignItems:"center"},children:[ Re(Zt,{size:18,color:D}),!oe&&Re("div",{style:{position:"absolute",top:"-2px",right:"-2px",width:"6px",height:"6px",backgroundColor:"var(--gh-danger, #ef4444)",borderRadius:"50%",boxShadow:"0 0 0 2px var(--gh-bg, #ffffff)",animation:"pulse-red 2s infinite"}})]}), Re("span",{style:{fontSize:"18px",fontWeight:600,userSelect:"none"},children:le("panelTitle")})]}), Re(ob,{isOpen:ee,onClose:ve,tips:ge,onMouseEnter:fe,onMouseLeave:be})]}), De("div",{className:"gh-panel-controls","data-no-header-press-hint":"true",style:{display:"flex",gap:"1px",alignItems:"center"},children:[ Re(od,{content:"edge-snap"===(T.panel?.panelMode??"edge-snap")?le("pinPanel"):le("snapToEdge"),children:Re("button",{type:"button","aria-label":"edge-snap"===(T.panel?.panelMode??"edge-snap")?le("pinPanel"):le("snapToEdge"),onClick:()=>{const e=T.panel?.panelMode??"edge-snap";"edge-snap"===e&&z.current&&(H.current=z.current.getBoundingClientRect()),C("panel","panelMode","edge-snap"===e?"floating":"edge-snap");},className:"gh-header-icon-btn",children:"edge-snap"===(T.panel?.panelMode??"edge-snap")?Re(en,{size:14}):Re(Jt,{size:14})})}),c&&Re(od,{content:le("toggleTheme"),children:Re("button",{onClick:e=>{c?.(w(e.currentTarget));},className:"gh-header-icon-btn",children:Re("dark"===d?Pe:qe,{size:14})})}),T.tab?.openInNewTab&&Re(od,{content:le("newTabTooltip"),children:Re("button",{onClick:()=>window.open(window.location.origin,"_blank"),className:"gh-header-icon-btn",children:Re(ze,{size:14})})}), Re(od,{content:le("tabSettings"),children:Re("button",{"data-tip-target":"settings-btn",onClick:()=>{y?.();},className:"gh-header-icon-btn",children:Re(Fe,{size:14})})}), Re(od,{content:le("collapse"),children:Re("button",{onClick:e,"aria-label":le("collapse"),className:"gh-header-icon-btn",children:Re(He,{size:14})})})]})]}), De("div",{style:{position:"absolute",top:"56px",left:"50%",width:"max-content",maxWidth:"85%",transform:`translate(-50%, ${ne?"8px":"-4px"})`,opacity:ne?1:0,pointerEvents:"none",transition:"all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)",background:"var(--gh-bg-secondary, rgba(255, 255, 255, 0.85))",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"var(--gh-text, #1f2937)",border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",padding:"6px 12px",borderRadius:"12px",fontSize:"12px",fontWeight:500,display:"flex",textAlign:"left",alignItems:"flex-start",gap:"8px",boxShadow:"var(--gh-shadow-lg, 0 8px 24px rgba(0,0,0,0.12))",zIndex:10},children:[ Re("span",{style:{fontSize:"14px",flexShrink:0,marginTop:"1px"},children:"👻"}), Re("span",{style:{lineHeight:"1.5"},children:le("tip1",{modifier:ur()?"⌘ Cmd":"Ctrl"})})]}), Re("div",{className:"gh-panel-tabs",style:{display:"flex",borderBottom:"1px solid var(--gh-border, #e5e7eb)",padding:"0",background:"var(--gh-bg-secondary, #f9fafb)"},children:Ze.map(e=>{let t=null;return e===gr?t=We:e===hr?t=Ge:e===pr&&(t=Qe),De("button",{"data-tip-target":e===gr?"outline-tab":e===pr?"conversations-tab":e===hr?"prompts-tab":void 0,onClick:()=>Se(e),style:{flex:1,padding:"7px 8px",border:"none",background:"transparent",borderBottom:we===e?"3px solid var(--gh-primary, #4285f4)":"3px solid transparent",color:we===e?"var(--gh-primary, #4285f4)":"var(--gh-text-secondary, #6b7280)",fontWeight:we===e?600:400,cursor:"pointer",fontSize:"13px",whiteSpace:"nowrap",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",transition:"all 0.2s"},children:[ Re("span",{style:{display:"flex",alignItems:"center"},children:t&&Re(t,{size:16})}), Re("span",{children:le(`tab${e.charAt(0).toUpperCase()+e.slice(1)}`)})]},e)})}), De("div",{className:"gh-panel-content",style:{flex:1,overflowY:"auto",padding:"0",scrollbarWidth:"none",msOverflowStyle:"none"},children:[we===hr&&Re(Ub,{manager:i,adapter:l,selectedPromptId:u,onPromptSelect:h}),we===pr&&Re(vb,{manager:a,onInteractionStateChange:b}),we===gr&&Re(Pb,{manager:s,conversationManager:a,onJumpBefore:Ke,isCodexOpen:ee})]}), De("div",{className:"gh-panel-footer",style:{display:"flex",justifyContent:"space-around",alignItems:"center",padding:"8px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)"},children:[ Re(od,{content:le("scrollTop"),triggerStyle:{flex:1,maxWidth:"120px"},children:De("button",{className:"gh-interactive scroll-nav-btn",onClick:Oe,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Re(rt,{size:14}), Re("span",{children:le("scrollTop")})]})}), Re(od,{content:le(Te?"jumpToAnchor":"noAnchor"),triggerStyle:{flex:"0 0 32px"},children:Re("button",{className:"gh-interactive scroll-nav-btn anchor-btn",onClick:Ve,disabled:!Te,style:{width:"32px",height:"32px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"50%",padding:0,cursor:Te?"pointer":"default",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)",opacity:Te?1:.4},onMouseEnter:e=>{if(Te){e.currentTarget.style.transform="scale(1.1)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(360deg)");}},onMouseLeave:e=>{e.currentTarget.style.transform="scale(1)",e.currentTarget.style.boxShadow=Te?"var(--gh-btn-shadow)":"none";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(0deg)");},children:Re("span",{className:"anchor-tap-wrapper"+(Ee>0?" is-tapping":""),onAnimationEnd:()=>Ae(0),style:{display:"flex",alignItems:"center",justifyContent:"center"},children:Re("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)"},children:Re(_e,{size:14})})},Ee)})}), Re(od,{content:le("scrollBottom"),triggerStyle:{flex:1,maxWidth:"120px"},children:De("button",{className:"gh-interactive scroll-nav-btn",onClick:je,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Re(ot,{size:14}), Re("span",{children:le("scrollBottom")})]})})]})]})]})};e('.gh-queue-capsule{position:fixed;z-index:99998;display:flex;align-items:center;gap:6px;padding:6px 14px;border-radius:20px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);color:var(--gh-text, #1f2937);font-size:13px;font-weight:500;cursor:pointer;-webkit-user-select:none;user-select:none;box-shadow:0 2px 12px #00000014;transition:all .2s ease;font-family:var( --gh-font-family, "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif )}.gh-queue-capsule:hover{transform:translateY(-1px);background:var(--gh-bg-secondary, #f9fafb);box-shadow:0 4px 16px #0000001f}.gh-queue-capsule-icon{font-size:14px;line-height:1}.gh-queue-capsule-badge{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4);font-size:11px;font-weight:600}.gh-queue-panel{position:fixed;z-index:99999;width:420px;max-width:calc(100vw - 40px);max-height:400px;border-radius:16px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 8px 32px #0000001f,0 2px 8px #0000000f;display:flex;flex-direction:column;overflow:hidden;font-family:var( --gh-font-family, "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif )}.gh-queue-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-header-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-header-actions{display:flex;align-items:center;gap:4px}.gh-queue-header-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border:none;border-radius:6px;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-header-btn:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-list{flex:1;overflow-y:auto;padding:8px;max-height:180px}.gh-queue-empty{display:flex;align-items:center;justify-content:center;padding:16px;color:var(--gh-text-tertiary, #9ca3af);font-size:13px}.gh-queue-item{display:flex;align-items:flex-start;gap:8px;padding:8px 10px;border-radius:8px;margin-bottom:4px;background:var(--gh-bg-secondary, #f9fafb);transition:background .15s}.gh-queue-item:hover{background:var(--gh-bg-tertiary, #f3f4f6)}.gh-queue-item-index{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--gh-accent, #4285f4);color:#fff;font-size:11px;font-weight:600;margin-top:1px}.gh-queue-item-content{flex:1;min-width:0;font-size:13px;line-height:1.5;color:var(--gh-text, #1f2937);word-break:break-word;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.gh-queue-item-actions{flex-shrink:0;display:flex;align-items:center;gap:4px;opacity:0;transition:opacity .15s}.gh-queue-item:hover .gh-queue-item-actions{opacity:1}.gh-queue-item-remove,.gh-queue-item-force-send,.gh-queue-item-edit{display:flex;align-items:center;justify-content:center;width:22px;height:22px;border:none;border-radius:4px;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;transition:all .15s}.gh-queue-item-remove:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #dc2626)}.gh-queue-item-force-send:hover,.gh-queue-item-edit:hover{background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-area{flex:1;min-width:0;display:flex;flex-direction:column;gap:6px}.gh-queue-item-edit-input{width:100%;padding:6px 8px;border:1px solid var(--gh-accent, #4285f4);border-radius:6px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:vertical;min-height:48px;max-height:120px;outline:none;font-family:inherit}.gh-queue-item-edit-actions-row{display:flex;align-items:center;justify-content:flex-end;gap:4px}.gh-queue-item-edit-btn-save,.gh-queue-item-edit-btn-cancel{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border:none;border-radius:4px;background:transparent;cursor:pointer;transition:all .15s}.gh-queue-item-edit-btn-save{color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-btn-save:hover{background:var(--gh-bg-accent, #eef2ff)}.gh-queue-item-edit-btn-cancel{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-item-edit-btn-cancel:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-item[data-status=sending]{border-left:3px solid var(--gh-accent, #4285f4)}.gh-queue-item[data-status=sent]{opacity:.5}.gh-queue-item[data-status=failed]{border-left:3px solid var(--gh-text-danger, #dc2626)}.gh-queue-input-area{padding:12px;border-top:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-input-wrapper{display:flex;align-items:flex-end;gap:8px}.gh-queue-input{flex:1;min-height:36px;max-height:120px;padding:8px 12px;border:1.5px solid var(--gh-border, #e5e7eb);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:none;outline:none;font-family:inherit;transition:border-color .15s}.gh-queue-input:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-input::placeholder{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-send-btn{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:36px;height:36px;border:none;border-radius:10px;background:var(--gh-accent, #4285f4);color:#fff;cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-send-btn:hover{background:var(--gh-accent-hover, #3b78e7)}.gh-queue-send-btn:disabled{opacity:.5;cursor:not-allowed}.gh-queue-status{display:flex;align-items:center;gap:6px;padding:6px 12px;font-size:11px;color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-disable-hint{margin-left:4px;opacity:.6;font-size:10px;cursor:help}.gh-queue-status-dot{width:6px;height:6px;border-radius:50%;background:#22c55e}.gh-queue-status-dot[data-generating=true]{background:#f59e0b;animation:gh-queue-pulse 1.5s infinite}@keyframes gh-queue-pulse{0%,to{opacity:1}50%{opacity:.4}}.gh-queue-shortcut-hint{margin-left:auto;font-size:10px;color:var(--gh-text-tertiary, #9ca3af);opacity:.6}.gh-queue-batch-dialog{max-width:560px}.gh-queue-batch-section{margin-bottom:16px}.gh-queue-batch-tabs{display:flex;gap:6px;margin:12px 0 16px;padding:3px;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:8px;background:var(--gh-bg-secondary, #f9fafb)}.gh-queue-batch-tab{flex:1;height:30px;border:none;border-radius:6px;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:13px;font-weight:600}.gh-queue-batch-tab[data-active=true]{background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);box-shadow:0 1px 3px #0f172a1f}.gh-queue-batch-label{margin-bottom:8px;font-size:13px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-group{display:flex;gap:8px;flex-wrap:wrap}.gh-queue-batch-mode-btn{padding:8px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:8px;background:var(--gh-bg, #ffffff);color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:13px;transition:all .15s ease}.gh-queue-batch-mode-btn:hover{border-color:var(--gh-accent, #4285f4);color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-btn[data-active=true]{border-color:var(--gh-accent, #4285f4);background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-batch-delimiter-input{margin-bottom:0}.gh-queue-batch-library-search{margin-bottom:10px}.gh-queue-batch-library-list{max-height:260px;overflow-y:auto;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:10px;background:var(--gh-bg, #ffffff)}.gh-queue-batch-library-item{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;padding:9px 10px;border-bottom:1px solid var(--gh-border-light, #e5e7eb);cursor:pointer}.gh-queue-batch-library-item:last-child{border-bottom:none}.gh-queue-batch-library-item:hover{background:var(--gh-hover, #f3f4f6)}.gh-queue-batch-library-item[data-disabled=true]{cursor:not-allowed;opacity:.62}.gh-queue-batch-library-item[data-disabled=true]:hover{background:var(--gh-bg, #ffffff)}.gh-queue-batch-library-main{min-width:0;display:flex;flex-direction:column;gap:3px}.gh-queue-batch-library-title{font-size:13px;font-weight:600;color:var(--gh-text, #1f2937);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-content{font-size:12px;color:var(--gh-text-secondary, #6b7280);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-category{max-width:90px;padding:2px 6px;border-radius:5px;background:var(--gh-hover, #f3f4f6);color:var(--gh-text-secondary, #6b7280);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-empty{padding:24px 12px;color:var(--gh-text-tertiary, #9ca3af);font-size:13px;text-align:center}.gh-queue-batch-textarea{width:100%;min-height:160px;max-height:300px;padding:10px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.55;resize:vertical;box-sizing:border-box;outline:none;font-family:inherit}.gh-queue-batch-textarea:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-batch-preview{margin-bottom:20px;padding:12px;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:10px;background:var(--gh-bg-secondary, #f9fafb);display:flex;flex-direction:column}.gh-queue-batch-preview-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px;font-size:12px;color:var(--gh-text-secondary, #6b7280)}.gh-queue-batch-preview-body{max-height:220px;overflow-y:auto;min-height:0}.gh-queue-batch-preview-list{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:6px}.gh-queue-batch-preview-item{color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word}.gh-queue-batch-preview-empty,.gh-queue-batch-preview-more{font-size:12px;color:var(--gh-text-tertiary, #9ca3af)}');const Wb=({adapter:e,dispatcher:t})=>{const[n,r]=_(false),[o,a]=_(false),[s,l]=_(""),[c,d]=_(false),[u,h]=_(""),[g,p]=_("library"),[m,f]=_("line"),[b,y]=_(""),[v,x]=_(""),[w,S]=_("single"),[C,k]=_([]),[T,A]=_(null),[M,I]=_(""),[N,R]=_(null),D=Um(e=>e.items),P=Um(),q=Rm(e=>e.prompts),B=$(null),O=$(null),z=$(null),F=D.filter(e=>"pending"===e.status).length,U=D.filter(e=>"pending"===e.status||"sending"===e.status).length,H=D.filter(e=>"pending"===e.status||"sending"===e.status).length,W=Mi(e=>e.settings.features?.prompts?.submitShortcut??"enter"),j=Mi(e=>e.settings?.shortcuts),G=j?.keybindings?.togglePromptQueue,V=i.useMemo(()=>{if(null===G)return "";const e=navigator.userAgent.toLowerCase().includes("mac");if(G){const t=lr(G);return t?dr(t,e):""}return e?"⌥J":"Alt+J"},[G]),Q=i.useMemo(()=>{const e=v.trim().toLowerCase();return [...e?q.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e)||t.category?.toLowerCase().includes(e)):q].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:(t.lastUsedAt||0)-(e.lastUsedAt||0))},[v,q]),K=i.useMemo(()=>{const e=new Set(C);return q.filter(t=>e.has(t.id)&&0===$b(t.content).length)},[q,C]),Z=i.useMemo(()=>K.flatMap(e=>"line"===w?Ob(e.content):[e.content.trim()].filter(Boolean)),[w,K]),Y=i.useMemo(()=>((e,t,n)=>{const r=_b(e),o=_b((e=>e.replace(/\\(\\|n|r|t)/g,(e,t)=>{switch(t){case "n":return "\n";case "r":return "\r";case "t":return "\t";case "\\":return "\\";default:return t}}))(n));return ("line"===t?Ob(e):o?r.split(o):[]).map(e=>e.trim()).filter(Boolean)})(u,m,b),[b,u,m]),X="library"===g?Z:Y,J=E(e=>{let t=e,n=e.parentElement;for(let r=0;r<10&&n&&n!==document.body;r++){const e=window.getComputedStyle(n);if(e.borderRadius&&parseFloat(e.borderRadius)>0){t=n;break}n=n.parentElement;}return t},[]),ee=E(()=>{const t=e.getTextareaElement();if(!t)return void R(null);const n=J(t).getBoundingClientRect(),r=window.innerHeight-n.top+6,o=Math.min(420,window.innerWidth-40);let i=n.right-20-o;i<20&&(i=20);const a=window.innerWidth-(i+o);R({bottom:r,right:a,width:o});},[e,J]);L(()=>{ee();let t=null,n=null;const r=()=>{if(n=e.getTextareaElement(),n){const e=J(n);t=new ResizeObserver(()=>{ee();}),t.observe(n),t.observe(e),n.parentElement&&t.observe(n.parentElement);}};r();const o=setInterval(()=>{ee(),t||n||r();},2e3);return window.addEventListener("resize",ee),()=>{clearInterval(o),window.removeEventListener("resize",ee),t&&t.disconnect();}},[ee,e,J]),L(()=>{const t=setInterval(()=>{a(e.isGenerating());},1e3);return ()=>clearInterval(t)},[e]),L(()=>{const e=()=>{r(e=>!e);};return window.addEventListener("ophel:togglePromptQueue",e),()=>window.removeEventListener("ophel:togglePromptQueue",e)},[]),L(()=>{n&&B.current&&setTimeout(()=>B.current?.focus(),100);},[n]),L(()=>{if(!c||"text"!==g)return;const e=window.setTimeout(()=>O.current?.focus(),60);return ()=>window.clearTimeout(e)},[g,c]),L(()=>{const e=z.current;if(e)return as(e,{capture:false})},[n,N]),L(()=>{if(!n||c)return;const e=e=>{z.current&&!z.current.contains(e.target)&&r(false);},t=setTimeout(()=>{document.addEventListener("mousedown",e);},100);return ()=>{clearTimeout(t),document.removeEventListener("mousedown",e);}},[c,n]);const te=E(async()=>{const e=s.trim();e&&(l(""),o?(P.enqueue(e),t.isRunning()||t.start()):await t.sendImmediately(e,W));},[s,o,P,t,W]),ne=E(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.stopPropagation(),te()),"Escape"===e.key&&(e.stopPropagation(),r(false));},[te]),re=E(e=>{P.remove(e);},[P]),oe=E(async(e,n)=>{P.remove(e);await t.sendImmediately(n,W)||(P.enqueue(n),t.isRunning()||t.start());},[P,t,W]),ie=E(()=>{P.clear();},[P]),ae=E(()=>{h(""),p("library"),f("line"),y(""),x(""),S("single"),k([]),d(false);},[]),se=E(e=>{k(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);},[]),ce=E(async()=>{if("text"===g&&"delimiter"===m&&!b.trim())return void Pi(le("queueBatchDelimiterRequired"),2500);if(0===X.length)return void Pi(le("queueBatchImportEmpty"),2500);const n=P.enqueueMany(X);0!==n.length?(t.isRunning()||t.start(),e.isGenerating()||await t.processNextNow(),Pi(le("queueBatchImportSuccess",{count:String(n.length)}),2500),ae()):Pi(le("queueBatchImportEmpty"),2500);},[e,b,X,g,m,t,ae,P]),de=E((e,t)=>{A(e),I(t);},[]),ue=E(e=>{M.trim()&&P.updateContent(e,M.trim()),A(null);},[M,P]),he=E(()=>{A(null);},[]),ge=E(()=>{B.current&&(B.current.style.height="0px",B.current.style.height=Math.min(B.current.scrollHeight,120)+"px");},[]);L(()=>{ge();},[s,ge]);const pe=E(e=>{l(e.target.value);},[]);if(!N)return null;const me=document.querySelector(".gh-root")||document.body,fe={bottom:N.bottom,right:N.right},be={bottom:N.bottom,right:N.right,width:N.width};return n?De(Ne,{children:[Kc( De("div",{className:"gh-queue-panel",style:be,ref:z,children:[ De("div",{className:"gh-queue-header",children:[ De("div",{className:"gh-queue-header-title",children:[ Re("span",{children:Re(Ve,{size:18,color:"currentColor"})}), Re("span",{children:le("queueTitle")}),F>0&&Re("span",{className:"gh-queue-capsule-badge",children:F})]}), De("div",{className:"gh-queue-header-actions",children:[ Re(od,{content:le("queueBatchImport"),children:Re("button",{className:"gh-queue-header-btn",onClick:()=>d(true),children:Re(Ke,{size:16,color:"currentColor"})})}),H>0&&Re(od,{content:le("queueClearAll"),children:Re("button",{className:"gh-queue-header-btn",onClick:ie,children:Re(Pt,{size:16,color:"currentColor"})})}), Re(od,{content:le("collapse"),children:Re("button",{className:"gh-queue-header-btn",onClick:()=>r(false),children:De("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Re("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]})]}), Re("div",{className:"gh-queue-list",children:0===D.filter(e=>"pending"===e.status||"sending"===e.status).length?Re("div",{className:"gh-queue-empty",children:le("queueEmpty")}):D.filter(e=>"pending"===e.status||"sending"===e.status).map((e,t)=>De("div",{className:"gh-queue-item","data-status":e.status,children:[ Re("span",{className:"gh-queue-item-index",children:t+1}),T===e.id?De("div",{className:"gh-queue-item-edit-area",children:[ Re("textarea",{className:"gh-queue-item-edit-input",value:M,onChange:e=>{I(e.target.value);const t=e.target;t.style.height="0px",t.style.height=Math.min(t.scrollHeight,120)+"px";},onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),ue(e.id)),"Escape"===t.key&&he();},autoFocus:true}), De("div",{className:"gh-queue-item-edit-actions-row",children:[ Re("button",{className:"gh-queue-item-edit-btn-save",onClick:()=>ue(e.id),title:le("queueEditSave"),children:Re("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Re("polyline",{points:"20 6 9 17 4 12"})})}), Re("button",{className:"gh-queue-item-edit-btn-cancel",onClick:he,title:le("queueEditCancel"),children:De("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Re("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}):De(Ne,{children:[ Re("span",{className:"gh-queue-item-content",children:e.content}), De("div",{className:"gh-queue-item-actions",children:["pending"===e.status&&Re("button",{className:"gh-queue-item-edit",onClick:()=>de(e.id,e.content),title:le("queueEdit"),children:De("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), Re("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),"pending"===e.status&&Re("button",{className:"gh-queue-item-force-send",onClick:()=>oe(e.id,e.content),title:le("queueForceSend"),children:De("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Re("polyline",{points:"5 12 12 5 19 12"})]})}), Re("button",{className:"gh-queue-item-remove",onClick:()=>re(e.id),title:le("queueRemove"),children:De("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Re("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]},e.id))}), Re("div",{className:"gh-queue-input-area",children:De("div",{className:"gh-queue-input-wrapper",children:[ Re("textarea",{ref:B,className:"gh-queue-input",value:s,onChange:pe,onKeyDown:ne,placeholder:le(o?"queuePlaceholderBusy":"queuePlaceholderIdle"),rows:1}), Re("button",{className:"gh-queue-send-btn",onClick:te,disabled:!s.trim(),title:"Enter",children:De("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Re("polyline",{points:"5 12 12 5 19 12"})]})})]})}), De("div",{className:"gh-queue-status",children:[ Re("span",{className:"gh-queue-status-dot","data-generating":o?"true":"false"}), Re("span",{children:le(o?"queueStatusBusy":"queueStatusIdle")}), De("span",{className:"gh-queue-disable-hint",title:le("queueSettingDesc"),children:["(",le("queueDisableHint"),")"]}),V&&Re("span",{className:"gh-queue-shortcut-hint",children:V})]})]}),me),c&&De($f,{onClose:ae,closeOnOverlayClick:false,closeOnEscape:false,dialogClassName:"gh-queue-batch-dialog",dialogStyle:{maxWidth:560,width:"min(560px, calc(100vw - 32px))"},children:[ Re("div",{className:"gh-dialog-title",children:le("queueBatchImportTitle")}), Re("div",{className:"gh-dialog-message",children:le("queueBatchImportDesc")}), De("div",{className:"gh-queue-batch-tabs",children:[ Re("button",{className:"gh-queue-batch-tab","data-active":"library"===g,onClick:()=>p("library"),children:le("queueBatchLibraryTab")}), Re("button",{className:"gh-queue-batch-tab","data-active":"text"===g,onClick:()=>p("text"),children:le("queueBatchTextTab")})]}),"text"===g&&De(Ne,{children:[ De("div",{className:"gh-queue-batch-section",children:[ Re("div",{className:"gh-queue-batch-label",children:le("queueBatchSplitModeLabel")}), De("div",{className:"gh-queue-batch-mode-group",children:[ Re("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===m,onClick:()=>f("line"),children:le("queueBatchSplitModeLine")}), Re("button",{className:"gh-queue-batch-mode-btn","data-active":"delimiter"===m,onClick:()=>f("delimiter"),children:le("queueBatchSplitModeDelimiter")})]})]}),"delimiter"===m&&De("div",{className:"gh-queue-batch-section",children:[ Re("div",{className:"gh-queue-batch-label",children:le("queueBatchDelimiterLabel")}), Re("input",{className:"gh-dialog-input gh-queue-batch-delimiter-input",value:b,onChange:e=>y(e.target.value),placeholder:le("queueBatchDelimiterPlaceholder")})]}), De("div",{className:"gh-queue-batch-section",children:[ Re("div",{className:"gh-queue-batch-label",children:le("queueBatchInputLabel")}), Re("textarea",{ref:O,className:"gh-queue-batch-textarea",value:u,onChange:e=>h(e.target.value),placeholder:le("queueBatchInputPlaceholder")})]})]}),"library"===g&&De(Ne,{children:[ De("div",{className:"gh-queue-batch-section",children:[ Re("div",{className:"gh-queue-batch-label",children:le("queueBatchLibraryModeLabel")}), De("div",{className:"gh-queue-batch-mode-group",children:[ Re("button",{className:"gh-queue-batch-mode-btn","data-active":"single"===w,onClick:()=>S("single"),children:le("queueBatchLibraryModeSingle")}), Re("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===w,onClick:()=>S("line"),children:le("queueBatchSplitModeLine")})]})]}), De("div",{className:"gh-queue-batch-section",children:[ Re("div",{className:"gh-queue-batch-label",children:le("queueBatchLibrarySearchLabel")}), Re("input",{className:"gh-dialog-input gh-queue-batch-library-search",value:v,onChange:e=>x(e.target.value),placeholder:le("queueBatchLibrarySearchPlaceholder")}), Re("div",{className:"gh-queue-batch-library-list",children:0===Q.length?Re("div",{className:"gh-queue-batch-library-empty",children:le("queueBatchLibraryEmpty")}):Q.slice(0,80).map(e=>{const t=$b(e.content).length>0; return De("label",{className:"gh-queue-batch-library-item","data-disabled":t?"true":"false",title:t?le("queueBatchLibraryVariablePrompt"):void 0,children:[ Re("input",{type:"checkbox",disabled:t,checked:!t&&C.includes(e.id),onChange:()=>{t||se(e.id);}}), De("span",{className:"gh-queue-batch-library-main",children:[ Re("span",{className:"gh-queue-batch-library-title",children:e.title}), Re("span",{className:"gh-queue-batch-library-content",children:t?le("queueBatchLibraryVariablePrompt"):e.content})]}), Re("span",{className:"gh-queue-batch-library-category",children:e.category||le("uncategorized")})]},e.id)})})]})]}), De("div",{className:"gh-queue-batch-preview",children:[ De("div",{className:"gh-queue-batch-preview-header",children:[ Re("span",{children:le("queueBatchPreviewTitle")}), Re("span",{children:le("queueBatchPreviewCount",{count:String(X.length)})})]}), Re("div",{className:"gh-queue-batch-preview-body",children:0===X.length?Re("div",{className:"gh-queue-batch-preview-empty",children:le("queueBatchPreviewEmpty")}):De(Ne,{children:[ Re("ol",{className:"gh-queue-batch-preview-list",children:X.slice(0,5).map((e,t)=>Re("li",{className:"gh-queue-batch-preview-item",children:e},`${t}-${e.slice(0,20)}`))}),X.length>5&&Re("div",{className:"gh-queue-batch-preview-more",children:le("queueBatchPreviewMore",{count:String(X.length-5)})})]})})]}), De("div",{className:"gh-dialog-buttons",children:[ Re("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:ae,children:le("cancel")}), Re("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:()=>{ce();},disabled:0===X.length||"text"===g&&"delimiter"===m&&!b.trim(),children:le("queueBatchImportAction")})]})]})]}):Kc( Re(od,{content:V||le("queueQuickAsk"),children:De("div",{className:"gh-queue-capsule",style:fe,onClick:()=>r(true),children:[ Re("span",{className:"gh-queue-capsule-icon",children:Re(Ve,{size:18,color:"currentColor"})}), Re("span",{children:U>0?le("queueInQueue",{count:String(U)}):le("queueQuickAsk")})]})}),me)},jb=()=>({width:window.innerWidth,height:window.innerHeight}),Gb=(e,t)=>e&&t?e.xRatio===t.xRatio&&e.yRatio===t.yRatio:e===t,Vb=3e3,Qb=({isPanelExpanded:e,onPanelToggle:t,onPanelLogoHoverStart:n,onPanelLogoHoverEnd:r,onThemeToggle:o,themeMode:a,onExport:s,onMove:l,onSetTag:c,onScrollLock:d,onSettings:u,onCleanup:h,onGlobalSearch:g,scrollLocked:p,onCopyMarkdown:m,onModelLockToggle:f,isModelLocked:b,onOpenSettings:y,isScrolling:v})=>{const x=E(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:w,updateNestedSetting:S}=Mi(),C=w||ti,k=am(),T=C.quickButtons||ti.quickButtons,A=q(()=>T.collapsed||[],[T.collapsed]),M=C.panel?.defaultPosition??"right",I="left"===M?{left:"16px",right:"auto"}:{right:"16px",left:"auto"},N=Math.min(Math.max(T.opacity??1,.4),1),R=T.position??null,D=T.proximityRadius??150,B=k?.getSiteId()||"_default",z=ni(C,B),F=a||("dark"===z.mode?"dark":"light");"light"===F?z.lightStyleId:z.darkStyleId;const U="dark"===F?"brand":"currentColor",H=$(null),[W,j]=_(false),[G,V]=_(jb),Q=$(G),K=$(G),[Z,Y]=_({width:0,height:0}),X=E(e=>{Q.current=e,V(t=>t.width===e.width&&t.height===e.height?t:e);},[]);L(()=>{if(!W)return;const e=e=>{const t=e.target;H.current&&!H.current.contains(t)&&j(false);};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[W]);const[J,ee]=_(R),[te,ne]=_(false),[re,oe]=_(false),ie=$(R),ae=$(R),se=$({width:0,height:0}),[ce,de]=_(null),ue=$(null),he=$(null),ge=$(null),pe=$(null),me=$(false),fe=$(null),be=$(false),ye=$(null),ve=null!==O(lf,cf),[xe,we]=_(0);L(()=>{if(0===xe)return;const e=setTimeout(()=>we(0),400);return ()=>clearTimeout(e)},[xe]);const[Se,Ce]=_(false),[ke,Te]=_(true),Ee=$(null),Ae=$(false),Me=E((e=3e3)=>{Te(true),null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{Te(false);},e);},[]),Ie=E(e=>{null!==Ee.current&&(window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{Te(false);},e));},[]);L(()=>{const t=te||re||e||W;Ae.current=t,t?(Te(true),null!==Ee.current&&(window.clearTimeout(Ee.current),Ee.current=null)):Me(4e3);},[te,re,e,W,Me]),L(()=>{let e=null;const t=t=>{null===e&&0!==D&&(e=requestAnimationFrame(()=>{if(e=null,!H.current||Ae.current)return;const n=H.current.getBoundingClientRect(),r=Math.max(n.left-t.clientX,0,t.clientX-n.right),o=Math.max(n.top-t.clientY,0,t.clientY-n.bottom),i=Math.sqrt(r*r+o*o);D>0&&i<=D&&Me(Vb);}));},n=()=>{Ie(1500);},r=()=>{document.hidden&&Ie(1500);};return document.addEventListener("mousemove",t,{passive:true}),document.addEventListener("mouseleave",n,{passive:true}),document.addEventListener("visibilitychange",r),Me(Vb),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseleave",n),document.removeEventListener("visibilitychange",r),null!==e&&cancelAnimationFrame(e),null!==Ee.current&&window.clearTimeout(Ee.current);}},[Me,Ie,D]);const Le=!(ke||Se||W||e||te||re);$(Le).current=Le;const Be=q(()=>{if(te||re||W)return false;if(Le)return false;if(T.hideWhenPanelOpen&&e)return true;const t=e&&"edge-snap"!==(C.panel?.panelMode??"edge-snap");for(const n of A){if("manualAnchor"===n.id)continue;const r=Vr[n.id];if(!r)continue;if((!r.canToggle||n.enabled)&&!(r.isPanelOnly&&e||r.hideWhenPanelOpen&&t))return false}return true},[te,re,W,Le,e,A,C.panel?.panelMode,T.hideWhenPanelOpen]),[$e,_e]=_(false),[Oe,ze]=_(false),[Fe,Ue]=_(""),He=$(false),We=E(()=>{null!==ye.current&&(window.clearTimeout(ye.current),ye.current=null);},[]),je=E(e=>{const t=e??null;We(),Gb(ae.current,t)||(ae.current=t,S("quickButtons","position",t||void 0));},[We,S]);E(e=>{if(Gb(ae.current,e))return;We();const t={...e};ye.current=window.setTimeout(()=>{ye.current=null,Gb(ae.current,t)||(ae.current=t,S("quickButtons","position",t));},220);},[220,We,S]),L(()=>{const e=!Gb(ae.current,R);e&&We(),ae.current=R,e&&!me.current&&(ie.current=R,ee(R));},[We,R]),L(()=>()=>{We();},[We]),L(()=>{R&&(ue.current=null,de(null));},[R]);const Ge=E((e,t=se.current)=>{const n=t.width,r=t.height;return {width:n,height:r,maxX:Math.max(8,e.width-n-8),maxY:Math.max(8,e.height-r-8)}},[8]),Ve=E((e,t,n,r=se.current)=>{const{width:o,height:i,maxX:a,maxY:s}=Ge(n,r);return {x:Math.min(Math.max(e,8),a),y:Math.min(Math.max(t,8),s),width:o,height:i,maxX:a,maxY:s}},[8,Ge]),Qe=E((e,t,n,r=se.current)=>{const o=Ve(e,t,n,r),i=Math.max(1,o.maxX-8),a=Math.max(1,o.maxY-8);return {xRatio:Math.min(1,Math.max(0,(o.x-8)/i)),yRatio:Math.min(1,Math.max(0,(o.y-8)/a))}},[8,Ve]),Ke=E((e,t,n=se.current)=>{if(!e)return null;const{maxX:r,maxY:o}=Ge(t,n),i=Math.max(1,r-8),a=Math.max(1,o-8),s=8+e.xRatio*i,l=8+e.yRatio*a;return {x:Math.min(Math.max(s,8),r),y:Math.min(Math.max(l,8),o)}},[8,Ge]);P(()=>{const e=H.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect(),n={width:t.width,height:t.height},r=se.current,o=0===r.width&&0===r.height;if(!(r.width!==n.width||r.height!==n.height))return;se.current=n,Y(n);const i=jb(),a=K.current,s=a.width!==i.width||a.height!==i.height;if(K.current=i,Q.current.width===i.width&&Q.current.height===i.height||X(i),!ie.current){const e=ue.current??t.top,r=Ve(0,e,i,n).y;return void(ue.current!==r&&(ue.current=r,de(r)))}if(me.current||o||s)return;const l=Qe(t.left,t.top,i,n),c=ie.current;c.xRatio===l.xRatio&&c.yRatio===l.yRatio||(ie.current=l,ee(l));};t();const n=new ResizeObserver(()=>{t();});return n.observe(e),()=>{n.disconnect();}},[Ve,X,Qe]);const Ze=E(async()=>{He.current=false;const e=new AbortController,t=setInterval(()=>{He.current&&e.abort();},100);let n=setTimeout(()=>{He.current||(ze(true),Ue(le("loadingHistory")));},1600);try{const t=await Af({adapter:k,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{Ue(`${le("loadingHistory")} ${e}`);}});sf(t.previousScrollTop),_e(t.isFlutterMode),n&&(window.clearTimeout(n),n=null),ze(!1),Ue(""),t.success&&!t.silent&&Pi(le("historyLoaded"),2e3);}finally{clearInterval(t),n&&window.clearTimeout(n);}},[k]),Ye=E(()=>{He.current=true;},[]),Xe=E(async()=>{const{previousScrollTop:e,container:t}=await ff(k);sf(e),_e(wf(t));},[k]),Je=E(async()=>{const e=af();if(null===e)return;we(e=>e+1);const t=(await vf(k)).scrollTop;await bf(k,e),sf(t);},[k]),et=E(async()=>{const e=await vf(k);sf(e.scrollTop),_e(e.isFlutterMode);},[k]),tt=Ke(J,G,Z),nt=Ge(G,Z),rt=tt&&nt.width>0?tt.x+nt.width/2<=G.width/2?"side-right":"side-left":"left"===M?"side-right":"side-left",ot={scrollTop:Ze,scrollBottom:Xe,panel:t,anchor:Je,theme:e=>{e?.stopPropagation();const t=e?.currentTarget;t?o?.(x(t)):o?.();},floatingToolbar:e=>{e?.stopPropagation(),j(e=>!e);},globalSearch:e=>{e?.stopPropagation(),j(false),g?.();},zenMode:e=>{e?.stopPropagation();const t=k?.getSiteId()||"_default",n=ai(w||ti,t),r=!n.enabled;if(S("layout","zenMode",{...w?.layout?.zenMode??{},[t]:{...n,enabled:r}}),r){const e=w?.layout?.cleanMode?.[t]??{enabled:true};S("layout","cleanMode",{...w?.layout?.cleanMode??{},[t]:{...e,enabled:true}});}},settings:e=>{e?.stopPropagation(),j(false),y?.();}},it=(t,o,i)=>{const s=o.isPanelOnly,l=!i,c="floatingToolbar"===t,d="zenMode"===t,u=d&&Boolean(w?.layout?.zenMode?.[B]?.enabled),h=c?W:u,g=e&&"edge-snap"!==(w?.panel?.panelMode??"edge-snap");if(l||s&&e||o.hideWhenPanelOpen&&g)return null;let p;if("theme"===t)p=Re("dark"===a?Pe:qe,{size:20});else if(u)p=Re(Wt,{size:18,color:"currentColor"});else if(o.IconComponent){const e=o.IconComponent;p=Re(e,{size:"panel"===t?21:18,color:"panel"===t?U:void 0});}else p=o.icon;const m="anchor"===t,f="panel"===t,b=m&&!ve,y=le(m?ve?"goToAnchor":"noAnchor":o.labelKey); return Re(od,{content:y,children:Re("button",{className:`quick-prompt-btn gh-interactive ${s?"panel-only":""} ${f?"panel-btn":""} ${h?"active":""} ${c?"tools-trigger-btn":""} ${d?"zen-mode-btn":""}`,onClick:e=>ot[t]?.(e),onMouseEnter:e=>{f&&n?.(e.currentTarget.getBoundingClientRect(),{waitForGroupDwell:Le&&0===D});},onMouseLeave:()=>{f&&r?.();},"data-tip-target":"globalSearch"===t?"search-btn":"floatingToolbar"===t?"toolbar-btn":"shortcuts"===t?"shortcuts-btn":"settings"===t?"settings-btn":void 0,style:{opacity:b?.4:1,cursor:b?"default":"pointer"},disabled:b,children:m?Re("span",{className:"anchor-tap-wrapper"+(xe>0?" is-tapping":""),onAnimationEnd:()=>we(0),style:{display:"flex"},children:p},xe):p})},t)},at=e=>{if(!e)return null;const t=Vr.manualAnchor,n=t?.IconComponent; return Re(i.Fragment,{children:Re(od,{content:le("setAnchor"),children:Re("button",{className:"quick-prompt-btn manual-anchor-btn set-btn gh-interactive",onClick:et,children:n?Re(n,{size:18}):"📍"})})},"manualAnchor")},st=(e,t)=>Re("div",{className:"divider "},t),lt={[Io]:()=>s?.(),[Lo]:()=>m?.(),[No]:()=>l?.(),[Ro]:()=>c?.(),[Do]:()=>d?.(!p),[Po]:()=>f?.(),[qo]:()=>h?.(),[Bo]:()=>u?.()},ct=e=>e===Do?p||false:e===Po&&b||false;L(()=>{if(!H.current)return;let e=null,t=null;const n=()=>{e&&(clearTimeout(e),e=null),0===D?t=window.setTimeout(()=>{Ce(true);},300):Ce(true);},r=()=>{t&&(clearTimeout(t),t=null),e=window.setTimeout(()=>{Ce(false);},300);},o=H.current;return o.addEventListener("mouseenter",n),o.addEventListener("mouseleave",r),()=>{o.removeEventListener("mouseenter",n),o.removeEventListener("mouseleave",r),e&&clearTimeout(e),t&&clearTimeout(t);}},[Ve,D]),L(()=>{let e=null,t=null,n=false;const r=()=>{const e=jb();if(X(e),ie.current||null===ue.current)return;const t=Ve(0,ue.current,e,se.current).y;ue.current!==t&&(ue.current=t,de(t));},o=()=>{null===e?e=requestAnimationFrame(()=>{e=null,r(),n&&(n=false,o());}):n=true;},i=()=>{o(),null!==t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,r();},120);};return window.addEventListener("resize",i),window.visualViewport?.addEventListener("resize",i),()=>{window.removeEventListener("resize",i),window.visualViewport?.removeEventListener("resize",i),null!==e&&cancelAnimationFrame(e),null!==t&&window.clearTimeout(t);}},[Ve,X]);const dt=()=>{he.current&&(window.clearTimeout(he.current),he.current=null);},ut=()=>{(()=>{const e=me.current;oe(false),dt(),ge.current=null,pe.current=null,me.current&&(We(),me.current=false,ne(false)),H.current&&null!==fe.current&&H.current.hasPointerCapture(fe.current)&&H.current.releasePointerCapture(fe.current),fe.current=null,e&&je(ie.current);})();}; return De(Ne,{children:[ Re(rb,{isVisible:Oe,text:Fe,onStop:Ye}), De("div",{ref:H,className:`quick-btn-group gh-interactive ${e?"":"collapsed"} ${te?"dragging":""} ${re?"pressing":""} ${v?"scroll-hidden":""} ${Le?"liquid-collapsed":""} ${Be?"group-hidden":""}`,"aria-hidden":Be,onPointerDown:e=>{if(0!==e.button)return;if(!H.current)return;fe.current=e.pointerId,ge.current={x:e.clientX,y:e.clientY},be.current=false,oe(true);const t=H.current.getBoundingClientRect();pe.current={x:e.clientX-t.left,y:e.clientY-t.top},dt(),he.current=window.setTimeout(()=>{H.current&&null!==fe.current&&(We(),H.current.setPointerCapture(fe.current),oe(false),me.current=true,be.current=true,ne(true));},220);},onPointerMove:e=>{if(!ge.current)return;if(!me.current){const t=e.clientX-ge.current.x,n=e.clientY-ge.current.y;return void(Math.hypot(t,n)>6&&(dt(),oe(false)))}e.preventDefault();const t=jb(),n=pe.current||{x:0,y:0},r=e.clientX-n.x,o=e.clientY-n.y,i=Qe(r,o,t);X(t),ie.current=i,ee(i);},onPointerUp:ut,onPointerCancel:ut,onPointerLeave:()=>{me.current||(dt(),oe(false),ge.current=null,pe.current=null,fe.current=null);},onClickCapture:e=>{be.current&&(e.preventDefault(),e.stopPropagation(),be.current=false);},style:{position:"fixed",top:tt?`${tt.y}px`:null!==ce?`${ce}px`:"50%",left:tt?`${tt.x}px`:I.left,right:tt?"auto":I.right,transform:tt||null!==ce?"none":"translateY(-50%)",opacity:Be?0:N,pointerEvents:Be?"none":void 0},children:[ Re("div",{className:"quick-btn-drag-handle",style:{"--quick-btn-press-duration":"220ms"},"aria-hidden":"true"}),(()=>{if(Le)return [it("panel",Vr.panel,true)];const t=[],n=new Set(["scrollTop","scrollBottom","anchor","manualAnchor"]),r=A.map(t=>{if("manualAnchor"===t.id)return null;const r=Vr[t.id];if(!r)return null;const o=!r.canToggle||t.enabled;if(!o)return null;if(r.isPanelOnly&&e)return null;const i=e&&"edge-snap"!==(w?.panel?.panelMode??"edge-snap");return r.hideWhenPanelOpen&&i?null:{id:t.id,def:r,enabled:o,group:n.has(t.id)?"navigation":"tools"}}).filter(e=>null!==e);let o=0;for(;o=2&&ne.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(()=>{const e=[];let t=false,n=false;const r=T.toolsMenu??$o.map(e=>e.id),o=new Set(r);for(const i of $o){if(!(i.isSystem||o.has(i.id)))continue;i.isDanger&&!t&&(e.push(Re("div",{className:"menu-divider"},`divider-before-${i.id}`)),t=true),i.isSystem&&!n&&(e.push(Re("div",{className:"menu-divider"},`divider-before-${i.id}`)),n=true);const r=i.IconComponent,a=`quick-menu-btn ${!!i.isToggle&&ct(i.id)?"active":""} ${i.isDanger?"danger":""}`;e.push( Re(od,{content:le(i.labelKey),children:Re("button",{className:a,onClick:()=>{lt[i.id]?.(),j(false);},children:Re(r,{size:18})})},i.id));}return e})()})]})]})},Kb="50%",Zb=({title:e,onClear:t,adapter:n})=>{const[r,o]=_(120),[i,a]=_(Kb),s=$(null),l=$(null),c=$(null),d=E(e=>{let t=e,n=e.parentElement;for(let r=0;r<10&&n&&n!==document.body;r++){const e=window.getComputedStyle(n);if(e.borderRadius&&parseFloat(e.borderRadius)>0){t=n;break}n=n.parentElement;}return t},[]),u=E(()=>{const e=n?.getTextareaElement();if(!e||!e.isConnected)return o(e=>120===e?e:120),a(e=>e===Kb?e:Kb),void(c.current=null);const t=l.current,r=t&&t.isConnected&&t.contains(e)?t:d(e),i=r.getBoundingClientRect(),u=window.innerHeight,h={left:Math.round(i.left),top:Math.round(i.top),width:Math.round(i.width),height:Math.round(i.height),viewportHeight:u};r!==l.current&&s.current&&(l.current&&s.current.unobserve(l.current),s.current.observe(r),l.current=r);const g=c.current;if(g&&g.left===h.left&&g.top===h.top&&g.width===h.width&&g.height===h.height&&g.viewportHeight===h.viewportHeight)return;c.current=h;const p=u-h.top+6,m=Math.max(50,Math.min(p,u-50));o(e=>e===m?e:m);const f=`${Math.round(h.left+h.width/2)}px`;a(e=>e===f?e:f);},[n,d]);return L(()=>{if(!e)return;const t=n?.getTextareaElement();if(s.current=new ResizeObserver(()=>{u();}),t){const e=d(t);s.current.observe(e),l.current=e;}u();const r=[50,200,400].map(e=>setTimeout(u,e));let o=null;const i=()=>{u(),o=window.requestAnimationFrame(i);};return o=window.requestAnimationFrame(i),window.addEventListener("resize",u),()=>{window.removeEventListener("resize",u),r.forEach(e=>clearTimeout(e)),null!==o&&window.cancelAnimationFrame(o),s.current&&(s.current.disconnect(),s.current=null),l.current=null,c.current=null;}},[e,n,d,u]),e?De("div",{className:"selected-prompt-bar gh-interactive",style:{position:"fixed",bottom:`${r}px`,left:i,transform:"translateX(-50%)",zIndex:999998},children:[ Re("span",{className:"selected-prompt-label",children:le("currentPrompt")}), Re(od,{content:e,children:Re("span",{className:"selected-prompt-text",children:e})}), Re(od,{content:le("clear"),children:Re("button",{className:"clear-prompt-btn",type:"button","aria-label":le("clear"),onClick:t,children:Re($e,{size:14})})})]}):null};function Yb(){const e=q(()=>tb(),[]); return De("div",{className:"sidebar-community-links",children:[ Re(od,{content:le("rateAndReview"),children:Re("a",{href:e.url,target:"_blank",rel:"noopener noreferrer","aria-label":le("rateAndReview"),className:"sidebar-social-btn review-btn",children:i.cloneElement(e.icon,{size:18})})}), Re(od,{content:le("giveStar"),children:Re("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer","aria-label":le("giveStar"),className:"sidebar-social-btn github-btn",children:Re(ut,{size:18})})}), Re(od,{content:le("kofiSupport"),children:Re("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer","aria-label":le("kofiSupport"),className:"sidebar-social-btn kofi-btn",children:Re(nn,{size:18})})}), Re(od,{content:le("discordCommunity"),children:Re("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer","aria-label":le("discordCommunity"),className:"sidebar-social-btn discord-btn",children:Re(tn,{size:18})})})]})}const Xb={"zh-CN":"简体中文","zh-TW":"繁體中文",en:"English",es:"Español",pt:"Português",ru:"Русский",ja:"日本語",de:"Deutsch",fr:"Français",ko:"한국어"},Jb=({currentLang:e,themeMode:t="light",onSelect:n,onClose:r,triggerRef:o})=>{const i=$(null),[a,s]=_({top:0,left:0});L(()=>{if(!o.current)return;const e=o.current.getBoundingClientRect();s({top:e.top-10,left:e.right});},[o]);const l="dark"===t?{bg:"#1f2937",border:"#374151",text:"#e5e7eb",hover:"#374151",activeBg:"rgba(59, 130, 246, 0.2)"}:{bg:"#ffffff",border:"#e5e7eb",text:"#374151",hover:"#f3f4f6",activeBg:"rgba(59, 130, 246, 0.1)"};return Kc( De("div",{className:"lang-menu-portal",style:{position:"relative",zIndex:2147483647},children:[ Re("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:2e6,background:"transparent"},onClick:e=>{e.stopPropagation(),r();}}), Re("div",{ref:i,style:{position:"fixed",bottom:window.innerHeight-a.top+5,left:a.left-150,width:"150px",background:l.bg,border:`1px solid ${l.border}`,borderRadius:"8px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)",padding:"4px",zIndex:2000001,animation:"ophel-lang-pop 0.1s ease-out",display:"flex",flexDirection:"column",maxHeight:"500px",overflowY:"auto"},children:Object.entries(Xb).map(([t,r])=>De("button",{onClick:e=>{e.stopPropagation(),n(t);},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",border:"none",background:e===t?l.activeBg:"transparent",color:e===t?"#3b82f6":l.text,fontSize:"13px",cursor:"pointer",borderRadius:"4px",textAlign:"left",width:"100%",fontWeight:e===t?500:400,transition:"background-color 0.1s"},onMouseEnter:n=>{e!==t&&(n.currentTarget.style.backgroundColor=l.hover);},onMouseLeave:n=>{e!==t&&(n.currentTarget.style.backgroundColor=e===t?l.activeBg:"transparent");},children:[ Re("span",{children:r}),e===t&&Re("span",{children:"✓"})]},t))}), Re("style",{children:"\n @keyframes ophel-lang-pop {\n from { opacity: 0; transform: scale(0.95); }\n to { opacity: 1; transform: scale(1); }\n }\n "})]}),document.body)},ey=({siteId:e="_default"})=>{const{settings:t,setSettings:n}=Mi(),r=!window.__ophelThemeManager,o=window.__ophelThemeManager,a=O(o?.subscribe??(()=>()=>{}),o?.getSnapshot??(()=>"light")),s=t?.theme?.sites,l=s&&e in s?s[e]:s?._default,c=l?.mode||"light",d=async(r,o)=>{if(c===r)return;const i=window.__ophelThemeManager;if(i?.setMode)await i.setMode(r,o?.nativeEvent);else {const o=t?.theme?.sites||{},i=o[e]||o._default||{};n({theme:{...t?.theme,sites:{...o,[e]:{lightStyleId:"google-gradient",darkStyleId:"classic-dark",...i,mode:r}}}});}},u=e=>{n({language:e}),ae(e);},h=se(t?.language||"auto"),[g,p]=i.useState(false),m=i.useRef(null),f=i.useRef(null),[b,y]=i.useState("normal"),v=i.useRef("normal"),x={en:"EN","zh-CN":"简","zh-TW":"繁",ja:"JP",ko:"KR",fr:"FR",de:"DE",ru:"RU",es:"ES",pt:"PT"},w=["zh-CN","en"],S=w.includes(h)?"es":h,C=Array.from(new Set([...w,S]));return i.useEffect(()=>{v.current=b;},[b]),i.useEffect(()=>{const e=f.current;if(!e)return;const t=t=>{e.classList.toggle("is-compact","compact"===t),e.classList.toggle("is-icon","icon"===t);},n=n=>(t(n),e.scrollWidth<=e.clientWidth+1),r=()=>{let e="normal";if(!n("normal")){e=n("compact")?"compact":"icon";}t(e),e!==v.current&&y(e);},o=()=>{"function"!=typeof requestAnimationFrame?r():requestAnimationFrame(r);};if(o(),"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(()=>o());return t.observe(e),()=>t.disconnect()}return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[h]),De("div",{className:"settings-sidebar-footer",children:[!r&&De("div",{ref:f,className:`settings-theme-segmented ${"compact"===b?"is-compact":""} ${"icon"===b?"is-icon":""}`,children:[ Re(od,{content:le("themeLight"),triggerStyle:{flex:1},children:De("button",{className:"settings-theme-segment "+("light"===c?"active":""),onClick:e=>d("light",e),children:[ Re("span",{className:"segment-icon",children:Re(Pe,{size:16})}), Re("span",{className:"segment-label",children:le("themeLight")})]})}), Re(od,{content:le("themeDark"),triggerStyle:{flex:1},children:De("button",{className:"settings-theme-segment "+("dark"===c?"active":""),onClick:e=>d("dark",e),children:[ Re("span",{className:"segment-icon",children:Re(qe,{size:16})}), Re("span",{className:"segment-label",children:le("themeDark")})]})}), Re(od,{content:le("themeSystem"),triggerStyle:{flex:1},children:De("button",{className:"settings-theme-segment "+("system"===c?"active":""),onClick:e=>d("system",e),children:[ Re("span",{className:"segment-icon",children:Re(Be,{size:16})}), Re("span",{className:"segment-label",children:le("themeSystem")})]})})]}), De("div",{className:"settings-lang-inline",children:[ Re("button",{className:"lang-icon",onClick:e=>{e.stopPropagation(),p(!g);},children:Re(At,{size:16})}), Re("div",{className:"lang-links-container",children:C.map((e,t)=>De(i.Fragment,{children:[ Re("button",{className:"lang-link "+(h===e?"active":""),onClick:()=>u(e),children:x[e]||e}),t{e.stopPropagation(),p(!g);},children:Re(Et,{size:18})})}),g&&Re(Jb,{currentLang:h,themeMode:a,onSelect:e=>{u(e),p(false);},onClose:()=>p(false),triggerRef:m})]}), Re("style",{children:'\n .settings-lang-inline {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 3px 4px;\n background: var(--gh-bg-secondary, #f3f4f6);\n border-radius: 8px;\n margin-top: 4px; /* Reduced gap */\n height: 32px;\n }\n\n :host-context([data-gh-mode="dark"]) .settings-lang-inline {\n background: rgba(255, 255, 255, 0.08); /* 匹配深色模式下的 segmented */\n }\n\n .lang-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--gh-text-secondary, #9ca3af);\n padding: 4px;\n margin-left: 2px;\n background: transparent;\n border: none;\n cursor: pointer;\n transition: color 0.2s;\n }\n\n .lang-icon:hover {\n color: var(--gh-text, #374151);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-icon:hover {\n color: #e5e7eb;\n }\n\n /* 中间语言链接容器 */\n .lang-links-container {\n flex: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 2px;\n }\n\n .lang-link {\n background: none;\n border: none;\n padding: 2px 4px;\n cursor: pointer;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n transition: all 0.2s;\n border-radius: 4px;\n font-weight: 500;\n }\n\n .lang-link:hover {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link:hover {\n color: #f3f4f6;\n background: rgba(255, 255, 255, 0.1);\n }\n\n .lang-link.active {\n color: var(--gh-primary, #4285f4);\n font-weight: 700;\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.04);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link.active {\n color: var(--gh-primary, #7cb3ff);\n background: rgba(255, 255, 255, 0.12);\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n }\n\n .lang-divider {\n color: var(--gh-text-secondary, #d1d5db);\n font-size: 12px;\n margin: 0 1px;\n }\n\n .lang-more-btn {\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n color: var(--gh-text-secondary, #9ca3af);\n cursor: pointer;\n padding: 2px;\n border-radius: 4px;\n transition: all 0.2s;\n margin-right: 2px;\n }\n .lang-more-btn:hover, .lang-more-btn.active {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05); /* Match hover styles */\n }\n :host-context([data-gh-mode="dark"]) .lang-more-btn:hover {\n color: #e5e7eb;\n background: rgba(255, 255, 255, 0.1);\n }\n '})]})};function ty(){return globalThis.__OPHEL_SITE_ICONS__||{}}const ny=new Proxy({},{get:(e,t)=>{if("string"==typeof t)return ty()[t]},has:(e,t)=>"string"==typeof t&&t in ty(),ownKeys:()=>Reflect.ownKeys(ty()),getOwnPropertyDescriptor:(e,t)=>{if("string"==typeof t&&t in ty())return {enumerable:true,configurable:true}}}),ry=({title:e,description:t,children:n,className:r="",style:o,settingId:i})=>De("div",{className:`settings-card ${r}`,style:o,"data-setting-id":i,children:[e&&Re("div",{className:"settings-card-title",children:e}),t&&Re("div",{className:"settings-card-desc",children:t}),n]}),oy=({label:e,description:t,children:n,disabled:r=false,onDisabledClick:o,style:i,settingId:a})=>{const s=r&&!!o; return De("div",{className:`settings-row ${r?"disabled":""} ${s?"disabled-clickable":""}`,"data-setting-id":a,style:i,onClick:()=>{s&&o?.();},children:[ De("div",{className:"settings-row-info",children:[ Re("div",{className:"settings-row-label",children:e}),t&&Re("div",{className:"settings-row-desc",children:t})]}),n&&Re("div",{className:"settings-row-control",children:n})]})},iy=({label:e,description:t,checked:n,onChange:r,disabled:o=false,onDisabledClick:i,settingId:a})=>Re(oy,{label:e,description:t,disabled:o,onDisabledClick:i,settingId:a,children:Re(qf,{checked:n,onChange:r,disabled:o})}),ay=({tabs:e,activeTab:t,onTabChange:n})=>Re("div",{className:"settings-tab-group",children:e.map(e=>Re("button",{className:"settings-tab-item "+(t===e.id?"active":""),onClick:()=>n(e.id),children:e.label},e.id))}),sy=({title:e,Icon:t})=>De("h1",{className:"settings-page-title",style:{display:"flex",alignItems:"center"},children:[t&&Re(t,{size:28,className:"settings-page-title-icon",style:{marginRight:8,color:"var(--gh-primary, #4285f4)"}}),e]}),ly=()=>{const e=String(Eo.length); return De("div",{children:[ Re(sy,{title:le("navAbout"),Icon:dt}), Re("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",marginBottom:32},children:De("div",{className:"about-slogan-badge",children:[ Re("span",{style:{marginRight:6},children:"✨"}),le("aboutPageDesc"), Re("span",{style:{marginLeft:6},children:"✨"})]})}), De("div",{className:"about-hero-card",children:[ Re("img",{src:Pf,alt:Rf,className:"about-hero-logo",onError:e=>{e.target.style.display="none";}}), De("div",{className:"about-hero-content",children:[ De("div",{className:"about-hero-title",children:[Rf, De("span",{className:"about-hero-version",children:["v",Df]})]}), Re("div",{className:"about-hero-desc",children:le("aboutDescription",{appName:Rf})})]})]}), Re("div",{className:"about-section-title",children:le("rateAndReview")}), De("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:[ De("a",{href:"https://chromewebstore.google.com/detail/ophel-ai-%E5%AF%B9%E8%AF%9D%E5%A2%9E%E5%BC%BA%E5%B7%A5%E5%85%B7/lpcohdfbomkgepfladogodgeoppclakd",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4285F4"},children:[ De("div",{className:"about-link-header",children:[ Re(Bt,{size:24,color:"var(--card-color)"}), Re("span",{style:{fontWeight:600},children:le("chromeStore")})]}), Re("button",{className:"about-link-btn",children:le("reviewBtn")})]}), De("a",{href:"https://microsoftedge.microsoft.com/addons/detail/ophel-atlas-ai-chat-navi/ffpenkdeifijngifjmbbpijfpdhlolga",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#0078D7"},children:[ De("div",{className:"about-link-header",children:[ Re(Ot,{size:24}), Re("span",{style:{fontWeight:600},children:le("edgeAddons")})]}), Re("button",{className:"about-link-btn",children:le("reviewBtn")})]}), De("a",{href:"https://addons.mozilla.org/zh-CN/firefox/addon/ophel-ai-chat-enhancer/",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#FF7139"},children:[ De("div",{className:"about-link-header",children:[ Re($t,{size:24,color:"var(--card-color)"}), Re("span",{style:{fontWeight:600},children:le("firefoxAddons")})]}), Re("button",{className:"about-link-btn",children:le("reviewBtn")})]}), De("a",{href:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4b5563"},children:[ De("div",{className:"about-link-header",children:[ Re(_t,{size:24,color:"currentColor"}), Re("span",{style:{fontWeight:600,color:"var(--gh-text)"},children:le("greasyFork")})]}), Re("button",{className:"about-link-btn",children:le("reviewBtn")})]})]}), Re("div",{className:"about-section-title",children:le("communityAndSupport")}), De("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",marginBottom:16,fontStyle:"italic",textAlign:"center"},children:['"',le("communityMotto"),'"']}), De("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))"},children:[ De("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#111827"},children:[ De("div",{className:"about-link-header",children:[ Re(ut,{size:22}), Re("span",{style:{fontWeight:600},children:le("githubRepository")})]}), Re("div",{className:"about-link-desc",children:le("githubDesc")}), Re("button",{className:"about-link-btn about-star-btn",children:De("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Re(mt,{size:15,color:"currentColor",filled:true}),le("giveStar")]})})]}), De("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer",className:"about-link-card kofi-card",style:{"--card-color":"#FF5E5B"},children:[ De("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ Re(nn,{size:22,color:"var(--card-color)"}), Re("span",{style:{fontWeight:600},children:le("kofiSupport")})]}), Re("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:le("kofiDesc")}), Re("button",{className:"about-link-btn",children:De("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Re(nn,{size:14,color:"currentColor"}),le("kofiBtn")]})})]}), De("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#3B82F6"},children:[ De("div",{className:"about-link-header",children:[ Re(ht,{size:22,color:"var(--card-color)"}), Re("span",{style:{fontWeight:600,color:"var(--card-color)"},children:le("projectWebsite")})]}), Re("div",{className:"about-link-desc",children:le("websiteDesc")}), Re("button",{className:"about-link-btn",children:De("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Re(ht,{size:14,color:"currentColor"}),le("visitWebsite")]})})]}), De("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer",className:"about-link-card discord-card",style:{"--card-color":"#5865F2"},children:[ De("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ Re(tn,{size:22,color:"var(--card-color)"}), Re("span",{style:{fontWeight:600},children:le("discordCommunity")})]}), Re("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:le("discordDesc")}), Re("button",{className:"about-link-btn",children:De("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Re(tn,{size:14,color:"currentColor"}),le("joinDiscord")]})})]})]}), Re("div",{className:"about-section-title",children:le("aboutSupportedPlatforms")}), De("div",{className:"about-platforms-card",children:[ De("div",{className:"about-platforms-header",children:[ Re("div",{className:"about-platforms-desc",children:le("aboutSupportedPlatformsDesc",{count:e})}), Re("span",{className:"about-platforms-count",children:e})]}), Re("div",{className:"about-platforms-grid",children:Eo.map(e=>De("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"about-platform-chip",title:e.url,children:[ny[e.name]?Re("img",{src:ny[e.name],alt:e.name,className:"about-platform-chip-icon"}):Re("span",{className:"about-platform-chip-emoji","aria-hidden":"true",children:e.icon}), Re("span",{children:e.name})]},e.id))})]}), Re("div",{className:"about-section-title",children:le("techStack")}), De("div",{className:"about-tech-grid",children:[ Re(cy,{name:"Plasmo",version:"v0.89.0",desc:le("tsPlasmoDesc")}), Re(cy,{name:"React",version:"v18.2.0",desc:le("tsReactDesc")}), Re(cy,{name:"TypeScript",version:"v5.3.3",desc:le("tsTypescriptDesc")}), Re(cy,{name:"Zustand",version:"v5.0.3",desc:le("tsZustandDesc")}), Re(cy,{name:"Vite",version:"v5.0.0",desc:le("tsViteDesc")})]}), Re("div",{className:"about-section-title",children:le("credits")}), De("div",{className:"about-simple-card",children:[ De("div",{className:"about-simple-header",children:[ Re(gt,{size:18,style:{color:"#ef4444"}}),le("devAndMaintain")]}), Re("p",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:1.6,marginBottom:16},children:le("creditsDesc")}), De("div",{style:{display:"flex",gap:8},children:[ Re(dy,{text:"Made with ❤️"}), Re(dy,{text:"Open Source"}), Re(dy,{text:"Privacy First"})]}), De("div",{style:{marginTop:16,fontSize:"12px",color:"var(--gh-text-secondary)"},children:["GNU GPLv3 © ", (new Date).getFullYear()," ",Rf]})]}), De("div",{className:"about-privacy-banner",children:[ Re(pt,{size:24,className:"about-privacy-icon"}), De("div",{children:[ Re("div",{className:"about-privacy-title",children:le("privacyTitle")}), Re("div",{className:"about-privacy-desc",children:le("privacyText")})]})]})]})},cy=({name:e,version:t,desc:n})=>De("div",{className:"about-tech-card",children:[ De("div",{className:"about-tech-header",children:[ Re("div",{className:"about-tech-name",children:e}), Re("div",{className:"about-tech-version",children:t})]}), Re("div",{className:"about-tech-desc",children:n})]}),dy=({text:e})=>Re("span",{style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border)",borderRadius:"12px",fontSize:"12px",color:"var(--gh-text-secondary)"},children:e});function uy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function hy(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=false;try{n=this instanceof e;}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype;}else n={};return Object.defineProperty(n,"__esModule",{value:true}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:true,get:function(){return e[t]}});}),n}var gy,py;function my(){if(py)return gy;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],o=typeof r;"object"!==o&&"function"!==o||Object.isFrozen(r)||e(r);}),t}py=1;class t{constructor(e){ void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=false;}ignoreMatch(){this.isMatchIgnored=true;}}function n(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(e){for(const t in e)n[t]=e[t];}),n}const o=e=>!!e.scope;class i{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this);}addText(e){this.buffer+=n(e);}openNode(e){if(!o(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return [`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return `${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t);}closeNode(e){o(e)&&(this.buffer+="");}value(){return this.buffer}span(e){this.buffer+=``;}}const a=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class s{constructor(){this.rootNode=a(),this.stack=[this.rootNode];}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e);}openNode(e){const t=a({scope:e});this.add(t),this.stack.push(t);}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return "string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{s._collapse(e);}));}}class l extends s{constructor(e){super(),this.options=e;}addText(e){""!==e&&this.add(e);}startScope(e){this.openNode(e);}endScope(){this.closeNode();}__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n);}toHTML(){return new i(this,this.options).value()}finalize(){return this.closeAllNodes(),true}}function c(e){return e?"string"==typeof e?e:e.source:null}function d(e){return g("(?=",e,")")}function u(e){return g("(?:",e,")*")}function h(e){return g("(?:",e,")?")}function g(...e){return e.map(e=>c(e)).join("")}function p(...e){const t=function(e){const t=e[e.length-1];return "object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return "("+(t.capture?"":"?:")+e.map(e=>c(e)).join("|")+")"}function m(e){return new RegExp(e.toString()+"|").exec("").length-1}const f=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function b(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=c(e),o="";for(;r.length>0;){const e=f.exec(r);if(!e){o+=r;break}o+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?o+="\\"+String(Number(e[1])+t):(o+=e[0],"("===e[0]&&n++);}return o}).map(e=>`(${e})`).join(t)}const y="[a-zA-Z]\\w*",v="[a-zA-Z_]\\w*",x="\\b\\d+(\\.\\d+)?",w="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",S="\\b(0b[01]+)",C={begin:"\\\\[\\s\\S]",relevance:0},k={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[C]},T={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[C]},E=function(e,t,n={}){const o=r({scope:"comment",begin:e,end:t,contains:[]},n);o.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:true,relevance:0});const i=p("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return o.contains.push({begin:g(/[ ]+/,"(",i,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),o},A=E("//","$"),M=E("/\\*","\\*/"),I=E("#","$"),L={scope:"number",begin:x,relevance:0},N={scope:"number",begin:w,relevance:0},R={scope:"number",begin:S,relevance:0},D={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[C,{begin:/\[/,end:/\]/,relevance:0,contains:[C]}]},P={scope:"title",begin:y,relevance:0},q={scope:"title",begin:v,relevance:0},B={begin:"\\.\\s*"+v,relevance:0};var $=Object.freeze({__proto__:null,APOS_STRING_MODE:k,BACKSLASH_ESCAPE:C,BINARY_NUMBER_MODE:R,BINARY_NUMBER_RE:S,COMMENT:E,C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:A,C_NUMBER_MODE:N,C_NUMBER_RE:w,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1];},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch();}})},HASH_COMMENT_MODE:I,IDENT_RE:y,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:B,NUMBER_MODE:L,NUMBER_RE:x,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:T,REGEXP_MODE:D,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=g(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch();}},e)},TITLE_MODE:P,UNDERSCORE_IDENT_RE:v,UNDERSCORE_TITLE_MODE:q});function _(e,t){"."===e.input[e.index-1]&&t.ignoreMatch();}function O(e,t){ void 0!==e.className&&(e.scope=e.className,delete e.className);}function z(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=_,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0));}function F(e,t){Array.isArray(e.illegal)&&(e.illegal=p(...e.illegal));}function U(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match;}}function H(e,t){ void 0===e.relevance&&(e.relevance=1);}const W=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t];}),e.keywords=n.keywords,e.begin=g(n.beforeMatch,d(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:true})]},e.relevance=0,delete n.beforeMatch;},j=["of","and","for","in","not","or","if","then","parent","list","value"];function G(e,t,n="keyword"){const r=Object.create(null);return "string"==typeof e?o(n,e.split(" ")):Array.isArray(e)?o(n,e):Object.keys(e).forEach(function(n){Object.assign(r,G(e[n],t,n));}),r;function o(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,V(n[0],n[1])];});}}function V(e,t){return t?Number(t):function(e){return j.includes(e.toLowerCase())}(e)?0:1}const Q={},K=e=>{console.error(e);},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t);},Y=(e,t)=>{Q[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),Q[`${e}/${t}`]=true);},X=new Error;function J(e,t,{key:n}){let r=0;const o=e[n],i={},a={};for(let s=1;s<=t.length;s++)a[s+r]=o[s],i[s+r]=true,r+=m(t[s-1]);e[n]=a,e[n]._emit=i,e[n]._multi=true;}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope);}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),X;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"),X;J(e,e.begin,{key:"beginScope"}),e.begin=b(e.begin,{joinWith:""});}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"),X;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"),X;J(e,e.end,{key:"endScope"}),e.end=b(e.end,{joinWith:""});}}(e);}function te(e){function t(t,n){return new RegExp(c(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0;} // @ts-ignore addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=m(e)+1;}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(b(e,{joinWith:"|"}),true),this.lastIndex=0;}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class o{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0;} // @ts-ignore getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0;} // @ts-ignore addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++;}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else {const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e);}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(i,a){const s=i;if(i.isCompiled)return s;[O,U,ee,W].forEach(e=>e(i,a)),e.compilerExtensions.forEach(e=>e(i,a)),i.__beforeBegin=null,[z,F,H].forEach(e=>e(i,a)),i.isCompiled=true;let l=null;return "object"==typeof i.keywords&&i.keywords.$pattern&&(i.keywords=Object.assign({},i.keywords),l=i.keywords.$pattern,delete i.keywords.$pattern),l=l||/\w+/,i.keywords&&(i.keywords=G(i.keywords,e.case_insensitive)),s.keywordPatternRe=t(l,true),a&&(i.begin||(i.begin=/\B|\b/),s.beginRe=t(s.begin),i.end||i.endsWithParent||(i.end=/\B|\b/),i.end&&(s.endRe=t(s.end)),s.terminatorEnd=c(s.end)||"",i.endsWithParent&&a.terminatorEnd&&(s.terminatorEnd+=(i.end?"|":"")+a.terminatorEnd)),i.illegal&&(s.illegalRe=t(i.illegal)),i.contains||(i.contains=[]),i.contains=[].concat(...i.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?i:e)})),i.contains.forEach(function(e){n(e,s);}),i.starts&&n(i.starts,a),s.matcher=function(e){const t=new o;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(s),s}(e)}function ne(e){return !!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t;}}const oe=n,ie=r,ae=Symbol("nomatch"),se=function(n){const r=Object.create(null),o=Object.create(null),i=[];let a=true;const s="Could not find the language '{}', did you forget to load/include a language module?",c={disableAutodetect:true,name:"Plain text",contains:[]};let m={ignoreUnescapedHTML:false,throwUnescapedHTML:false,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:l};function f(e){return m.noHighlightRe.test(e)}function b(e,t,n){let r="",o="";"object"==typeof t?(r=e,n=t.ignoreIllegals,o=t.language):(Y("10.7.0","highlight(lang, code, ...args) has been deprecated."),Y("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),o=e,r=t),void 0===n&&(n=true);const i={code:r,language:o};E("before:highlight",i);const a=i.result?i.result:y(i.language,i.code,n);return a.code=i.code,E("after:highlight",a),a}function y(e,n,o,i){const l=Object.create(null);function c(e,t){return e.keywords[t]}function d(){if(!A.keywords)return void I.addText(L);let e=0;A.keywordPatternRe.lastIndex=0;let t=A.keywordPatternRe.exec(L),n="";for(;t;){n+=L.substring(e,t.index);const r=k.case_insensitive?t[0].toLowerCase():t[0],o=c(A,r);if(o){const[e,i]=o;if(I.addText(n),n="",l[r]=(l[r]||0)+1,l[r]<=7&&(N+=i),e.startsWith("_"))n+=t[0];else {const n=k.classNameAliases[e]||e;h(t[0],n);}}else n+=t[0];e=A.keywordPatternRe.lastIndex,t=A.keywordPatternRe.exec(L);}n+=L.substring(e),I.addText(n);}function u(){null!=A.subLanguage?function(){if(""===L)return;let e=null;if("string"==typeof A.subLanguage){if(!r[A.subLanguage])return void I.addText(L);e=y(A.subLanguage,L,true,M[A.subLanguage]),M[A.subLanguage]=e._top;}else e=v(L,A.subLanguage.length?A.subLanguage:null);A.relevance>0&&(N+=e.relevance),I.__addSublanguage(e._emitter,e.language);}():d(),L="";}function h(e,t){""!==e&&(I.startScope(t),I.addText(e),I.endScope());}function g(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=k.classNameAliases[e[n]]||e[n],o=t[n];r?h(o,r):(L=o,d(),L=""),n++;}}function p(e,t){return e.scope&&"string"==typeof e.scope&&I.openNode(k.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(h(L,k.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),L=""):e.beginScope._multi&&(g(e.beginScope,t),L="")),A=Object.create(e,{parent:{value:A}}),A}function f(e,n,r){let o=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(o){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(o=false);}if(o){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return f(e.parent,n,r)}function b(e){return 0===A.matcher.regexIndex?(L+=e[0],1):(P=true,0)}function x(e){const t=e[0],r=n.substring(e.index),o=f(A,e,r);if(!o)return ae;const i=A;A.endScope&&A.endScope._wrap?(u(),h(t,A.endScope._wrap)):A.endScope&&A.endScope._multi?(u(),g(A.endScope,e)):i.skip?L+=t:(i.returnEnd||i.excludeEnd||(L+=t),u(),i.excludeEnd&&(L=t));do{A.scope&&I.closeNode(),A.skip||A.subLanguage||(N+=A.relevance),A=A.parent;}while(A!==o.parent);return o.starts&&p(o.starts,e),i.returnEnd?0:t.length}let w={};function S(r,i){const s=i&&i[0];if(L+=r,null==s)return u(),0;if("begin"===w.type&&"end"===i.type&&w.index===i.index&&""===s){if(L+=n.slice(i.index,i.index+1),!a){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=w.rule,t}return 1}if(w=i,"begin"===i.type)return function(e){const n=e[0],r=e.rule,o=new t(r),i=[r.__beforeBegin,r["on:begin"]];for(const t of i)if(t&&(t(e,o),o.isMatchIgnored))return b(n);return r.skip?L+=n:(r.excludeBegin&&(L+=n),u(),r.returnBegin||r.excludeBegin||(L=n)),p(r,e),r.returnBegin?0:n.length}(i);if("illegal"===i.type&&!o){const e=new Error('Illegal lexeme "'+s+'" for mode "'+(A.scope||"")+'"');throw e.mode=A,e}if("end"===i.type){const e=x(i);if(e!==ae)return e}if("illegal"===i.type&&""===s)return L+="\n",1;if(D>1e5&&D>3*i.index){throw new Error("potential infinite loop, way more iterations than matches")}return L+=s,s.length}const k=C(e);if(!k)throw K(s.replace("{}",e)),new Error('Unknown language: "'+e+'"');const T=te(k);let E="",A=i||T;const M={},I=new m.__emitter(m);!function(){const e=[];for(let t=A;t!==k;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>I.openNode(e));}();let L="",N=0,R=0,D=0,P=false;try{if(k.__emitTokens)k.__emitTokens(n,I);else {for(A.matcher.considerAll();;){D++,P?P=!1:A.matcher.considerAll(),A.matcher.lastIndex=R;const e=A.matcher.exec(n);if(!e)break;const t=S(n.substring(R,e.index),e);R=e.index+t;}S(n.substring(R));}return I.finalize(),E=I.toHTML(),{language:e,value:E,relevance:N,illegal:!1,_emitter:I,_top:A}}catch(q){if(q.message&&q.message.includes("Illegal"))return {language:e,value:oe(n),illegal:true,relevance:0,_illegalBy:{message:q.message,index:R,context:n.slice(R-100,R+100),mode:q.mode,resultSoFar:E},_emitter:I};if(a)return {language:e,value:oe(n),illegal:false,relevance:0,errorRaised:q,_emitter:I,_top:A};throw q}}function v(e,t){t=t||m.languages||Object.keys(r);const n=function(e){const t={value:oe(e),illegal:false,relevance:0,_top:c,_emitter:new m.__emitter(m)};return t._emitter.addText(e),t}(e),o=t.filter(C).filter(T).map(t=>y(t,e,false));o.unshift(n);const i=o.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(C(e.language).supersetOf===t.language)return 1;if(C(t.language).supersetOf===e.language)return -1}return 0}),[a,s]=i,l=a;return l.secondBest=s,l}function x(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=m.languageDetectRe.exec(t);if(n){const t=C(n[1]);return t||(Z(s.replace("{}",n[1])),Z("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>f(e)||C(e))}(e);if(f(n))return;if(E("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(m.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),m.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,i=n?b(r,{language:n,ignoreIllegals:true}):v(r);e.innerHTML=i.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&o[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`);}(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),E("after:highlightElement",{el:e,result:i,text:r});}let w=false;function S(){if("loading"===document.readyState)return w||window.addEventListener("DOMContentLoaded",function(){S();},false),void(w=true);document.querySelectorAll(m.cssSelector).forEach(x);}function C(e){return e=(e||"").toLowerCase(),r[e]||r[o[e]]}function k(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{o[e.toLowerCase()]=t;});}function T(e){const t=C(e);return t&&!t.disableAutodetect}function E(e,t){const n=e;i.forEach(function(e){e[n]&&e[n](t);});}Object.assign(n,{highlight:b,highlightAuto:v,highlightAll:S,highlightElement:x,highlightBlock:function(e){return Y("10.7.0","highlightBlock will be removed entirely in v12.0"),Y("10.7.0","Please use highlightElement now."),x(e)},configure:function(e){m=ie(m,e);},initHighlighting:()=>{S(),Y("10.6.0","initHighlighting() deprecated. Use highlightAll() now.");},initHighlightingOnLoad:function(){S(),Y("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.");},registerLanguage:function(e,t){let o=null;try{o=t(n);}catch(i){if(K("Language definition for '{}' could not be registered.".replace("{}",e)),!a)throw i;K(i),o=c;}o.name||(o.name=e),r[e]=o,o.rawDefinition=t.bind(null,n),o.aliases&&k(o.aliases,{languageName:e});},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(o))o[t]===e&&delete o[t];},listLanguages:function(){return Object.keys(r)},getLanguage:C,registerAliases:k,autoDetection:T,inherit:ie,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t));}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t));});}(e),i.push(e);},removePlugin:function(e){const t=i.indexOf(e);-1!==t&&i.splice(t,1);}}),n.debugMode=function(){a=false;},n.safeMode=function(){a=true;},n.versionString="11.11.1",n.regex={concat:g,lookahead:d,either:p,optional:h,anyNumberOfTimes:u};for(const t in $)"object"==typeof $[t]&&e($[t]);return Object.assign(n,$),n},le=se({});return le.newInstance=()=>se({}),gy=le,le.HighlightJS=le,le.default=le,gy}const fy=uy(my()),by=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],yy=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),vy=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),xy=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),wy=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src", // @font-face "stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();var Sy={};const Cy=hy(U);var ky;const Ty=uy(function(){if(ky)return Sy;ky=1;var e=Sy&&Sy.__extends||function(){var e=function(t,n){return (e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);})(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r);}}(),t=Sy&&Sy.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1){e._history.stack=l.slice(0,c+1);var d=e._history.stack.length;if(d>100){var u=d-100;e._history.stack=l.slice(u,d),e._history.offset=Math.max(e._history.offset-u,0);}}var h=Date.now();if(r){var g=e._history.stack[e._history.offset];if(g&&h-g.timestamp<3e3){var p=/[^a-z0-9]([a-z0-9]+)$/i,m=null===(o=e._getLines(g.value,g.selectionStart).pop())||void 0===o?void 0:o.match(p),f=null===(i=e._getLines(n.value,n.selectionStart).pop())||void 0===i?void 0:i.match(p);if((null==m?void 0:m[1])&&(null===(a=null==f?void 0:f[1])||void 0===a?void 0:a.startsWith(m[1])))return void(e._history.stack[e._history.offset]=t(t({},n),{timestamp:h}))}}e._history.stack.push(t(t({},n),{timestamp:h})),e._history.offset++;},e._updateInput=function(t){var n=e._input;n&&(n.value=t.value,n.selectionStart=t.selectionStart,n.selectionEnd=t.selectionEnd,e.props.onValueChange(t.value));},e._applyEdits=function(n){var r=e._input,o=e._history.stack[e._history.offset];o&&r&&(e._history.stack[e._history.offset]=t(t({},o),{selectionStart:r.selectionStart,selectionEnd:r.selectionEnd})),e._recordChange(n),e._updateInput(n);},e._undoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r-1];o&&(e._updateInput(o),e._history.offset=Math.max(r-1,0));},e._redoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r+1];o&&(e._updateInput(o),e._history.offset=Math.min(r+1,n.length-1));},e._handleKeyDown=function(t){var n=e.props,r=n.tabSize,o=n.insertSpaces,i=n.ignoreTabKey,a=n.onKeyDown;if(!a||(a(t),!t.defaultPrevented)){27===t.keyCode&&t.currentTarget.blur();var c=t.currentTarget,d=c.value,u=c.selectionStart,h=c.selectionEnd,g=(o?" ":"\t").repeat(r);if(9===t.keyCode&&!i&&e.state.capture)if(t.preventDefault(),t.shiftKey){var p=(y=e._getLines(d,u)).length-1,m=e._getLines(d,h).length-1,f=d.split("\n").map(function(e,t){return t>=p&&t<=m&&e.startsWith(g)?e.substring(g.length):e}).join("\n");if(d!==f){var b=y[p];e._applyEdits({value:f,selectionStart:(null==b?void 0:b.startsWith(g))?u-g.length:u,selectionEnd:h-(d.length-f.length)});}}else if(u!==h){var y,v=(y=e._getLines(d,u)).length-1,x=e._getLines(d,h).length-1;b=y[v];e._applyEdits({value:d.split("\n").map(function(e,t){return t>=v&&t<=x?g+e:e}).join("\n"),selectionStart:b&&/\S/.test(b)?u+g.length:u,selectionEnd:h+g.length*(x-v+1)});}else {var w=u+g.length;e._applyEdits({value:d.substring(0,u)+g+d.substring(h),selectionStart:w,selectionEnd:w});}else if(8===t.keyCode){var S=u!==h;if(d.substring(0,u).endsWith(g)&&!S){t.preventDefault();w=u-g.length;e._applyEdits({value:d.substring(0,u-g.length)+d.substring(h),selectionStart:w,selectionEnd:w});}}else if(13===t.keyCode){if(u===h){var C=e._getLines(d,u).pop(),k=null==C?void 0:C.match(/^\s+/);if(null==k?void 0:k[0]){t.preventDefault();var T="\n"+k[0];w=u+T.length;e._applyEdits({value:d.substring(0,u)+T+d.substring(h),selectionStart:w,selectionEnd:w});}}}else if(57===t.keyCode||219===t.keyCode||222===t.keyCode||192===t.keyCode){var E=void 0;57===t.keyCode&&t.shiftKey?E=["(",")"]:219===t.keyCode?E=t.shiftKey?["{","}"]:["[","]"]:222===t.keyCode?E=t.shiftKey?['"','"']:["'","'"]:192!==t.keyCode||t.shiftKey||(E=["`","`"]),u!==h&&E&&(t.preventDefault(),e._applyEdits({value:d.substring(0,u)+E[0]+d.substring(u,h)+E[1]+d.substring(h),selectionStart:u,selectionEnd:h+2}));}else !(l?t.metaKey&&90===t.keyCode:t.ctrlKey&&90===t.keyCode)||t.shiftKey||t.altKey?(l?t.metaKey&&90===t.keyCode&&t.shiftKey:s?t.ctrlKey&&89===t.keyCode:t.ctrlKey&&90===t.keyCode&&t.shiftKey)&&!t.altKey?(t.preventDefault(),e._redoEdit()):77!==t.keyCode||!t.ctrlKey||l&&!t.shiftKey||(t.preventDefault(),e.setState(function(e){return {capture:!e.capture}})):(t.preventDefault(),e._undoEdit());}},e._handleChange=function(t){var n=t.currentTarget,r=n.value,o=n.selectionStart,i=n.selectionEnd;e._recordChange({value:r,selectionStart:o,selectionEnd:i},true),e.props.onValueChange(r);},e._history={stack:[],offset:-1},e._input=null,e}return e(r,n),r.prototype.componentDidMount=function(){this._recordCurrentState();},Object.defineProperty(r.prototype,"session",{get:function(){return {history:this._history}},set:function(e){this._history=e.history;},enumerable:false,configurable:true}),r.prototype.render=function(){var e=this,n=this.props,r=n.value,o=n.style,s=n.padding,l=n.highlight,u=n.textareaId,g=n.textareaClassName,p=n.autoFocus,m=n.disabled,f=n.form,b=n.maxLength,y=n.minLength,v=n.name,x=n.placeholder,w=n.readOnly,S=n.required,C=n.onClick,k=n.onFocus,T=n.onBlur,E=n.onKeyUp;n.onKeyDown,n.onValueChange,n.tabSize,n.insertSpaces,n.ignoreTabKey;var A=n.preClassName,M=i(n,["value","style","padding","highlight","textareaId","textareaClassName","autoFocus","disabled","form","maxLength","minLength","name","placeholder","readOnly","required","onClick","onFocus","onBlur","onKeyUp","onKeyDown","onValueChange","tabSize","insertSpaces","ignoreTabKey","preClassName"]),I={paddingTop:"object"==typeof s?s.top:s,paddingRight:"object"==typeof s?s.right:s,paddingBottom:"object"==typeof s?s.bottom:s,paddingLeft:"object"==typeof s?s.left:s},L=l(r);return a.createElement("div",t({},M,{style:t(t({},h.container),o)}),a.createElement("pre",t({className:A,"aria-hidden":"true",style:t(t(t({},h.editor),h.highlight),I)},"string"==typeof L?{dangerouslySetInnerHTML:{__html:L+"
"}}:{children:L})),a.createElement("textarea",{ref:function(t){return e._input=t},style:t(t(t({},h.editor),h.textarea),I),className:c+(g?" ".concat(g):""),id:u,value:r,onChange:this._handleChange,onKeyDown:this._handleKeyDown,onClick:C,onKeyUp:E,onFocus:k,onBlur:T,disabled:m,form:f,maxLength:b,minLength:y,name:v,placeholder:x,readOnly:w,required:S,autoFocus:p,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:false,"data-gramm":false}),a.createElement("style",{dangerouslySetInnerHTML:{__html:d}}))},r.defaultProps={tabSize:2,insertSpaces:true,ignoreTabKey:false,padding:0},r}(a.Component);Sy.default=u;var h={container:{position:"relative",textAlign:"left",boxSizing:"border-box",padding:0,overflow:"hidden"},textarea:{position:"absolute",top:0,left:0,height:"100%",width:"100%",resize:"none",color:"inherit",overflow:"hidden",MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",WebkitTextFillColor:"transparent"},highlight:{position:"relative",pointerEvents:"none"},editor:{margin:0,border:0,background:"none",boxSizing:"inherit",display:"inherit",fontFamily:"inherit",fontSize:"inherit",fontStyle:"inherit",fontVariantLigatures:"inherit",fontWeight:"inherit",letterSpacing:"inherit",lineHeight:"inherit",tabSize:"inherit",textIndent:"inherit",textRendering:"inherit",textTransform:"inherit",whiteSpace:"pre-wrap",wordBreak:"keep-all",overflowWrap:"break-word"}};return Sy}());class Ey extends s{constructor(e){super(e);let t=false;try{document.createElement("div").innerHTML="";}catch{t=true;}this.state={hasError:t};}static getDerivedStateFromError(e){return {hasError:true}}componentDidCatch(e,t){}render(){if(this.state.hasError){const{value:e,onValueChange:t,style:n,placeholder:r,className:o,fallbackPlaceholder:i}=this.props; return Re("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:Re("textarea",{className:`settings-textarea ${o||""}`,value:e,onChange:e=>t(e.target.value),placeholder:i||r,style:{...n,fontFamily:'"Menlo", "Monaco", "Consolas", monospace',resize:"none",flex:1,width:"100%",height:"100%",border:"none",outline:"none",padding:"12px"}})})} return Re(Ty,{...this.props})}}const Ay=({preset:e})=>{const t=e.variables,n=t["--gh-bg"]||"#ffffff",r=t["--gh-header-bg"]||t["--gh-primary"]||"#4285f4",o=t["--gh-border"]||"#e5e7eb",i=t["--gh-primary"]||"#4285f4",a=t["--gh-text"]||"#374151",s=t["--gh-text-secondary"]||"#9ca3af",l=t["--gh-bg-secondary"]||"#f3f4f6"; return De("div",{className:"theme-preview-layout",style:{backgroundColor:n,borderColor:o},children:[ De("div",{className:"theme-preview-header",style:{backgroundColor:r},children:[ Re("div",{className:"theme-preview-dot"}), Re("div",{className:"theme-preview-dot delay-1"}), Re("div",{className:"theme-preview-dot delay-2"})]}), De("div",{className:"theme-preview-body",children:[ De("div",{className:"theme-preview-sidebar",style:{backgroundColor:l,borderColor:o},children:[ Re("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.3}}), Re("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), Re("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), Re("div",{className:"theme-preview-active-item",style:{backgroundColor:i,opacity:.15}})]}), De("div",{className:"theme-preview-content",children:[ Re("div",{className:"theme-preview-hero",style:{backgroundColor:i,opacity:.1}}), De("div",{className:"theme-preview-row",children:[ Re("div",{className:"theme-preview-avatar",style:{backgroundColor:s,opacity:.2}}), De("div",{style:{flex:1},children:[ Re("div",{className:"theme-preview-line",style:{backgroundColor:a,opacity:.6,marginBottom:4}}), Re("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.4}})]})]}), Re("div",{className:"theme-preview-button",style:{backgroundColor:i}})]})]})]})};fy.registerLanguage("css",function(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return {name:"CSS",case_insensitive:true,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+vy.join("|")+")"},{begin:":(:)?("+xy.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+wy.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:true,excludeEnd:true}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:true,excludeEnd:true,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:yy.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+by.join("|")+")\\b"}]}});const My=({preset:e,isActive:t,onClick:n})=>{const r=`themePreset_${e.id}`,o=le(r),i=o&&o!==r?o:e.name; return De("div",{className:"settings-theme-card "+(t?"active":""),onClick:n,children:[ Re(Ay,{preset:e}), Re("div",{className:"settings-theme-name",children:i})]})},Iy=({siteId:e,initialTab:t})=>{const[n,r]=_(t||Dr),{settings:o,setSettings:i}=Mi();L(()=>{t&&r(t);},[t]);const[a,s]=_(false),[l,c]=_(null),d=o?.theme?.sites?.[e]||o?.theme?.sites?._default;if(!o)return null;const u=[{id:Dr,label:le("themePresetsTab")},{id:Pr,label:le("customStylesTab")}],h=o?.theme?.customStyles||[],g=e=>{const t=(e=>{const t={},n=/(--[\w-]+)\s*:\s*([^;]+);/g;let r;for(;null!==(r=n.exec(e));){const e=r[1],n=r[2].trim();t[e]=n;}return t})(e.css),n={"--gh-bg":"light"===e.mode?"#f3f4f6":"#1f2937","--gh-header-bg":"light"===e.mode?"#e5e7eb":"#374151","--gh-border":"light"===e.mode?"#d1d5db":"#4b5563","--gh-primary":"#4285f4","--gh-text":"light"===e.mode?"#374151":"#f9fafb","--gh-text-secondary":"light"===e.mode?"#6b7280":"#9ca3af","--gh-bg-secondary":"light"===e.mode?"#ffffff":"#1f2937"};return {id:e.id,name:e.name,variables:{...n,...t}}},p=[...Wm,...h.filter(e=>"light"===e.mode).map(g)],m=[...jm,...h.filter(e=>"dark"===e.mode).map(g)]; return De("div",{children:[ Re(sy,{title:le("navAppearance"),Icon:at}), Re("p",{className:"settings-page-desc",children:le("appearancePageDesc")}), Re(ry,{settingId:"appearance-theme-sync",children:Re(iy,{label:le("syncNativePageThemeLabel"),description:le("syncNativePageThemeDesc"),checked:o?.theme?.syncNativePageTheme??true,onChange:()=>i({theme:{...o?.theme,syncNativePageTheme:!(o?.theme?.syncNativePageTheme??1)}}),settingId:"appearance-sync-native-page-theme"})}), Re(ay,{tabs:u,activeTab:n,onTabChange:r}),n===Dr&&De(Ne,{children:[ Re(ry,{title:le("lightModePreset"),description:le("lightModePresetDesc"),settingId:"appearance-preset-light",children:Re("div",{className:"settings-theme-grid",children:p.map(t=>Re(My,{preset:t,isActive:(d?.lightStyleId||"google-gradient")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("light");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"light"},lightStyleId:t}}}});})(t.id)},t.id))})}), Re(ry,{title:le("darkModePreset"),description:le("darkModePresetDesc"),settingId:"appearance-preset-dark",children:Re("div",{className:"settings-theme-grid",children:m.map(t=>Re(My,{preset:t,isActive:(d?.darkStyleId||"classic-dark")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("dark");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"dark"},darkStyleId:t}}}});})(t.id)},t.id))})})]}),n===Pr&&Re(Ne,{children:De(ry,{title:le("customCSS"),description:le("customCSSDesc"),settingId:"appearance-custom-styles",children:[ De("button",{className:"settings-btn settings-btn-primary",onClick:()=>{c({id:"",name:"",css:"/* 🎨 Custom CSS Cheat Sheet\n * 以下是本扩展使用的主要 CSS 类名,您可以自由覆盖。\n */\n\n/* === 主题变量 === */\n/*\n:host {\n --gh-bg: #ffffff;\n --gh-text: #1f2937;\n --gh-primary: #4285f4;\n}\n*/\n\n/* === 面板样式 === */\n/*\n.gh-main-panel { }\n.gh-panel-header { }\n.gh-panel-content { }\n*/\n",mode:"light"}),s(true);},style:{marginBottom:"16px"},children:["➕ ",le("addCustomStyle")]}),0===(o?.theme?.customStyles||[]).length?Re("div",{style:{padding:"20px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)",fontSize:"13px",border:"1px dashed var(--gh-border, #e5e7eb)",borderRadius:"8px"},children:le("noCustomStyles")}):Re("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:(o?.theme?.customStyles||[]).map(e=>De("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"8px"},children:[ De("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Re("span",{style:{fontSize:"11px",padding:"2px 8px",borderRadius:"4px",backgroundColor:"light"===e.mode?"rgba(251, 191, 36, 0.2)":"rgba(99, 102, 241, 0.2)",color:"light"===e.mode?"#b45309":"#4338ca"},children:"light"===e.mode?"☀️":"🌙"}), Re("span",{style:{fontSize:"14px",fontWeight:500},children:e.name||le("unnamedStyle")})]}), De("div",{style:{display:"flex",gap:"8px"},children:[ De("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{c(e),s(true);},style:{padding:"6px 12px",fontSize:"12px"},children:["✏️ ",le("edit")]}), Re("button",{className:"settings-btn settings-btn-danger",onClick:()=>(e=>{if(confirm(le("confirmDeleteStyle"))){const t=(o?.theme?.customStyles||[]).filter(t=>t.id!==e);i({theme:{...o?.theme,customStyles:t}});}})(e.id,e.name),style:{padding:"6px 12px",fontSize:"12px"},children:"🗑️"})]})]},e.id))})]})}),a&&l&&Re("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},children:De("div",{style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"800px",maxWidth:"95%",height:"85vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},children:[ De("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:l.id?le("editStyle"):le("newStyle")}), Re("button",{onClick:()=>s(false),style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:"✕"})]}), De("div",{style:{padding:"16px",overflowY:"auto",flex:1,display:"flex",flexDirection:"column"},children:[ De("div",{style:{marginBottom:"16px"},children:[ Re("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:le("styleNameLabel")}), Re("input",{type:"text",className:"settings-input",value:l.name,onChange:e=>c({...l,name:e.target.value}),placeholder:le("enterStyleName"),style:{width:"100%"}})]}), De("div",{style:{marginBottom:"16px"},children:[ Re("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:le("styleModeLabel")}), De("div",{style:{display:"flex",gap:"12px"},children:[ De("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ Re("input",{type:"radio",checked:"light"===l.mode,onChange:()=>c({...l,mode:"light"})}), De("span",{children:["☀️ ",le("lightMode")]})]}), De("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ Re("input",{type:"radio",checked:"dark"===l.mode,onChange:()=>c({...l,mode:"dark"})}), De("span",{children:["🌙 ",le("darkMode")]})]})]})]}), De("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[ De("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:["CSS ",le("code")]}), Re("div",{className:"settings-textarea",style:{flex:1,padding:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:Re(Ey,{value:l.css,onValueChange:e=>c({...l,css:e}),highlight:e=>Ad(fy.highlight(e,{language:"css"}).value),padding:12,style:{fontFamily:'"Menlo", "Monaco", "Consolas", monospace',fontSize:13,minHeight:"100%"},textareaClassName:"focus-outline-none"})})]})]}), De("div",{style:{padding:"16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>s(false),children:le("cancel")}), Re("button",{className:"settings-btn settings-btn-primary",onClick:()=>{if(!l)return;if(!l.name.trim())return void Pi(le("pleaseEnterStyleName"));const e=o?.theme?.customStyles||[];let t;if(l.id)t=e.map(e=>e.id===l.id?l:e);else {const n={...l,id:crypto.randomUUID()};t=[...e,n];}i({theme:{...o?.theme,customStyles:t}}),s(false),Pi(l.id?le("styleUpdated"):le("styleCreated"));},children:l.id?le("save"):le("create")})]})]})})]})};function Ly(e){const t=[];if(!e||"object"!=typeof e)return {valid:false,errorKeys:["backupValidationInvalidFormat"]};if(e.version||t.push("backupValidationMissingVersion"),!e.data||"object"!=typeof e.data)return t.push("backupValidationMissingData"),{valid:false,errorKeys:t};const n=e.data;return void 0!==n.settings&&("object"!=typeof n.settings||Array.isArray(n.settings))&&t.push("backupValidationSettingsType"),void 0!==n.prompts&&(Array.isArray(n.prompts)||t.push("backupValidationPromptsType")),void 0!==n.folders&&(Array.isArray(n.folders)||t.push("backupValidationFoldersType")),void 0!==n.conversations&&("object"!=typeof n.conversations||Array.isArray(n.conversations))&&t.push("backupValidationConversationsType"),void 0!==n.readingHistory&&("object"!=typeof n.readingHistory||Array.isArray(n.readingHistory))&&t.push("backupValidationHistoryType"),{valid:0===t.length,errorKeys:t}}function Ny(e,t){const n=e.getElementsByTagNameNS("*",t)[0];return n?.textContent?.trim()||null}function Ry(e,t,n){if(!e)return null;const r=function(e){try{return decodeURIComponent(e)}catch{return e}}(e.trim());if(!r.endsWith(".json")||!r.includes(`${Nf}_backup_`))return null;const o=t?parseInt(t.trim(),10):0,i=Number.isFinite(o)?o:0,a=n?new Date(n.trim()):new Date(0),s=Number.isNaN(a.getTime())?new Date(0):a;return {name:r.split("/").pop()||r,path:r,size:i,lastModified:s}}function Dy(e){return function(e){if("undefined"==typeof DOMParser)return null;try{const t=(new DOMParser).parseFromString(e,"application/xml");return function(e){return e.getElementsByTagName("parsererror").length>0}(t)?null:Array.from(t.getElementsByTagNameNS("*","response")).map(e=>Ry(Ny(e,"href"),Ny(e,"getcontentlength"),Ny(e,"getlastmodified"))).filter(e=>Boolean(e))}catch{return null}}(e)??function(e){const t="(?:[a-zA-Z0-9_-]+:)?",n=new RegExp(`<${t}response[^>]*>([\\s\\S]*?)<\\/${t}response>`,"gi");return Array.from(e.matchAll(n)).map(e=>{const n=e[1],r=n.match(new RegExp(`<${t}href[^>]*>([^<]+)<\\/${t}href>`,"i")),o=n.match(new RegExp(`<${t}getcontentlength[^>]*>([^<]+)<\\/${t}getcontentlength>`,"i")),i=n.match(new RegExp(`<${t}getlastmodified[^>]*>([^<]+)<\\/${t}getlastmodified>`,"i"));return Ry(r?.[1]??null,o?.[1]??null,i?.[1]??null)}).filter(e=>Boolean(e))}(e)}const Py=[{id:"jianguoyun",labelKey:"providerJianguoyun",urlTemplate:"https://dav.jianguoyun.com/dav/",hintKey:"providerJianguoyunHint",helpUrl:"https://help.jianguoyun.com/?p=2064",passwordPlaceholderKey:"providerJianguoyunPasswordPlaceholder"},{id:"infinicloud",labelKey:"providerInfinicloud",urlTemplate:"https://connect.infini.cloud/dav",hintKey:"providerInfinicloudHint"},{id:"pcloud",labelKey:"providerPcloud",urlTemplate:"https://webdav.pcloud.com",hintKey:"providerPcloudHint",helpUrl:"https://docs.pcloud.com/protocols/webdav_protocol/"},{id:"nextcloud",labelKey:"providerNextcloud",urlTemplate:"",urlPlaceholder:"https://your-domain.com/remote.php/dav/files/username/",hintKey:"providerNextcloudHint"},{id:"synology",labelKey:"providerSynology",urlTemplate:"",urlPlaceholder:"https://your-nas.example.com/webdav/",hintKey:"providerSynologyHint",helpUrl:"https://kb.synology.com/en-global/DSM/help/DSM/AdminCenter/file_webdav"},{id:"seafile",labelKey:"providerSeafile",urlTemplate:"",urlPlaceholder:"https://your-seafile-domain.com/seafdav",hintKey:"providerSeafileHint"},{id:"custom",labelKey:"providerCustom",urlTemplate:"",urlPlaceholder:"https://dav.example.com/dav/"}];function qy(e){return Py.some(t=>t.id===e)}function By(e){if(!e)return "custom";const t=e.toLowerCase();return t.includes("jianguoyun.com")||t.includes("nutscloud.com")?"jianguoyun":t.includes("infini.cloud")?"infinicloud":t.includes("pcloud.com")?"pcloud":t.includes("/remote.php/")?"nextcloud":t.includes("/seafdav")||t.includes("/seafile-webdav")?"seafile":t.includes(".quickconnect.to")||t.includes(".synology.me")||/\/webdav\//.test(t)?"synology":"custom"}const $y={enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:Nf};class _y{config=$y;autoSyncTimer=null;constructor(){this.loadConfig();}async loadConfig(){const{getSettingsState:e}=await o(async()=>{const{getSettingsState:e}=await Promise.resolve().then(()=>Ri);return {getSettingsState:e}},void 0),t=e();if(t?.webdav){const e={...$y,...t.webdav,provider:qy(t.webdav.provider)?t.webdav.provider:void 0};!e.provider&&e.url&&(e.provider=By(e.url)),this.config=e;}return this.config}async setConfig(e,t=true){if(this.config={...this.config,...e},t){const{useSettingsStore:e}=await o(async()=>{const{useSettingsStore:e}=await Promise.resolve().then(()=>Ri);return {useSettingsStore:e}},void 0);e.getState().setSettings({webdav:this.config});}}async saveConfig(e){return this.setConfig(e,true)}getConfig(){return {...this.config}}async testConnection(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const e=await this.request("PROPFIND",this.config.remoteDir,null,{Depth:"0"});return e.ok||404===e.status?{success:!0,messageKey:"webdavConnectionSuccess"}:401===e.status?{success:!1,messageKey:"webdavAuthFailed"}:{success:!1,messageKey:"webdavConnectionFailed",messageArgs:{status:e.status}}}catch(e){return {success:false,messageKey:"webdavConnectionFailed",messageArgs:{error:String(e)}}}}async upload(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});const e=await new Promise(e=>chrome.storage.local.get(null,e)),t=Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return ro.includes(e)&&n?.state&&(n=oo.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}})),n={version:3,timestamp:(new Date).toISOString(),data:t},r=function(){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return `${Nf}_backup_${t}-${n}-${r}_${o}-${i}-${a}.json`}(),o=this.buildRemotePath(r);if(this.config.remoteDir)try{await this.request("MKCOL",this.config.remoteDir);}catch{}const i=await this.request("PUT",o,JSON.stringify(n,null,2),{"Content-Type":"application/json"});if(i.ok||201===i.status||204===i.status){const e=Date.now();return await this.saveConfig({lastSyncTime:e,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavUploadSuccess",timestamp:e}}return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavUploadFailed",messageArgs:{status:i.status}}}catch(e){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavUploadFailed",messageArgs:{error:String(e)}}}}async getBackupList(e=10){if(!this.config.url||!this.config.username||!this.config.password)return [];try{const t='\n\n \n \n \n \n \n',n=await this.request("PROPFIND",this.config.remoteDir,t,{Depth:"1","Content-Type":"application/xml"});if(!n.ok)return [];const r=Dy(await n.text());return r.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),r.slice(0,e)}catch(t){return console.error("Failed to get backup list:",t),[]}}async deleteFile(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const t=this.buildRemotePath(e),n=await this.request("DELETE",t);return n.ok||204===n.status||404===n.status?{success:!0,messageKey:"webdavDeleteSuccess"}:{success:!1,messageKey:"webdavDeleteFailed",messageArgs:{status:n.status}}}catch(t){return {success:false,messageKey:"webdavDeleteFailed",messageArgs:{error:String(t)}}}}async download(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});let t=e;if(!t){const e=await this.getBackupList(1);if(0===e.length)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavFileNotFound"};t=e[0].name;}const n=this.buildRemotePath(t),r=await this.request("GET",n);if(!r.ok)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavDownloadFailed",messageArgs:{status:r.status}};const o=await r.text(),i=JSON.parse(o),a=Ly(i);if(!a.valid)return console.error("Backup validation failed:",a.errorKeys),await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavInvalidFormat"};const s=this.config,l=Object.fromEntries(Object.entries(i.data).map(([e,t])=>{if(null==t)return [e,t];if(ro.includes(e)){let n;if(oo.includes(e))if("object"!=typeof t||Array.isArray(t))n="readingHistory"===e?{history:t}:{[e]:t};else {const r=t;n="conversations"===e&&void 0!==r.conversations?t:"readingHistory"!==e||void 0===r.history&&void 0===r.lastCleanupRun?"readingHistory"===e?{history:t}:{[e]:t}:t;}else n={[e]:t};return [e,JSON.stringify({state:n,version:0})]}return "object"==typeof t?[e,JSON.stringify(t)]:[e,t]}));await new Promise((e,t)=>chrome.storage.local.set(l,()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await new Promise((e,t)=>{chrome.storage.local.get("settings",n=>{if(chrome.runtime.lastError)return void t(chrome.runtime.lastError);let r=n.settings;if("string"==typeof r)try{r=JSON.parse(r);}catch{return void e()}r?.state?.settings&&(r.state.settings.webdav=s),chrome.storage.local.set({settings:JSON.stringify(r)},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e());});});const c=Date.now();return await this.saveConfig({lastSyncTime:c,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavDownloadSuccess",timestamp:c}}catch(t){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavDownloadFailed",messageArgs:{error:String(t)}}}}startAutoSync(){this.stopAutoSync(),this.config.enabled&&"auto"===this.config.syncMode&&this.config.syncInterval>0&&(this.autoSyncTimer=setInterval(()=>{this.upload();},60*this.config.syncInterval*1e3));}stopAutoSync(){this.autoSyncTimer&&(clearInterval(this.autoSyncTimer),this.autoSyncTimer=null);}buildRemotePath(e){let t=this.config.remoteDir.trim();return t=t.replace(/^\/+|\/+$/g,""),t?`${t}/${e}`:e}async request(e,t,n,r){const o=this.buildUrl(t);return this.requestViaGM(e,o,n,r)}requestViaGM(e,t,n,r){return new Promise((o,i)=>{const a={...r};if(this.config.username&&this.config.password){const e=btoa(`${this.config.username}:${this.config.password}`);a.Authorization=`Basic ${e}`;}GM_xmlhttpRequest({method:e,url:t,headers:a,data:n||void 0,onload:e=>{o({ok:e.status>=200&&e.status<300,status:e.status,statusText:e.statusText,text:async()=>e.responseText,headers:{get:t=>{const n=e.responseHeaders?.split("\r\n")||[];for(const e of n){const[n,...r]=e.split(":");if(n?.toLowerCase()===t.toLowerCase())return r.join(":").trim()}return null}}});},onerror:e=>{i(new Error(e.statusText||"GM_xmlhttpRequest failed"));},ontimeout:()=>{i(new Error("Request timeout"));}});})}async requestViaBackground(e,t,n,r){const o=await chrome.runtime.sendMessage({type:"WEBDAV_REQUEST",method:e,url:t,body:n,headers:r,auth:{username:this.config.username,password:this.config.password}});if(!o.success)throw new Error(o.error||"WebDAV request failed");return {ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,text:async()=>o.body,headers:{get:e=>o.headers?.[e.toLowerCase()]||null}}}buildUrl(e){let t=this.config.url.trim();t.endsWith("/")||(t+="/");return t+e.replace(/^\/+/,"")}}let Oy=null;function zy(){return Oy||(Oy=new _y),Oy}let Fy=null;const Uy=Fo()(Wo((e,t)=>(Fy=()=>e({_hasHydrated:true}),{history:{},lastCleanupRun:0,_hasHydrated:false,savePosition:(t,n)=>e(e=>({history:{...e.history,[t]:n}})),getPosition:e=>t().history[e],cleanup:n=>{if(-1===n)return;const r=Date.now(),o=t();if(r-o.lastCleanupRun<864e5)return;const i=24*n*60*60*1e3,a={};let s=false;for(const[e,t]of Object.entries(o.history))r-t.ts<=i?a[e]=t:s=true;e(s?{history:a,lastCleanupRun:r}:{lastCleanupRun:r});},setHasHydrated:t=>e({_hasHydrated:t})}),{name:"readingHistory",storage:Uo(()=>gi),partialize:e=>({history:e.history,lastCleanupRun:e.lastCleanupRun}),onRehydrateStorage:()=>()=>{Fy?.();}})),Hy=()=>Uy.getState(),Wy=Object.freeze(Object.defineProperty({__proto__:null,getReadingHistoryStore:Hy,useReadingHistoryStore:Uy},Symbol.toStringTag,{value:"Module"})),jy=e=>{if(0===e)return "0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["B","KB","MB","GB","TB"][t]},Gy=e=>e instanceof Error?e.message:String(e),Vy=({onClose:e,onRestore:t})=>{const[n,r]=_([]),[o,a]=_(true),[s,l]=_({show:false,title:"",message:"",onConfirm:()=>{}}),c=async()=>{a(true);try{const e=zy(),t=await e.getBackupList();r(t);}catch(e){Pi(le("loadFailed")+": "+String(e));}finally{a(false);}};i.useEffect(()=>{c();},[]); return De("div",{className:"settings-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.show&&Re(_f,{title:s.title,message:s.message,danger:s.danger,onConfirm:s.onConfirm,onCancel:()=>l(e=>({...e,show:false}))}), De("div",{className:"settings-modal",style:{width:"500px",height:"600px",background:"var(--gh-card-bg, #ffffff)",borderRadius:"12px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ De("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("div",{style:{fontWeight:600,fontSize:"16px"},children:le("webdavBackupList")}), De("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Re(od,{content:le("refresh"),children:Re("button",{onClick:c,className:"settings-btn settings-btn-secondary","aria-label":le("refresh"),style:{padding:"6px",display:"flex",alignItems:"center"},children:Re(Ue,{size:16})})}), Re("button",{onClick:e,className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px"},children:"✕"})]})]}), Re("div",{style:{overflowY:"auto",padding:"16px",flex:1},children:o?Re("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:le("loading")}):0===n.length?Re("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:le("noBackupsFound")}):Re("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:n.map(e=>De("div",{style:{padding:"12px 14px",background:"var(--gh-bg, #ffffff)",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"space-between",transition:"border-color 0.15s"},children:[ De("div",{style:{minWidth:0,flex:1,marginRight:"12px"},children:[ Re("div",{style:{fontSize:"13px",fontWeight:500,color:"var(--gh-text, #1f2937)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}), De("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginTop:"2px"},children:[jy(e.size)," • ",e.lastModified.toLocaleString()]})]}), De("div",{style:{display:"flex",gap:"6px",flexShrink:0},children:[ Re(od,{content:le("restore"),children:Re("button",{onClick:()=>(e=>{l({show:true,title:le("restore"),message:le("backupRestoreConfirmMsg",{name:e.name}),danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const n=zy();if((await n.download(e.name)).success){try{"extension"===$i.type&&"undefined"!=typeof chrome&&(await new Promise((e,t)=>chrome.storage.local.set({[ci]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await chrome.runtime.sendMessage({type:pd}));}catch{}Pi(le("restoreSuccess")),setTimeout(()=>{t();},1500);}else Pi(le("restoreError")),a(!1);}catch(n){Pi(le("restoreError")+": "+String(n)),a(false);}}});})(e),"aria-label":le("restore"),style:{padding:"7px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"7px",border:"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 25%, transparent)",background:"color-mix(in srgb, var(--gh-primary, #4285f4) 8%, transparent)",color:"var(--gh-primary, #4285f4)",cursor:"pointer",transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-primary, #4285f4) 16%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-primary, #4285f4) 40%, transparent)";},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-primary, #4285f4) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-primary, #4285f4) 25%, transparent)";},children:Re(an,{size:16,color:"currentColor"})})}), Re(od,{content:le("delete"),children:Re("button",{onClick:()=>(e=>{l({show:true,title:le("delete"),message:le("backupDeleteCloudConfirmMsg",{name:e.name}),danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const t=zy();(await t.deleteFile(e.name)).success?(Pi(le("deleteSuccess")),c()):(Pi(le("deleteError")),a(!1));}catch(t){Pi(le("deleteError")+": "+String(t)),a(false);}}});})(e),"aria-label":le("delete"),style:{padding:"7px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"7px",border:"1px solid color-mix(in srgb, var(--gh-danger, #ef4444) 20%, transparent)",background:"color-mix(in srgb, var(--gh-danger, #ef4444) 7%, transparent)",color:"var(--gh-danger, #ef4444)",cursor:"pointer",transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-danger, #ef4444) 14%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-danger, #ef4444) 35%, transparent)";},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-danger, #ef4444) 7%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-danger, #ef4444) 20%, transparent)";},children:Re(Ft,{size:16,color:"currentColor"})})})]})]},e.name))})})]})]})},Qy=({onNavigate:e})=>{const{settings:t,setSettings:n,resetSettings:r}=Mi(),[o,i]=_(false),a=$(null),[s,l]=_(""),[c,d]=_({url:"",username:"",password:"",remoteDir:"ophel",provider:"custom"});L(()=>{if(t?.webdav){const e=t.webdav,n=qy(e.provider)?e.provider:e.url?By(e.url):"custom";d(t=>({...t,...e,provider:n}));}},[t?.webdav]);const[u,h]=_({show:false,title:"",message:"",onConfirm:()=>{}}),[g,p]=_({show:false,onConfirm:()=>{}});if(!t)return null;const m=async e=>{await new Promise((t,n)=>chrome.storage.local.set(e,()=>chrome.runtime.lastError?n(chrome.runtime.lastError):t()));},f=async e=>{try{let n={};const r=(new Date).toISOString();let o=`ophel-backup-${r.slice(0,10)}.json`;if("full"===e){const e=await new Promise(e=>chrome.storage.local.get(null,e));n={version:3,timestamp:r,type:"full",data:Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return ro.includes(e)&&n?.state&&(n=oo.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}}))};}else if("prompts"===e){const e=await new Promise(e=>chrome.storage.local.get("prompts",e));let i=[];try{const t="string"==typeof e.prompts?JSON.parse(e.prompts):e.prompts;t?.state?.prompts&&(i=t.state.prompts);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"prompts",data:{prompts:i}},o=`ophel-prompts-${r.slice(0,10)}.json`;}else if("settings"===e){const e=await new Promise(e=>chrome.storage.local.get("settings",e));let i={};try{const t="string"==typeof e.settings?JSON.parse(e.settings):e.settings;t?.state?.settings?i=t.state.settings:t?.state&&(i=t.state);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"settings",data:{settings:i}},o=`ophel-settings-${r.slice(0,10)}.json`;}const i=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),a=URL.createObjectURL(i),s=document.createElement("a");s.href=a,s.download=o,s.click(),URL.revokeObjectURL(a),Pi(le("exportSuccess"));}catch(n){Pi(le("exportError"));}},b=async e=>{try{const n=JSON.parse(e),r=Ly(n);if(!r.valid){r.errorKeys.map(e=>le(e)).join(", ");return console.error("Backup validation failed:",r.errorKeys),void Pi(le("invalidBackupFile"))}h({show:!0,title:le("importData"),message:De("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Re("div",{children:le("importConfirm")}), Re("div",{style:{border:"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 15%, transparent)",background:"var(--gh-hover, #f8fafc)",borderRadius:"8px",padding:"10px 12px"},children:De("div",{style:{display:"grid",gridTemplateColumns:"72px 1fr",rowGap:"6px",columnGap:"10px",alignItems:"start"},children:[ Re("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:le("backupTime")}), Re("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:String(n.timestamp||"-")}), Re("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:le("backupType")}), Re("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:(t=n.type,"full"===t?le("fullBackup"):"prompts"===t?le("promptsBackup"):"settings"===t?le("settingsBackup"):String(t||le("unknown")))})]})}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:le("openAiPagesWillRefresh")})]}),danger:!0,onConfirm:async()=>{h(e=>({...e,show:!1}));try{const e={};Object.entries(n.data).forEach(([t,n])=>{if(null!=n)if(ro.includes(t)){let r=n;if(oo.includes(t))if("object"!=typeof n||Array.isArray(n))r="readingHistory"===t?{history:n}:{[t]:n};else {const e=n;r="conversations"===t&&void 0!==e.conversations?n:"readingHistory"!==t||void 0===e.history&&void 0===e.lastCleanupRun?"readingHistory"===t?{history:n}:{[t]:n}:n;}else r="prompts"===t&&Array.isArray(n)?{prompts:n}:"settings"!==t||n.settings?{[t]:n}:{settings:n};e[t]=JSON.stringify({state:r,version:0});}else e[t]="object"==typeof n?JSON.stringify(n):n;}),await m(e),await(async()=>{try{"extension"===$i.type&&"undefined"!=typeof chrome&&(await m({[ci]:Date.now()}),await chrome.runtime.sendMessage({type:pd}));}catch{}})(),Pi(le("importSuccess")),setTimeout(()=>window.location.reload(),1e3);}catch(e){console.error("[Backup] import storage write failed:",e),Pi(`${le("importError")}${Gy(e)}`);}}});}catch(n){console.error("[Backup] import parse failed:",n),Pi(`${le("importError")}${Gy(n)}`);}var t;},y=async e=>{const t=c.url;if(!t)return Pi(le("webdavConfigIncomplete")),false;if(!$i.hasCapability("permissions"))return await e(),true;try{const n=new URL(t).origin+"/*";return (await chrome.runtime.sendMessage({type:dd,origin:n})).hasPermission?(await e(),!0):(p({show:!0,onConfirm:async()=>{p(e=>({...e,show:!1}));try{const t=await chrome.runtime.sendMessage({type:hd,permType:"allUrls"});if(!t.success)return void Pi(t.error||le("permissionRequired"));const n=await(async e=>{const t=Date.now()+6e4;for(;Date.now()setTimeout(e,1e3));}return !1})("");if(!n)return void Pi(le("permissionRequired"));await e();}catch(RS){console.warn("WebDAV permission request failed:",RS),Pi(le("permissionRequired"));}}}),!1)}catch(n){return console.warn("Perm check logic skipped:",n),await e(),true}},v=(()=>{const e=t.webdav??ti.webdav,n=e.provider??(e.url?By(e.url):"custom");return c.url!==e.url||c.username!==e.username||c.password!==e.password||c.remoteDir!==e.remoteDir||c.provider!==n})(); return De("div",{className:"settings-content",children:[ Re(sy,{title:le("navBackup"),Icon:ft}),u.show&&Re(_f,{title:u.title,message:u.message,danger:u.danger,onConfirm:u.onConfirm,onCancel:()=>h(e=>({...e,show:false}))}),g.show&&Re(_f,{title:le("permissionRequired"),message:le("webdavPermissionDesc"),onConfirm:g.onConfirm,onCancel:()=>p(e=>({...e,show:false}))}),o&&Re(Vy,{onClose:()=>i(false),onRestore:()=>window.location.reload()}), De("div",{className:"backup-grid",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(400px, 1fr))",gap:"20px",marginBottom:"24px"},children:[ Re(ry,{title:le("exportData"),description:le("exportDataDesc"),children:De("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ De("div",{children:[ Re("div",{style:{fontWeight:500,fontSize:"14px"},children:le("fullBackup")}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("fullBackupDesc")})]}), Re("button",{onClick:()=>f("full"),className:"settings-btn settings-btn-success",style:{padding:"6px 16px"},children:le("export")})]}), De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ De("div",{children:[ Re("div",{style:{fontWeight:500,fontSize:"14px"},children:le("promptsBackup")}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("promptsBackupDesc")})]}), Re("button",{onClick:()=>f("prompts"),className:"settings-btn settings-btn-primary",style:{padding:"6px 16px"},children:le("export")})]}), De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ De("div",{children:[ Re("div",{style:{fontWeight:500,fontSize:"14px"},children:le("settingsBackup")}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("settingsBackupDesc")})]}), Re("button",{onClick:()=>f("settings"),className:"settings-btn settings-btn-secondary",style:{padding:"6px 16px"},children:le("export")})]})]})}), Re(ry,{title:le("importData"),description:le("importDataDesc"),children:De("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("div",{style:{fontSize:"14px",fontWeight:500},children:le("selectFile")}), De("button",{className:"settings-btn settings-btn-secondary",onClick:()=>a.current?.click(),style:{padding:"6px 12px"},children:[le("browse"), Re("input",{ref:a,type:"file",accept:".json",style:{display:"none"},onChange:async e=>{const t=e.target.files?.[0];if(!t)return;const n=await t.text();l(n),a.current&&(a.current.value="");}})]})]}), De("div",{style:{flex:1},children:[ Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginBottom:"4px"},children:le("dataPreview")}), Re("textarea",{className:"settings-input",value:s,onChange:e=>l(e.target.value),placeholder:le("pastePlaceholder"),style:{width:"100%",height:"120px",fontFamily:"monospace",fontSize:"12px",resize:"vertical"}})]}), Re("button",{onClick:()=>{s.trim()?b(s):Pi(le("selectFileOrPasteFirst"));},className:"settings-btn settings-btn-primary",style:{width:"100%",justifyContent:"center",padding:"8px"},disabled:!s.trim(),children:le("importBtn")})]})})]}), De(ry,{title:le("webdavConfig"),description:le("webdavConfigDesc"),children:[ De("div",{style:{background:"var(--gh-bg-secondary, #f8f9fa)",border:"1px solid var(--gh-border, #e0e0e0)",borderRadius:"8px",padding:"12px",marginBottom:"20px",fontSize:"13px",color:"var(--gh-text-secondary)"},children:[ De("div",{style:{fontWeight:600,marginBottom:"4px",display:"flex",alignItems:"center",gap:"6px",color:"var(--gh-text)"},children:[ Re(yt,{size:14,color:"var(--gh-primary, #4285f4)"})," ",le("restoreTip")]}), Re("div",{style:{lineHeight:1.5},children:le("restoreTipContent")})]}), Re(oy,{label:le("webdavProvider"),children:Re("select",{className:"settings-input settings-select",value:c.provider||"custom",onChange:e=>{const t=e.target.value,n=Py.find(e=>e.id===t);d(e=>({...e,provider:t,...n?.urlTemplate?{url:n.urlTemplate}:{}}));},style:{width:"280px"},children:Py.map(e=>Re("option",{value:e.id,children:le(e.labelKey)},e.id))})}),(()=>{const e=Py.find(e=>e.id===(c.provider||"custom"));return e?.hintKey?De("div",{style:{background:"var(--gh-primary-light-bg, rgba(66, 133, 244, 0.05))",border:"1px solid var(--gh-primary-border, rgba(66, 133, 244, 0.2))",borderRadius:"8px",padding:"10px 12px",marginBottom:"4px",fontSize:"12px",color:"var(--gh-text-secondary)",display:"flex",alignItems:"flex-start",gap:"8px"},children:[ Re(yt,{size:14,color:"var(--gh-primary, #4285f4)",style:{flexShrink:0,marginTop:"1px"}}), De("div",{children:[le(e.hintKey),e.helpUrl&&Re("a",{href:e.helpUrl,target:"_blank",rel:"noreferrer noopener",style:{marginLeft:"6px",color:"var(--gh-primary, #4285f4)",textDecoration:"underline"},children:le("learnMore")})]})]}):null})(), Re(oy,{label:le("webdavAddress"),children:(()=>{const e=Py.find(e=>e.id===(c.provider||"custom")); return Re("input",{type:"text",className:"settings-input",placeholder:e?.urlPlaceholder||"https://dav.example.com/dav/",value:c.url,onChange:e=>d({...c,url:e.target.value}),style:{width:"280px"}})})()}), Re(oy,{label:le("username"),children:Re("input",{type:"text",className:"settings-input",value:c.username,onChange:e=>d({...c,username:e.target.value}),style:{width:"280px"}})}), Re(oy,{label:le("password"),children:(()=>{const e=Py.find(e=>e.id===(c.provider||"custom")),t=le(e?.passwordPlaceholderKey?e.passwordPlaceholderKey:"webdavPasswordPlaceholder"); return Re("input",{type:"password",className:"settings-input",placeholder:t,value:c.password,onChange:e=>d({...c,password:e.target.value}),style:{width:"280px"}})})()}), Re(oy,{label:le("defaultDir"),description:le("defaultDirHint"),children:Re("input",{type:"text",className:"settings-input",placeholder:"ophel",value:c.remoteDir,onChange:e=>d({...c,remoteDir:e.target.value}),style:{width:"280px"}})}), De("div",{style:{marginTop:"16px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"8px"},children:[ De("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ De("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{await y(async()=>{const e=zy();await e.setConfig(c,!1);(await e.testConnection()).success?Pi(le("webdavConnectionSuccess")):Pi(le("webdavConnectionFailed"));});},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ Re(on,{size:16})," ",le("webdavTestBtn")]}), De("div",{style:{position:"relative"},children:[ De("button",{className:"settings-btn "+(v?"settings-btn-primary":"settings-btn-secondary"),onClick:()=>{const e=t.webdav??ti.webdav;n({webdav:{...e,...c}}),Pi(le("saveSuccess"));},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ Re(rn,{size:16})," ",le("saveConfig")]}),v&&Re("span",{style:{position:"absolute",top:"-4px",right:"-4px",width:"8px",height:"8px",backgroundColor:"var(--gh-warning, #f59e0b)",borderRadius:"50%",boxShadow:"0 0 0 2px var(--gh-bg, #ffffff)"}})]})]}), De("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ De("button",{className:"settings-btn settings-btn-secondary",style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await y(async()=>{const e=zy();await e.setConfig(c,!1),i(!0);});},children:[ Re(an,{size:16,color:"currentColor"})," ",le("restore")]}), De("button",{className:"settings-btn "+(v?"settings-btn-secondary":"settings-btn-primary"),style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await y(async()=>{const e=zy();await e.setConfig(c,!1);(await e.upload()).success?Pi(le("webdavUploadSuccess")):Pi(le("webdavUploadFailed"));});},children:[ Re(bt,{size:16,color:"currentColor"})," ",le("backupNow")]})]})]})]}), Re(ry,{title:le("dangerZone"),description:le("dangerZoneDesc"),className:"danger-zone-card",children:De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ De("div",{children:[ Re("div",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-danger, #ef4444)"},children:le("clearAllData")}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("clearAllDataDesc")})]}), Re("button",{className:"settings-btn settings-btn-danger",onClick:()=>{h({show:true,title:le("clearAllData"),message:le("clearAllDataConfirm"),danger:true,onConfirm:async()=>{h(e=>({...e,show:false}));try{if("extension"===$i.type&&"undefined"!=typeof chrome)try{await chrome.runtime.sendMessage({type:gd});}catch{}await Promise.all([new Promise((e,t)=>chrome.storage.local.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),new Promise((e,t)=>chrome.storage.sync.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e()))]),await new Promise((e,t)=>chrome.storage.local.set({[Go]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),r(),Rm.getState().setPrompts(io()),mm.setState({folders:ao}),vm.setState({tags:[]}),cm.setState({conversations:{},lastUsedFolderId:"inbox"}),Uy.setState({history:{},lastCleanupRun:0}),Pi(le("clearSuccess")),setTimeout(()=>window.location.reload(),1500);}catch(e){Pi(le("error")+": "+String(e));}}});},style:{padding:"8px 16px",fontSize:"13px"},children:le("clearAllData")})]})})]})},Ky="ophel:usageMonitor",Zy={version:2,records:{},events:[]},Yy=(e,t=0)=>Number.isFinite(e)?Math.max(0,Math.floor(e)):t,Xy=e=>{const t=Date.now();return e?{count:Yy(e.count),updatedAt:Yy(e.updatedAt,t),resetAt:Yy(e.resetAt,t)}:{count:0,updatedAt:t,resetAt:t}},Jy=e=>{if(!e||"object"!=typeof e)return null;const t=Yy(e.ts,Date.now());return {id:"string"==typeof e.id&&e.id?e.id:`${t}-${Math.random().toString(36).slice(2,8)}`,ts:t,siteId:"string"==typeof e.siteId&&e.siteId?e.siteId:"_default",cid:"string"==typeof e.cid&&e.cid?e.cid:"default",sessionId:"string"==typeof e.sessionId?e.sessionId:"",countDelta:Yy(e.countDelta,1)||1,requestTokens:Yy(e.requestTokens),roundTripTokens:Yy(e.roundTripTokens),loadedConversationTokens:Yy(e.loadedConversationTokens),loadedOutputTokens:Yy(e.loadedOutputTokens)}},ev=e=>{const t=Date.now();return e.filter(e=>t-e.ts<=3456e7).sort((e,t)=>e.ts-t.ts).slice(-4e3)},tv=e=>{if(!e||"object"!=typeof e)return {...Zy};const t=Array.isArray(e.events)?e.events:[];return {version:2,records:e.records&&"object"==typeof e.records?e.records:{},events:ev(t.map(e=>Jy(e)).filter(Boolean))}};async function nv(){const e=await $i.storage.get(Ky);return tv(e)}async function rv(e){await $i.storage.set(Ky,tv(e));}const ov=e=>{const t=new Date(e);return t.setMinutes(0,0,0),t},iv=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t},av=e=>{const t=new Date(e);return t.setDate(1),t.setHours(0,0,0,0),t},sv=e=>`${`${e.getHours()}`.padStart(2,"0")}:00`,lv=e=>`${e.getMonth()+1}/${e.getDate()}`,cv=e=>`${e.getFullYear()}/${`${e.getMonth()+1}`.padStart(2,"0")}`,dv=(e,t)=>{switch(t){case "requestTokens":return e.requestTokens;case "roundTripTokens":return e.roundTripTokens;case "loadedConversationTokens":return e.loadedConversationTokens;case "loadedOutputTokens":return e.loadedOutputTokens;default:return e.count}};function uv(e){return $i.storage.watch(Ky,(t,n)=>{e(tv(t),tv(n));})}const hv=({value:e,onChange:t,placeholder:n,className:r,style:o})=>{const[a,s]=_(e);i.useEffect(()=>{s(e);},[e]);const l=()=>{a!==e&&t(a);}; return Re("input",{type:"text",className:r,value:a,onChange:e=>s(e.target.value),onBlur:l,onKeyDown:e=>{"Enter"===e.key&&(l(),e.target.blur());},placeholder:n,style:o})},gv=({siteId:e})=>{const[t,n]=_("day"),[r,o]=_("requestTokens"),[a,s]=_("_default"===e?"all":e),[l,c]=_([]),[d,u]=_(true),[h,g]=_(null),p=i.useRef(null),m=i.useMemo(()=>[{id:"all",label:le("usageMonitorChartSiteAll")},{id:ho,label:"Gemini"},{id:mo,label:"Gemini Enterprise"},{id:go,label:"ChatGPT"},{id:uo,label:"Claude"},{id:fo,label:"Grok"},{id:bo,label:"AI Studio"},{id:xo,label:"DeepSeek"},{id:yo,label:"Doubao"},{id:vo,label:"ima"},{id:po,label:"ChatGLM"},{id:wo,label:"Kimi"},{id:So,label:"Qianwen"},{id:Co,label:"Qwen Studio"},{id:To,label:"Z.ai"}],[]),f=m.find(e=>e.id===a)?.label||le("usageMonitorChartSiteAll"),b=i.useCallback(async()=>{u(true);try{const e=await async function(e){return (await nv()).events.filter(t=>!(e?.siteId&&"_default"!==e.siteId&&t.siteId!==e.siteId||e?.cid&&t.cid!==e.cid))}({siteId:"all"===a?void 0:a});c(function(e,t,n=new Date){const r="hour"===t?24:"day"===t?30:12,o=[],i=new Map;for(let a=r-1;a>=0;a--){const e=new Date(n);let r,s,l;"hour"===t?(e.setHours(e.getHours()-a),r=ov(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}-${r.getHours()}`,l=sv(r)):"day"===t?(e.setDate(e.getDate()-a),r=iv(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`,l=lv(r)):(e.setMonth(e.getMonth()-a),r=av(e),s=`${r.getFullYear()}-${r.getMonth()}`,l=cv(r));const c={key:s,label:l,startAt:r.getTime(),endAt:"hour"===t?r.getTime()+36e5:"day"===t?r.getTime()+864e5:new Date(r.getFullYear(),r.getMonth()+1,1).getTime(),count:0,requestTokens:0,roundTripTokens:0,loadedConversationTokens:0,loadedOutputTokens:0,maxLoadedConversationTokens:0,maxRequestTokens:0,maxRoundTripTokens:0,maxLoadedOutputTokens:0};o.push(c),i.set(s,c);}return e.forEach(e=>{const n=new Date(e.ts),r="hour"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}-${n.getHours()}`:"day"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`:`${n.getFullYear()}-${n.getMonth()}`,o=i.get(r);o&&(o.count+=e.countDelta,o.requestTokens+=e.requestTokens,o.roundTripTokens+=e.roundTripTokens,o.loadedConversationTokens+=e.loadedConversationTokens,o.loadedOutputTokens+=e.loadedOutputTokens,o.maxLoadedConversationTokens=Math.max(o.maxLoadedConversationTokens,e.loadedConversationTokens),o.maxRequestTokens=Math.max(o.maxRequestTokens,e.requestTokens),o.maxRoundTripTokens=Math.max(o.maxRoundTripTokens,e.roundTripTokens),o.maxLoadedOutputTokens=Math.max(o.maxLoadedOutputTokens,e.loadedOutputTokens));}),o}(e,t));}finally{u(false);}},[t,a]);L(()=>{b();},[b]),L(()=>{const e=uv(()=>{b();});return ()=>e()},[b]),L(()=>{if(!p.current)return;const e=p.current,t=()=>{e.scrollLeft=e.scrollWidth;};t();const n=window.requestAnimationFrame(t);return ()=>window.cancelAnimationFrame(n)},[t,l.length]);const y=l.map(e=>dv(e,r)),v=Math.max(1,...y),x=y[y.length-1]??0,w=le("requestTokens"===r?"usageMonitorChartMetricRequest":"roundTripTokens"===r?"usageMonitorChartMetricRoundTrip":"loadedConversationTokens"===r?"usageMonitorChartMetricConversation":"loadedOutputTokens"===r?"usageMonitorChartMetricOutput":"usageMonitorChartMetricCount"),S="month"===t?72:"hour"===t?48:44,C=l.length>1?Math.max(640,40+(l.length-1)*S+48):640,k=16,T=12,E=18,A=C-E-T,M=220-k-32,I=l.length>1?A/(l.length-1):A,N="month"===t?1:"hour"===t?2:Math.max(2,Math.ceil(l.length/10)),R=l.map((e,t)=>{const n=E+I*t,o=dv(e,r);return {x:n,y:k+M-o/v*M,value:o,label:e.label}}),D=R.length>0?R.map((e,t)=>`${0===t?"M":"L"} ${e.x.toFixed(2)} ${e.y.toFixed(2)}`).join(" "):"",P=R.length>0?`${D} L ${R[R.length-1].x.toFixed(2)} ${(k+M).toFixed(2)} L ${R[0].x.toFixed(2)} ${(k+M).toFixed(2)} Z`:"",q=null!==h&&h>=0&&h=0&&h0&&h-1U?Math.min(H-U-8,Math.max(8,B.x-W-110)):8,G=B&&B.y>110?Math.max(8,B.y-94):8,V="var(--gh-border, #e5e7eb)",Q="var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",K="var(--gh-primary, #4285f4)",Z="var(--gh-border-active, #6366f1)",Y="var(--gh-text-secondary, #6b7280)",X="var(--gh-text, #374151)",J="var(--gh-card-bg, #ffffff)",ee="var(--gh-border, #e5e7eb)",te="var(--gh-border-active, #6366f1)",ne="var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))"; return De("div",{style:{marginTop:"14px",padding:"14px",borderRadius:"12px",border:`1px solid ${ee}`,background:"var(--gh-bg-secondary, #f9fafb)"},children:[ De("div",{style:{display:"flex",justifyContent:"space-between",gap:"12px",flexWrap:"wrap"},children:[ De("div",{children:[ Re("div",{style:{fontSize:"14px",fontWeight:600,color:"var(--gh-text, #374151)"},children:le("usageMonitorChartTitle")}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:le("usageMonitorChartDesc")}), De("div",{style:{marginTop:"8px",display:"inline-flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[ Re("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:le("usageMonitorChartSiteLabel")}), Re("select",{className:"settings-select",value:a,onChange:e=>s(e.target.value),style:{minWidth:"170px"},children:m.map(e=>Re("option",{value:e.id,children:e.label},e.id))})]})]}), De("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap",alignItems:"flex-start"},children:[ Re("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["hour",le("usageMonitorChartHour")],["day",le("usageMonitorChartDay")],["month",le("usageMonitorChartMonth")]].map(([e,r])=>Re(zf,{size:"sm",variant:t===e?"primary":"secondary",onClick:()=>n(e),children:r},e))}), Re("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["count",le("usageMonitorChartMetricCount")],["requestTokens",le("usageMonitorChartMetricRequest")],["roundTripTokens",le("usageMonitorChartMetricRoundTrip")],["loadedConversationTokens",le("usageMonitorChartMetricConversation")],["loadedOutputTokens",le("usageMonitorChartMetricOutput")]].map(([e,t])=>Re(zf,{size:"sm",variant:r===e?"primary":"secondary",onClick:()=>o(e),children:t},e))})]})]}), De("div",{style:{display:"flex",gap:"18px",marginTop:"12px",marginBottom:"8px",flexWrap:"wrap"},children:[ De("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ De("span",{children:[w,": "]}), Re("strong",{style:{color:"var(--gh-text, #374151)"},children:x})]}), De("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ De("span",{children:[le("usageMonitorChartCurrentSite"),": "]}), Re("strong",{style:{color:"var(--gh-text, #374151)"},children:f})]}), De("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Re("span",{children:"MAX: "}), Re("strong",{style:{color:"var(--gh-text, #374151)"},children:v})]}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:Re("span",{children:le("usageMonitorChartScrollHint")})})]}), De("div",{style:{position:"relative",marginTop:"4px"},onMouseLeave:()=>g(null),children:[ De("div",{ref:p,style:{position:"relative",borderRadius:"10px",overflowX:"auto",overflowY:"hidden",background:J,border:`1px solid ${ee}`,minHeight:"220px"},children:[ Re("div",{style:{width:`${C}px`,minWidth:"100%",position:"relative"},children:De("svg",{viewBox:`0 0 ${C} 220`,style:{width:"100%",height:"220px",display:"block"},children:[[0,.25,.5,.75,1].map(e=>{const t=k+M-M*e; return Re("line",{x1:E,x2:C-T,y1:t,y2:t,stroke:V,strokeWidth:"1",opacity:.6},e)}),P&&Re("path",{d:P,fill:Q}),D&&Re("path",{d:D,fill:"none",stroke:K,strokeWidth:"2.5",strokeLinejoin:"round",strokeLinecap:"round"}),R.map(e=>Re("circle",{cx:e.x,cy:e.y,r:"3",fill:K},`${e.label}-${e.x}`)),B&&Re("line",{x1:B.x,x2:B.x,y1:k,y2:k+M,stroke:Z,strokeDasharray:"4 4",strokeWidth:"1",opacity:.65}),l.map((e,t)=>{const n=R[t],r=R[t-1],o=R[t+1],i=r?(r.x+n.x)/2:E,a=o?(n.x+o.x)/2:C-T; return Re("rect",{x:i,y:k,width:Math.max(12,a-i),height:M,fill:"transparent",pointerEvents:"all",onMouseEnter:()=>g(t),onMouseMove:()=>g(t)},`${e.key}-hover`)}),l.map((e,t)=>{if(!(0===t||t===l.length-1||t%N===0))return null; return Re("text",{x:E+I*t,y:210,textAnchor:"middle",fill:Y,fontSize:"11",children:e.label},e.key)})]})}),!d&&l.every(e=>0===dv(e,r))&&Re("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Y,fontSize:"13px"},children:le("usageMonitorChartEmpty")})]}),q&&B&&De("div",{style:{position:"absolute",left:`${j}px`,top:`${G}px`,width:"220px",borderRadius:"10px",padding:"10px 12px",background:J,color:X,border:`1px solid ${te}`,boxShadow:ne,pointerEvents:"none",zIndex:5},children:[ Re("div",{style:{fontSize:"12px",fontWeight:700,marginBottom:"8px"},children:(e=>{const n=new Date(e.startAt),r=new Date(e.endAt-1);if("hour"===t){return `${`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`} ${`${n.getHours()}`.padStart(2,"0")}:00 - ${`${r.getHours()}`.padStart(2,"0")}:59`}return "day"===t?`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`:`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}`})(q)}),null!==F&&De("div",{style:{fontSize:"11px",marginBottom:"8px",color:"var(--gh-text-secondary, #6b7280)"},children:[w,": ",O," · ",F>=0?"+":"",F," ",le("usageMonitorChartDelta")]}), De("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"6px 10px",fontSize:"12px"},children:[ Re("span",{style:{color:Y},children:le("usageMonitorChartMetricCount")}), Re("strong",{children:q.count}), Re("span",{style:{color:Y},children:le("usageMonitorChartMetricRequest")}), Re("strong",{children:q.requestTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMetricRoundTrip")}), Re("strong",{children:q.roundTripTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMetricConversation")}), Re("strong",{children:q.loadedConversationTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMetricOutput")}), Re("strong",{children:q.loadedOutputTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMaxConversation")}), Re("strong",{children:q.maxLoadedConversationTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMaxRequest")}), Re("strong",{children:q.maxRequestTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMaxRoundTrip")}), Re("strong",{children:q.maxRoundTripTokens}), Re("span",{style:{color:Y},children:le("usageMonitorChartMaxOutput")}), Re("strong",{children:q.maxLoadedOutputTokens})]})]})]})]})},pv=({siteId:e,initialTab:t})=>{const n=[{id:Tr,label:le("tabOutline")},{id:Er,label:le("tabConversations")},{id:Ar,label:le("tabPrompts")},{id:Mr,label:le("tabSettingsTab")},{id:Ir,label:le("reminderTab")},{id:Lr,label:le("navContent")},{id:Nr,label:le("readingHistoryTitle")}],[r,o]=_(t||n[0].id),[a,s]=_(false),l=i.useRef(null),{settings:c,updateDeepSetting:d,updateNestedSetting:u}=Mi(),h=E(()=>{l.current&&(l.current.onended=null,l.current.onerror=null);},[]),g=E(()=>{const e=l.current;e?(h(),e.pause(),e.currentTime=0,s(false)):s(false);},[h]);if(L(()=>{t&&o(t);},[t]),L(()=>()=>{g();},[g]),L(()=>{r!==Ir&&g();},[r,g]),L(()=>{c?.tab?.showNotification&&c.tab.notificationSound||g();},[c?.tab?.notificationSound,c?.tab?.showNotification,g]),L(()=>{const e=l.current;if(!e||!a)return;const t=c?.tab?.notificationVolume??.5;e.volume=Math.max(.1,Math.min(1,t));},[a,c?.tab?.notificationVolume]),!c)return null;const p=le("enablePrerequisiteToast"),m=e=>qi(p.replace("{setting}",e),2e3,{},1500,e),f=le("autoRenameTabLabel"),b=le("showNotificationLabel"),y=le("showStatusLabel"),v=le("privacyModeLabel"),x=le("readingHistoryPersistenceLabel"),w=le("formulaCopyLabel"),S="zip"===c.export?.packaging||"markdown"===c.export?.packaging?c.export.packaging:"markdown",C=[{value:"markdown",label:le("exportPackagingMarkdown")},{value:"zip",label:le("exportPackagingZip")}],k="mathml"===c.content?.formulaCopyFormat?"mathml":"latex",T=[{value:"latex",label:le("formulaCopyFormatLatex")},{value:"mathml",label:le("formulaCopyFormatMathml")}],A=no.length>1,M=e=>le("secondsValueLabel",{val:String(e)}),I=e=>`${e}x`,N=le("notificationSoundPreviewButtonLabel"),R=e=>{const t=e||c.tab?.notificationSoundPreset||no[0].id,n=$i.getNotificationSoundUrl(t);if(!n)return void Pi(le("notificationSoundPreviewFailed"),2e3);g();let r=l.current;r||(r=new Audio,l.current=r);const o=c.tab?.notificationVolume??.5;r.volume=Math.max(.1,Math.min(1,o)),r.src=n,r.currentTime=0,r.onended=()=>{h(),s(false);},r.onerror=()=>{h(),s(false),Pi(le("notificationSoundPreviewFailed"),2e3);},s(true),r.play().catch(()=>{h(),s(false),Pi(le("notificationSoundPreviewFailed"),2e3);});},D=De(ry,{title:le("notificationSettings"),children:[ Re(iy,{label:le("showNotificationLabel"),description:le("showNotificationDesc"),settingId:"tab-show-notification",checked:c.tab?.showNotification??false,onChange:async()=>{const e=c.tab?.showNotification;if(e)u("tab","showNotification",false);else {if(!$i.hasCapability("permissions"))return void u("tab","showNotification",true);if(void 0!==chrome.permissions){await chrome.permissions.request({permissions:["notifications"]})&&u("tab","showNotification",true);}else {const e=await md({type:ud,permissions:["notifications"]});e.success&&e.hasPermission?u("tab","showNotification",true):(await md({type:hd,permType:"notifications"}),Pi(le("permissionRequestToast"),3e3));}}}}), Re(iy,{label:le("notificationSoundLabel"),description:le("notificationSoundDesc"),settingId:"tab-notification-sound",checked:c.tab?.notificationSound??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notificationSound",!c.tab?.notificationSound)}),A&&Re(oy,{label:le("notificationSoundPresetLabel"),settingId:"tab-notification-sound-preset",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("select",{className:"settings-select",value:c.tab?.notificationSoundPreset||no[0].id,onChange:e=>{const t=e.target.value;u("tab","notificationSoundPreset",t),R(t);},disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{flex:1},children:no.map(e=>Re("option",{value:e.id,children:le(e.labelKey)},e.id))}), Re(zf,{type:"button",variant:a?"primary":"secondary",size:"sm",onClick:()=>R(),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{minWidth:"56px",flexShrink:0},children:N})]})}), Re(oy,{label:le("notificationVolumeLabel"),settingId:"tab-notification-volume",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("input",{type:"range",min:"0.1",max:"1.0",step:"0.1",value:c.tab?.notificationVolume||.5,onChange:e=>u("tab","notificationVolume",parseFloat(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{width:"100px"}}), De("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(c.tab?.notificationVolume||.5)),"%"]})]})}), Re(oy,{label:le("notificationRepeatCountLabel"),settingId:"tab-notification-repeat-count",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Re("select",{className:"settings-select",value:c.tab?.notificationRepeatCount??1,onChange:e=>u("tab","notificationRepeatCount",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5].map(e=>Re("option",{value:e,children:I(e)},e))})}), Re(oy,{label:le("notificationRepeatIntervalLabel"),settingId:"tab-notification-repeat-interval",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Re("select",{className:"settings-select",value:c.tab?.notificationRepeatInterval??3,onChange:e=>u("tab","notificationRepeatInterval",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5,10].map(e=>Re("option",{value:e,children:M(e)},e))})}), Re(iy,{label:le("notifyWhenFocusedLabel"),description:le("notifyWhenFocusedDesc"),settingId:"tab-notify-when-focused",checked:c.tab?.notifyWhenFocused??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notifyWhenFocused",!c.tab?.notifyWhenFocused)}), Re(iy,{label:le("autoFocusLabel"),description:le("autoFocusDesc"),settingId:"tab-auto-focus",checked:c.tab?.autoFocus??false,onChange:()=>u("tab","autoFocus",!c.tab?.autoFocus)})]}),P=De(ry,{title:le("usageMonitorSettingsTitle"),description:le("usageMonitorSettingsDesc"),children:[ De("div",{style:{marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text-secondary, #6b7280)",fontSize:"12px",lineHeight:1.6},children:[ Re("div",{children:le("usageMonitorExplainLocalOnly")}), Re("div",{children:le("usageMonitorExplainNoBackend")}), Re("div",{children:le("usageMonitorExplainReset")})]}), Re(iy,{label:le("usageMonitorEnabledLabel"),description:le("usageMonitorEnabledDesc"),settingId:"usage-monitor-enabled",checked:c.usageMonitor?.enabled??false,onChange:()=>u("usageMonitor","enabled",!c.usageMonitor?.enabled)}), Re("div",{style:{marginTop:"-2px",marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border-active, #6366f1)",background:"var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",color:"var(--gh-text, #374151)",fontSize:"12px",lineHeight:1.55},children:le("usageMonitorExplainRender")}), Re(oy,{label:le("usageMonitorDailyLimitLabel"),description:le("usageMonitorDailyLimitDesc"),settingId:"usage-monitor-daily-limit",disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(le("usageMonitorEnabledLabel")),children:Re(Ff,{value:c.usageMonitor?.dailyLimit??100,onChange:e=>u("usageMonitor","dailyLimit",e),min:1,max:9999,defaultValue:100,disabled:!c.usageMonitor?.enabled,style:{width:"96px"}})}), Re(iy,{label:le("usageMonitorAutoResetLabel"),description:le("usageMonitorAutoResetDesc"),settingId:"usage-monitor-auto-reset",checked:c.usageMonitor?.autoResetEnabled??false,disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(le("usageMonitorEnabledLabel")),onChange:()=>u("usageMonitor","autoResetEnabled",!c.usageMonitor?.autoResetEnabled)}), Re(gv,{siteId:e})]}); return De("div",{children:[ Re(sy,{title:le("navFeatures"),Icon:lt}), Re("p",{className:"settings-page-desc",children:le("featuresPageDesc")}), Re(ay,{tabs:n,activeTab:r,onTabChange:o}),r===Mr&&De(Ne,{children:[ De(ry,{title:le("tabBehaviorTitle"),children:[ Re(iy,{label:le("openNewTabLabel"),description:le("openNewTabDesc"),settingId:"tab-open-new",checked:c.tab?.openInNewTab??true,onChange:()=>u("tab","openInNewTab",!c.tab?.openInNewTab)}), Re(iy,{label:le("autoRenameTabLabel"),description:le("autoRenameTabDesc"),settingId:"tab-auto-rename",checked:c.tab?.autoRename??false,onChange:()=>u("tab","autoRename",!c.tab?.autoRename)}), Re(oy,{label:le("renameIntervalLabel"),settingId:"tab-rename-interval",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:Re("select",{className:"settings-select",value:c.tab?.renameInterval||3,onChange:e=>u("tab","renameInterval",parseInt(e.target.value)),disabled:!c.tab?.autoRename,children:[1,3,5,10,30,60].map(e=>Re("option",{value:e,children:M(e)},e))})}), Re(oy,{label:le("titleFormatLabel"),description:le("titleFormatDesc"),settingId:"tab-title-format",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:Re(Gf,{value:c.tab?.titleFormat??"{status}{title}",onChange:e=>u("tab","titleFormat",e),placeholders:["{status}","{title}","{model}"],placeholder:"{status}{title}",disabled:!c.tab?.autoRename,style:{width:"260px"}})}), Re(iy,{label:le("showStatusLabel"),description:le("showStatusDesc"),settingId:"tab-show-status",checked:c.tab?.showStatus??true,onChange:()=>u("tab","showStatus",!c.tab?.showStatus)}), Re(iy,{label:le("hideStatusWhenReadLabel"),description:le("hideStatusWhenReadDesc"),settingId:"tab-hide-status-when-read",disabled:!c.tab?.showStatus,onDisabledClick:()=>m(y),checked:c.tab?.hideStatusWhenRead??false,onChange:()=>u("tab","hideStatusWhenRead",!c.tab?.hideStatusWhenRead)})]}), De(ry,{title:le("privacyModeTitle"),children:[ Re(iy,{label:le("privacyModeLabel"),description:le("privacyModeDesc"),settingId:"tab-privacy-mode",checked:c.tab?.privacyMode??false,onChange:()=>u("tab","privacyMode",!c.tab?.privacyMode)}), Re(oy,{label:le("privacyTitleLabel"),settingId:"tab-privacy-title",disabled:!c.tab?.privacyMode,onDisabledClick:()=>m(v),children:Re("input",{type:"text",className:"settings-input",value:c.tab?.privacyTitle||"Google",onChange:e=>u("tab","privacyTitle",e.target.value),placeholder:"Google",disabled:!c.tab?.privacyMode,style:{width:"180px"}})})]})]}),r===Ir&&De(Ne,{children:[D,P]}),r===Tr&&De(Ne,{children:[ De(ry,{title:le("outlineSettings"),description:le("outlineSettingsDesc"),children:[ Re(iy,{label:le("outlineAutoUpdateLabel"),description:le("outlineAutoUpdateDesc"),settingId:"outline-auto-update",checked:c.features?.outline?.autoUpdate??true,onChange:()=>d("features","outline","autoUpdate",!c.features?.outline?.autoUpdate)}), Re(oy,{label:le("outlineUpdateIntervalLabel"),description:le("outlineUpdateIntervalDesc"),settingId:"outline-update-interval",children:Re(Ff,{value:c.features?.outline?.updateInterval??2,onChange:e=>d("features","outline","updateInterval",e),min:1,max:60,defaultValue:2,style:{width:"80px"}})}), Re(oy,{label:le("outlineFollowModeLabel"),description:"current"===c.features?.outline?.followMode?le("outlineFollowCurrentDesc"):"latest"===c.features?.outline?.followMode?le("outlineFollowLatestDesc"):le("outlineFollowManualDesc"),settingId:"outline-follow-mode",children:De("select",{className:"settings-select",value:c.features?.outline?.followMode||"current",onChange:e=>d("features","outline","followMode",e.target.value),children:[ Re("option",{value:"current",children:le("outlineFollowCurrent")}), Re("option",{value:"latest",children:le("outlineFollowLatest")}), Re("option",{value:"manual",children:le("outlineFollowManual")})]})}), Re(iy,{label:le("outlineShowWordCountLabel"),description:le("outlineShowWordCountDesc"),settingId:"outline-show-word-count",checked:c.features?.outline?.showWordCount??false,onChange:()=>d("features","outline","showWordCount",!c.features?.outline?.showWordCount)})]}), De(ry,{title:le("bookmarkSettings"),description:le("bookmarkSettingsDesc"),children:[ Re(oy,{label:le("inlineBookmarkModeLabel"),description:le("inlineBookmarkModeDesc"),settingId:"outline-inline-bookmark-mode",children:De("select",{className:"settings-select",value:c.features?.outline?.inlineBookmarkMode||"always",onChange:e=>d("features","outline","inlineBookmarkMode",e.target.value),children:[ Re("option",{value:"always",children:le("inlineBookmarkModeAlways")}), Re("option",{value:"hover",children:le("inlineBookmarkModeHover")}), Re("option",{value:"hidden",children:le("inlineBookmarkModeHidden")})]})}), Re(oy,{label:le("panelBookmarkModeLabel"),description:le("panelBookmarkModeDesc"),settingId:"outline-panel-bookmark-mode",children:De("select",{className:"settings-select",value:c.features?.outline?.panelBookmarkMode||"always",onChange:e=>d("features","outline","panelBookmarkMode",e.target.value),children:[ Re("option",{value:"always",children:le("inlineBookmarkModeAlways")}), Re("option",{value:"hover",children:le("inlineBookmarkModeHover")}), Re("option",{value:"hidden",children:le("inlineBookmarkModeHidden")})]})})]}), Re(ry,{title:le("scrollSettings"),children:Re(iy,{label:le("preventAutoScrollLabel"),description:le("preventAutoScrollDesc"),settingId:"outline-prevent-auto-scroll",checked:c.panel?.preventAutoScroll??false,onChange:()=>u("panel","preventAutoScroll",!c.panel?.preventAutoScroll)})})]}),r===Er&&De(Ne,{children:[ De(ry,{title:le("conversationsSettingsTitle"),description:le("conversationsSettingsDesc"),children:[ Re(iy,{label:le("folderRainbowLabel"),description:le("folderRainbowDesc"),settingId:"conversation-folder-rainbow",checked:c.features?.conversations?.folderRainbow??true,onChange:()=>d("features","conversations","folderRainbow",!c.features?.conversations?.folderRainbow)}), Re(iy,{label:le("conversationsSyncUnpinLabel"),description:le("conversationsSyncUnpinDesc"),settingId:"conversation-sync-unpin",checked:c.features?.conversations?.syncUnpin??false,onChange:()=>d("features","conversations","syncUnpin",!c.features?.conversations?.syncUnpin)}), Re(iy,{label:le("conversationsSyncDeleteLabel"),description:le("conversationsSyncDeleteDesc"),settingId:"conversation-sync-delete",checked:c.features?.conversations?.syncDelete??true,onChange:()=>d("features","conversations","syncDelete",!(c.features?.conversations?.syncDelete??1))})]}), De(ry,{title:le("exportSettings"),children:[ Re(oy,{label:le("exportPackagingLabel"),description:le("exportPackagingDesc"),settingId:"export-packaging",children:Re(Wf,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:C,value:S,ariaLabel:le("exportPackagingLabel"),onChange:e=>u("export","packaging",e)})}), Re(iy,{label:le("exportFilenameTimestamp"),description:le("exportFilenameTimestampDesc"),settingId:"export-filename-timestamp",checked:c.export?.exportFilenameTimestamp??false,onChange:()=>u("export","exportFilenameTimestamp",!c.export?.exportFilenameTimestamp)}), Re(iy,{label:le("exportIncludeThoughtsLabel"),description:le("exportIncludeThoughtsDesc"),settingId:"export-include-thoughts",checked:c.export?.includeThoughts??true,onChange:()=>u("export","includeThoughts",!(c.export?.includeThoughts??1))}), Re(oy,{label:le("exportCustomUserName"),description:le("exportCustomUserNameDesc"),settingId:"export-custom-user-name",children:Re(hv,{className:"settings-input",value:c.export?.customUserName||"",onChange:e=>u("export","customUserName",e),placeholder:"User",style:{width:"180px"}})}), Re(oy,{label:le("exportCustomModelName"),description:le("exportCustomModelNameDesc"),settingId:"export-custom-model-name",children:Re(hv,{className:"settings-input",value:c.export?.customModelName||"",onChange:e=>u("export","customModelName",e),placeholder:"Site Name",style:{width:"180px"}})})]})]}),r===Ar&&De(ry,{title:le("promptSettingsTitle"),description:le("promptSettingsDesc"),children:[ Re(iy,{label:le("promptDoubleClickSendLabel"),description:le("promptDoubleClickSendDesc"),settingId:"prompt-double-click-send",checked:c.features?.prompts?.doubleClickToSend??false,onChange:()=>d("features","prompts","doubleClickToSend",!c.features?.prompts?.doubleClickToSend)}), Re(oy,{label:le("promptSubmitShortcutLabel"),description:le("promptSubmitShortcutDesc"),settingId:"shortcuts-prompt-submit-shortcut",children:De("select",{className:"settings-select",value:c.features?.prompts?.submitShortcut??"enter",onChange:e=>d("features","prompts","submitShortcut",e.target.value),children:[ Re("option",{value:"enter",children:le("promptSubmitShortcutEnter")}), Re("option",{value:"ctrlEnter",children:le("promptSubmitShortcutCtrlEnter")})]})}), Re(iy,{label:le("queueSettingLabel"),description:le("queueSettingDesc"),settingId:"prompt-queue",checked:c.features?.prompts?.promptQueue??false,onChange:()=>d("features","prompts","promptQueue",!c.features?.prompts?.promptQueue)})]}),r===Nr&&De(ry,{title:le("readingHistoryTitle"),description:le("readingHistoryDesc"),children:[ Re(iy,{label:le("readingHistoryPersistenceLabel"),description:le("readingHistoryPersistenceDesc"),settingId:"reading-history-persistence",checked:c.readingHistory?.persistence??true,onChange:()=>u("readingHistory","persistence",!c.readingHistory?.persistence)}), Re(iy,{label:le("readingHistoryAutoRestoreLabel"),description:le("readingHistoryAutoRestoreDesc"),settingId:"reading-history-auto-restore",checked:c.readingHistory?.autoRestore??true,disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(x),onChange:()=>u("readingHistory","autoRestore",!c.readingHistory?.autoRestore)}), Re(oy,{label:le("readingHistoryCleanup"),settingId:"reading-history-cleanup-days",disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(x),children:De("select",{className:"settings-select",value:c.readingHistory?.cleanupDays||30,onChange:e=>u("readingHistory","cleanupDays",parseInt(e.target.value)),disabled:!c.readingHistory?.persistence,children:[ De("option",{value:1,children:["1 ",le("day")]}), De("option",{value:3,children:["3 ",le("days")]}), De("option",{value:7,children:["7 ",le("days")]}), De("option",{value:30,children:["30 ",le("days")]}), De("option",{value:90,children:["90 ",le("days")]}), Re("option",{value:-1,children:le("forever")})]})})]}),r===Lr&&De(ry,{title:le("interactionEnhance"),description:le("interactionEnhanceDesc"),children:[ Re(iy,{label:le("assistantMermaidLabel"),description:le("assistantMermaidDesc"),settingId:"content-assistant-mermaid",checked:c.content?.assistantMermaid??true,onChange:()=>u("content","assistantMermaid",!(c.content?.assistantMermaid??1))}), Re(iy,{label:le("userQueryMarkdownLabel"),description:le("userQueryMarkdownDesc"),settingId:"content-user-query-markdown",checked:c.content?.userQueryMarkdown??true,onChange:()=>u("content","userQueryMarkdown",!(c.content?.userQueryMarkdown??1))}), Re(iy,{label:le("formulaCopyLabel"),description:le("formulaCopyDesc"),settingId:"content-formula-copy",checked:c.content?.formulaCopy??true,onChange:()=>u("content","formulaCopy",!c.content?.formulaCopy)}), Re(oy,{label:le("formulaCopyFormatLabel"),description:le("formulaCopyFormatDesc"),settingId:"content-formula-copy-format",disabled:!c.content?.formulaCopy,onDisabledClick:()=>m(w),children:Re(Wf,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:T,value:k,ariaLabel:le("formulaCopyFormatLabel"),disabled:!c.content?.formulaCopy,onChange:e=>u("content","formulaCopyFormat",e)})}), Re(iy,{label:le("formulaDelimiterLabel"),description:le("formulaDelimiterDesc"),settingId:"content-formula-delimiter",checked:c.content?.formulaDelimiter??true,disabled:!c.content?.formulaCopy||"latex"!==k,onDisabledClick:()=>{c.content?.formulaCopy?qi(le("formulaDelimiterLatexOnlyToast"),2e3,{},1500,"formula-delimiter-latex-only"):m(w);},onChange:()=>u("content","formulaDelimiter",!c.content?.formulaDelimiter)}), Re(iy,{label:le("tableCopyLabel"),description:le("tableCopyDesc"),settingId:"content-table-copy",checked:c.content?.tableCopy??true,onChange:()=>u("content","tableCopy",!c.content?.tableCopy)})]})]})},mv=(e,t)=>{const n=le(e);return n===e?t:n},fv=({siteId:e})=>{const{settings:t,updateNestedSetting:n}=Mi();if(!t)return null;const r=t.globalSearch?.promptEnterBehavior||"smart",o=t.globalSearch?.doubleShift??ti.globalSearch.doubleShift,i=t.globalSearch?.enableFuzzySearch??false,a=ur(),s=t.shortcuts?.keybindings?.[jn],l=null===s?null:s||rr[jn],c=l?dr(l,a):"",d=[];o&&d.push(mv("globalSearchTriggerDoubleShift","double-press Shift")),c&&d.push(c);const u=((e,t,n)=>{let r=mv(e,t);return Object.keys(n).forEach(e=>{r=r.replace(new RegExp(`{${e}}`,"g"),n[e]);}),r})("globalSearchTriggerHint","Trigger: {shortcut}",{shortcut:d.join(" / ")||mv("shortcutNotSet","Not set")}),h=`shortcut-binding-${jn}`; return De("div",{children:[ Re(sy,{title:mv("navGlobalSearch","Global Search"),Icon:Qt}), Re("p",{className:"settings-page-desc",children:`${mv("globalSearchPageDesc","Configure Search Everywhere behavior and interaction details")} · ${u}`}), De(ry,{title:mv("globalSearchMatchingSettingsTitle","Search Matching"),description:mv("globalSearchMatchingSettingsDesc","Configure how Search Everywhere matches search results"),children:[ Re(oy,{label:mv("globalSearchShortcutSettingLabel","全局搜索快捷键"),description:mv("globalSearchShortcutSettingDesc","跳转到快捷键设置,自定义或禁用全局搜索快捷键。"),settingId:"global-search-shortcut-setting-link",children:Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:wr,settingId:h}}));},children:mv("globalSearchShortcutSettingAction","前往设置")})}), Re(iy,{label:mv("doubleShiftToSearch","Double Shift to open Global Search"),description:mv("doubleShiftToSearchDesc","Press Shift twice quickly to open Global Search"),checked:o,onChange:()=>n("globalSearch","doubleShift",!o),settingId:"global-search-double-shift"}), Re(iy,{label:mv("globalSearchEnableFuzzySearchLabel","Enable fuzzy search"),description:mv("globalSearchEnableFuzzySearchDesc","When enabled, Search Everywhere uses fuzzy matching for title, folder, tag, prompt content, and setting identifiers."),checked:i,onChange:()=>n("globalSearch","enableFuzzySearch",!i),settingId:"global-search-fuzzy-search"})]}), Re(ry,{title:mv("globalSearchPromptSettingsTitle","Prompt Behavior"),description:mv("globalSearchPromptSettingsDesc","Choose what happens when pressing Enter on a prompt result in Search Everywhere"),children:Re(oy,{label:mv("globalSearchPromptEnterBehaviorLabel","Search Everywhere prompt Enter behavior"),description:mv("globalSearchPromptEnterBehaviorDesc","Smart: insert directly when no variable, open variable dialog when needed; Locate only: switch to Prompts and locate the item."),settingId:"global-search-prompt-enter-behavior",children:De("select",{className:"settings-select",value:r,onChange:e=>n("globalSearch","promptEnterBehavior",e.target.value),children:[ Re("option",{value:"smart",children:mv("globalSearchPromptEnterBehaviorSmart","Smart (Recommended)")}), Re("option",{value:"locate",children:mv("globalSearchPromptEnterBehaviorLocate","Locate Only")})]})})})]})},bv=({iconNode:e,label:t,index:n,total:r,enabled:o=true,showToggle:i=false,onToggle:a,onDragStart:s,onDragOver:l,onDragEnd:c,onDrop:d,isDragging:u=false})=>De("div",{className:"settings-sortable-item "+(u?"dragging":""),draggable:true,onDragStart:e=>s(e,n),onDragOver:e=>l(e,n),onDragEnd:c,onDrop:e=>d(e,n),style:{opacity:u?.4:1,cursor:"grab",border:u?"1px dashed var(--gh-primary)":void 0},children:[ Re("div",{className:"settings-sortable-handle",style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px 4px 0",cursor:"grab",color:"var(--gh-text-secondary, #9ca3af)"},children:Re(vt,{size:16})}),e&&Re("span",{className:"settings-sortable-item-icon",children:e}), Re("span",{className:"settings-sortable-item-label",children:t}), Re("div",{className:"settings-sortable-item-actions",children:i&&Re(qf,{checked:o,onChange:()=>a?.(),size:"sm"})})]}),yv=({siteId:e,initialTab:t})=>{const[n,r]=_(t||"panel"),{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l,updateDeepSetting:c}=Mi();L(()=>{t&&r(t);},[t]),le("enablePrerequisiteToast");const[d,u]=_(null),h=(e,t)=>({panel:{...o.panel,[e]:t}}),g=(e,t,n)=>{u({type:t,index:n}),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",`${t}:${n}`);},p=e=>{e.preventDefault(),e.dataTransfer.dropEffect="move";},m=(e,t)=>{if(e.preventDefault(),!d||"tab"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.features?.order||[]],[i]=r.splice(n,1);r.splice(t,0,i),l("features","order",r),u(null);},f=(e,t)=>{if(e.preventDefault(),!d||"button"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.quickButtons?.collapsed||[]],[i]=r.splice(n,1);r.splice(t,0,i),l("quickButtons","collapsed",r),u(null);},b=()=>{u(null);};if(!o)return null;const y=[{id:"panel",label:le("panelTab")},{id:"tabOrder",label:le("tabOrderTab")},{id:"shortcuts",label:le("shortcutsTab")},{id:"toolsMenu",label:le("toolboxMenu")}]; return De("div",{children:[ Re(sy,{title:le("navGeneral"),Icon:it}), Re("p",{className:"settings-page-desc",children:le("generalPageDesc")}), Re(ay,{tabs:y,activeTab:n,onTabChange:r}),"panel"===n&&De(ry,{title:le("panelSettings"),children:[ Re(oy,{label:le("panelModeLabel"),description:le("panelModeDesc"),settingId:"panel-mode",children:Re("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[{value:"edge-snap",label:le("panelModeEdgeSnap"),Icon:Jt},{value:"floating",label:le("panelModeFloating"),Icon:en}].map((e,t)=>De("button",{type:"button","aria-pressed":(o.panel?.panelMode??"edge-snap")===e.value,onClick:()=>l("panel","panelMode",e.value),style:{display:"inline-flex",alignItems:"center",gap:"5px",padding:"4px 12px",fontSize:"13px",border:"none",borderLeft:t>0?"1px solid var(--gh-border, #e5e7eb)":"none",cursor:"pointer",background:(o.panel?.panelMode??"edge-snap")===e.value?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:(o.panel?.panelMode??"edge-snap")===e.value?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:[ Re(e.Icon,{size:14}),e.label]},e.value))})}), Re(oy,{label:le("defaultPositionLabel"),description:le("defaultPositionDesc"),settingId:"panel-default-position",children:De("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[ Re("button",{onClick:()=>l("panel","defaultPosition","left"),style:{padding:"4px 12px",fontSize:"13px",border:"none",cursor:"pointer",background:"left"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"left"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:le("defaultPositionLeft")}), Re("button",{onClick:()=>l("panel","defaultPosition","right"),style:{padding:"4px 12px",fontSize:"13px",border:"none",borderLeft:"1px solid var(--gh-border, #e5e7eb)",cursor:"pointer",background:"right"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"right"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:le("defaultPositionRight")})]})}), Re(oy,{label:le("panelWidthLabel"),description:le("panelWidthDesc"),settingId:"panel-width",children:Re(Hf,{value:Math.max(o.panel?.width??320,240),onChange:e=>{i(h("width",e));},onPreviewChange:e=>{a(h("width",e));},onCancelPreview:s,min:240,max:600,step:10,unit:"px",defaultValue:320,formatValue:e=>`${e}px`,ariaLabel:le("panelWidthLabel")})}), Re(oy,{label:le("panelHeightLabel"),description:le("panelHeightDesc"),settingId:"panel-height",children:Re(Hf,{value:o.panel?.height??85,onChange:e=>{i(h("height",e));},onPreviewChange:e=>{a(h("height",e));},onCancelPreview:s,min:50,max:100,step:1,unit:"vh",defaultValue:85,formatValue:e=>`${e}vh`,ariaLabel:le("panelHeightLabel")})}),"edge-snap"===(o.panel?.panelMode??"edge-snap")&&Re(oy,{label:le("edgeSnapThresholdLabel"),description:le("edgeSnapThresholdDesc"),settingId:"panel-edge-snap-threshold",children:Re(Hf,{value:o.panel?.edgeSnapThreshold??30,onChange:e=>{i(h("edgeSnapThreshold",e));},onPreviewChange:e=>{a(h("edgeSnapThreshold",e));},onCancelPreview:s,min:0,max:400,step:2,unit:"px",defaultValue:30,formatValue:e=>`${e}px`,ariaLabel:le("edgeSnapThresholdLabel")})}),"floating"===(o.panel?.panelMode??"edge-snap")&&Re(oy,{label:le("defaultEdgeDistanceLabel"),description:le("defaultEdgeDistanceDesc"),settingId:"panel-edge-distance",children:Re(Hf,{value:o.panel?.defaultEdgeDistance??0,onChange:e=>{i(h("defaultEdgeDistance",e));},onPreviewChange:e=>{a(h("defaultEdgeDistance",e));},onCancelPreview:s,min:0,max:400,step:5,unit:"px",defaultValue:0,formatValue:e=>`${e}px`,ariaLabel:le("defaultEdgeDistanceLabel")})})]}),"tabOrder"===n&&Re(ry,{title:le("tabOrderSettings"),description:le("tabOrderDesc"),children:o.features?.order?.filter(e=>Gr[e]).map((e,t)=>{const n=Gr[e],r="prompts"===e?false!==o.features?.prompts?.enabled:"outline"===e?false!==o.features?.outline?.enabled:"conversations"!==e||false!==o.features?.conversations?.enabled; return Re(bv,{iconNode:n.IconComponent?Re(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:le(n.label),index:t,total:o.features?.order.filter(e=>Gr[e]).length,enabled:r,showToggle:true,onToggle:()=>{"prompts"===e?c("features","prompts","enabled",!r):"outline"===e?c("features","outline","enabled",!r):"conversations"===e&&c("features","conversations","enabled",!r);},onDragStart:e=>g(e,"tab",t),onDragOver:p,onDragEnd:b,onDrop:m,isDragging:"tab"===d?.type&&d?.index===t},e)})}),"shortcuts"===n&&De(Ne,{children:[ De(ry,{title:le("quickButtonsBehaviorTitle"),description:le("quickButtonsBehaviorDesc"),children:[ Re(iy,{label:le("quickButtonsHideWhenPanelOpenLabel"),description:le("quickButtonsHideWhenPanelOpenDesc"),settingId:"quick-buttons-hide-when-panel-open",checked:o.quickButtons?.hideWhenPanelOpen??false,onChange:()=>l("quickButtons","hideWhenPanelOpen",!o.quickButtons?.hideWhenPanelOpen)}), Re(oy,{label:le("quickButtonsProximityRadiusLabel"),description:le("quickButtonsProximityRadiusDesc"),settingId:"quick-buttons-proximity-radius",children:De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("input",{type:"range",min:"0",max:"300",step:"10",value:o.quickButtons?.proximityRadius??150,onChange:e=>l("quickButtons","proximityRadius",parseInt(e.target.value,10)),style:{width:"120px"}}), De("span",{style:{fontSize:"12px",minWidth:"36px"},children:[o.quickButtons?.proximityRadius??150,"px"]})]})}), Re(oy,{label:le("quickButtonsOpacityLabel"),description:le("quickButtonsOpacityDesc"),settingId:"quick-buttons-opacity",children:De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("input",{type:"range",min:"0.4",max:"1",step:"0.05",value:o.quickButtons?.opacity??1,onChange:e=>l("quickButtons","opacity",parseFloat(e.target.value)),style:{width:"120px"}}), De("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(o.quickButtons?.opacity??1)),"%"]})]})})]}), Re(ry,{title:le("collapsedButtonsOrderTitle"),description:le("collapsedButtonsOrderDesc"),children:o.quickButtons?.collapsed?.map((e,t)=>{if("manualAnchor"===e.id)return null;const n=Vr[e.id];return n?Re(bv,{iconNode:n.IconComponent?Re(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:le(n.labelKey),index:t,total:o.quickButtons.collapsed.length,enabled:e.enabled,showToggle:n.canToggle,onToggle:()=>(e=>{const t=[...o.quickButtons?.collapsed||[]];t[e]={...t[e],enabled:!t[e].enabled},l("quickButtons","collapsed",t);})(t),onDragStart:e=>g(e,"button",t),onDragOver:p,onDragEnd:b,onDrop:f,isDragging:"button"===d?.type&&d?.index===t},e.id):null})})]}),"toolsMenu"===n&&Re(ry,{title:le("toolboxMenuTitle"),description:le("toolboxMenuDesc"),children:$o.filter(e=>e.id!==Bo).map(e=>{const t=(o.quickButtons?.toolsMenu??$o.map(e=>e.id)).includes(e.id); return Re(iy,{label:le(e.labelKey),settingId:`tools-menu-${e.id}`,checked:t,onChange:()=>{const n=o.quickButtons?.toolsMenu??$o.map(e=>e.id),r=t?n.filter(t=>t!==e.id):[...n,e.id];l("quickButtons","toolsMenu",r);}},e.id)})})]})},vv=[{id:"storage",name:"存储",nameKey:"permissionStorage",description:"permissionStorageDesc",icon:"💾"}],xv=[{id:"notifications",name:"通知",nameKey:"permissionNotifications",description:"permissionNotificationsDesc",icon:"🔔",permissions:["notifications"]},{id:"cookies",name:"Cookie管理",nameKey:"permissionCookies",description:"permissionCookiesDesc",icon:"🍪",permissions:["cookies"]}],wv=[{id:"webdav",name:"WebDAV 访问权限",nameKey:"permissionWebdavAccess",description:"permissionWebdavAccessDesc",icon:"☁️",origins:[""]}],Sv=()=>{const{updateNestedSetting:e}=Mi(),[t,n]=_({}),[r,o]=_(true),[i,a]=_({open:false,message:"",onConfirm:()=>{}}),s=void 0!==chrome.permissions,l=E(async()=>{o(true);const e={};for(const n of xv)try{let t=!1;if(s)t=await chrome.permissions.contains({permissions:n.permissions||[]});else {const e=await md({type:ud,permissions:n.permissions||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}for(const n of wv)try{let t=!1;if(s)t=await chrome.permissions.contains({origins:n.origins||[]});else {const e=await md({type:ud,origins:n.origins||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}n(e),o(false);},[s]),c=E(async e=>{try{if(s){await chrome.permissions.request({origins:e.origins?.length?e.origins:void 0,permissions:e.permissions?.length?e.permissions:void 0})&&n(t=>({...t,[e.id]:!0}));}else await md({type:hd,permType:e.id,origins:e.origins,permissions:e.permissions}),setTimeout(()=>l(),2e3);}catch(t){console.error(`请求权限 ${e.id} 失败:`,t);}},[s,l]);L(()=>{if(l(),s&&"undefined"!=typeof window){"true"===new URLSearchParams(window.location.search).get("auto_request")&&setTimeout(()=>{const e=wv[0];e&&c(e);},500);}},[l,s,c]);const d=t=>{let r=le("revokeConfirmDefault");"notifications"===t.id?r=le("revokeConfirmNotifications"):"webdav"===t.id&&(r=le("revokeConfirmWebdav")),a({open:true,message:Re("div",{style:{whiteSpace:"pre-wrap"},children:r}),onConfirm:()=>(async t=>{try{let r=!1;if(s)r=await chrome.permissions.remove({origins:t.origins?.length?t.origins:void 0,permissions:t.permissions?.length?t.permissions:void 0});else {const e=await md({type:"REVOKE_PERMISSIONS",origins:t.origins,permissions:t.permissions});e&&e.success&&(r=e.removed);}r&&(n(e=>({...e,[t.id]:!1})),"notifications"===t.id?e("tab","showNotification",!1):"webdav"===t.id&&e("content","watermarkRemoval",!1));}catch(r){console.error(`撤销权限 ${t.id} 失败:`,r);}finally{a(e=>({...e,open:false}));}})(t)});}; return De("div",{children:[ Re(sy,{title:le("navPermissions"),Icon:ct}), Re("p",{className:"settings-page-desc",children:le("permissionsPageDesc")}), De(ry,{title:le("optionalPermissions"),description:le("optionalPermissionsDesc"),children:[ De("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",paddingBottom:"12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ Re("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #9ca3af)"},children:le("permissionsSyncHint")}), Re("button",{className:"settings-btn settings-btn-secondary",onClick:async e=>{e.preventDefault(),e.stopPropagation(),await l(),Pi(le("permissionsRefreshed"),1500);},disabled:r,style:{fontSize:"12px",padding:"4px 12px",flexShrink:0},children:le(r?"refreshing":"refreshStatus")})]}),[...xv,...wv].map((e,n,r)=>Re(oy,{label:De("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("span",{style:{fontSize:"18px"},children:e.icon}), Re("span",{children:le(e.nameKey)})]}),description:le(e.description),style:n===r.length-1?{borderBottom:"none"}:{},children:Re("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:t[e.id]?De(Ne,{children:[ Re("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(16, 185, 129, 0.1)",color:"#10b981"},children:le("granted")}), Re("button",{className:"settings-btn settings-btn-secondary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),d(e);},children:le("revoke")})]}):De(Ne,{children:[ Re("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(239, 68, 68, 0.1)",color:"#ef4444"},children:le("notGranted")}), Re("button",{className:"settings-btn settings-btn-primary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),c(e);},children:le("allowRecommended")})]})})},e.id))]}), Re(ry,{title:le("requiredPermissions"),description:le("requiredPermissionsDesc"),children:vv.map((e,t)=>Re(oy,{label:De("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("span",{style:{fontSize:"18px"},children:e.icon}), Re("span",{children:le(e.nameKey)})]}),description:le(e.description),style:t===vv.length-1?{borderBottom:"none"}:{},children:Re("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(107, 114, 128, 0.1)",color:"var(--gh-text-secondary, #6b7280)"},children:le("required")})},e.id))}),i.open&&Re(_f,{title:le("warning"),message:i.message,confirmText:le("confirm"),cancelText:le("cancel"),danger:true,onConfirm:i.onConfirm,onCancel:()=>a(e=>({...e,open:false}))})]})},Cv=({binding:e,onChange:t,onRemove:n,conflictWarning:r})=>{const[o,i]=_(false),a=ur(),s=E(e=>{if(!o)return;if(e.preventDefault(),e.stopPropagation(),["Control","Alt","Shift","Meta"].includes(e.key))return;if(!a&&e.getModifierState("AltGraph"))return;const n={key:sr(e.key,e.code),alt:e.altKey,ctrl:a?e.metaKey:e.ctrlKey,shift:e.shiftKey};if(!(n.alt||n.ctrl||n.meta||n.shift)){if(!["Escape","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"].includes(e.key))return}a&&e.ctrlKey&&!e.metaKey||(t(n),i(false));},[o,t,a]),l=o?le("pressAnyKey"):e?dr(e,a):le("shortcutNotSet"); return De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re("button",{className:`shortcut-input ${o?"recording":""} ${e?"":"not-set"}`,onClick:()=>i(true),onKeyDown:s,onBlur:()=>{i(false);},style:{padding:"6px 12px",minWidth:"120px",fontSize:"13px",fontFamily:"monospace",border:o?"2px solid var(--gh-primary)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"6px",background:o?"var(--gh-bg-hover)":"var(--gh-bg)",color:e?"var(--gh-text)":"var(--gh-text-tertiary)",cursor:"pointer",textAlign:"center",transition:"all 0.2s",fontStyle:e?"normal":"italic"},children:l}),e&&Re(od,{content:le("shortcutRemove"),children:Re("button",{onClick:n,style:{padding:"4px 8px",fontSize:"12px",border:"1px solid var(--gh-border)",borderRadius:"4px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer",transition:"all 0.2s"},children:"✕"})}),r&&Re("span",{style:{fontSize:"12px",color:"var(--gh-error, #ef4444)"},children:r})]})},kv=({siteId:e})=>{const{settings:t,setSettings:n}=Mi(),r=t?.shortcuts,o=i.useMemo(()=>ur(),[]),a=E((e,t)=>{if(!t)return;const n=lr(t);if(!n)return;const o=r?.keybindings||{};for(const[r,i]of Object.entries(o)){if(r===e)continue;if(null===i)continue;const t=tr[r];if(!t)continue;const o=lr(i);if(o&&(o.key===n.key&&!!o.alt==!!n.alt&&!!o.ctrl==!!n.ctrl&&!!o.shift==!!n.shift)){return [le("shortcutConflictWith"),`"${le(t.labelKey)}"`,le("shortcutConflict")].filter(Boolean).join(" ")}}},[r?.keybindings]),s=E((e,t)=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:t}}});},[r,n]),l=E(e=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:null}}});},[r,n]),[c,d]=_(false),u=E(()=>{n({shortcuts:{...r,keybindings:{...rr}}}),d(false);},[r,n]),h=Object.entries(nr).map(([e,t])=>{const n=Object.entries(tr).filter(([,t])=>t.category===e);return {categoryId:e,categoryMeta:t,actions:n}});return t?De("div",{children:[ Re(sy,{title:le("navShortcuts"),Icon:Mt}), Re("p",{className:"settings-page-desc",children:le("shortcutsPageDesc")}), De(ry,{title:le("shortcutsGlobalSettings"),children:[ Re(iy,{label:le("enableShortcuts"),description:le("enableShortcutsDesc"),checked:r?.enabled??true,settingId:"shortcuts-enabled",onChange:()=>n({shortcuts:{...r,enabled:!(r?.enabled??1),globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:r?.keybindings??rr}})}),$i.hasCapability("commands")&&De(Ne,{children:[ Re(oy,{label:le("globalShortcutUrl"),description:(()=>{const e=le("globalShortcutUrlDesc",{shortcut:o?"⌥O":"Alt+O"});return "globalShortcutUrlDesc"===e?o?"按下全局快捷键 ⌥O 时打开的网址":"按下全局快捷键 Alt+O 时打开的网址":e})(),settingId:"shortcuts-global-url",children:Re("input",{type:"text",className:"settings-input",value:r?.globalUrl||"https://gemini.google.com",onChange:e=>n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:e.target.value,keybindings:r?.keybindings??rr}}),style:{width:"280px"},placeholder:"https://gemini.google.com"})}), Re(oy,{label:le("globalShortcutsTitle"),description:le("globalShortcutsDesc"),settingId:"shortcuts-browser-shortcuts",children:(()=>{const e=navigator.userAgent,t=e.includes("Chrome")&&!e.includes("Edg/"),n=e.includes("Edg/"),r=e.includes("Firefox");if(!(t||n||r)) return Re("span",{style:{fontSize:"13px",color:"var(--gh-text-tertiary)"},children:le("browserNotSupported")});let o="chrome://extensions/shortcuts";return n&&(o="edge://extensions/shortcuts"),r?Re("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:"1.5"},children:le("firefoxShortcutsGuide")}):Re("button",{onClick:()=>md({type:"OPEN_URL",url:o}),style:{padding:"6px 12px",fontSize:"13px",border:"none",borderRadius:"6px",background:"var(--gh-primary)",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},children:le("openBrowserShortcuts")})})()})]}), Re("div",{style:{marginTop:"16px",paddingTop:"16px",display:"flex",justifyContent:"flex-end"},children:Re("button",{onClick:()=>d(true),style:{padding:"8px 16px",fontSize:"13px",border:"1px solid var(--gh-border)",borderRadius:"6px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer"},children:le("resetShortcuts")})})]}),h.map(({categoryId:e,categoryMeta:t,actions:n})=>Re(ry,{title:le(t.labelKey),children:n.map(([e,t])=>{const n=r?.keybindings?.[e],o=null===n?null:n||rr[e],i=a(e,o); return Re(oy,{label:le(t.labelKey),disabled:!r?.enabled,settingId:`shortcut-binding-${e}`,children:Re(Cv,{binding:o,onChange:t=>s(e,t),onRemove:()=>l(e),conflictWarning:i||void 0})},e)})},e)),c&&Re(_f,{title:le("resetShortcuts"),message:le("resetShortcutsConfirm"),danger:true,onConfirm:u,onCancel:()=>d(false)})]}):null};let Tv=null;const Ev=Fo()(Wo((e,t)=>(Tv=()=>e({_hasHydrated:true}),{keys:[],currentKeyId:"",_hasHydrated:false,addKey:t=>{const n={id:crypto.randomUUID(),...t,createdAt:Date.now()};return e(e=>({keys:[...e.keys,n]})),n},updateKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,...n}:e)})),deleteKey:t=>e(e=>({keys:e.keys.filter(e=>e.id!==t),currentKeyId:e.currentKeyId===t?"":e.currentKeyId})),setCurrentKey:t=>e({currentKeyId:t}),testKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,isValid:n.isValid,accountType:n.accountType,testedAt:Date.now()}:e)})),setKeys:t=>e({keys:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"claudeSessionKeys",storage:Uo(()=>gi),partialize:e=>({keys:e.keys,currentKeyId:e.currentKeyId}),onRehydrateStorage:()=>()=>{Tv?.();}})),Av=Object.freeze(Object.defineProperty({__proto__:null,useClaudeSessionKeysStore:Ev},Symbol.toStringTag,{value:"Module"})),Mv=({siteId:e})=>{const{keys:t,currentKeyId:n,addKey:r,deleteKey:o,setCurrentKey:i,testKey:a,setKeys:s}=Ev(),[l,c]=_({}),[d,u]=_({type:"none"}),[h,g]=_(null),[p,m]=_(null),[f,b]=_(false),[y,v]=_(""),x=e===uo,w=t.find(e=>e.id===n),S=()=>u({type:"none"}),C=async(e,t)=>{try{await navigator.clipboard.writeText(t),m(e),Pi(le("claudeKeyCopied"),Zr),setTimeout(()=>m(null),Zr);}catch{Pi(le("claudeKeyCopyFailed"),Zr);}},k=async e=>{if(!e)return void Pi(le("claudePleaseSelectKey"),Zr);if(e===n)return void Pi(le("claudeAlreadyUsing"),Zr);if($i.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Pi(le("claudeRequestPermission"),Xr)}else {if(!(await md({type:ud,permissions:["cookies"]})).hasPermission)return await md({type:hd,permType:"cookies"}),void Pi(le("claudeRequestPermission"),Xr)}const r=e?t.find(t=>t.id===e)?.key:"";await $i.setClaudeSessionKey(r||""),i(e),Pi(le("claudeKeySwitched"),Yr);},T=async(e,t,n,r=true)=>{if($i.hasCapability("tabs"))try{if((await md({type:"CHECK_CLAUDE_GENERATING"})).isGenerating)return r&&Pi(le("claudeGenerating"),Xr),!1}catch{}c(t=>({...t,[e]:true}));try{const o=await $i.testClaudeSessionKey(n);return o.isValid?(a(e,{isValid:!0,accountType:o.accountType}),r&&Pi(`${t}: ${o.accountType}`,Yr),!0):(a(e,{isValid:!1}),r&&Pi(`${t}: ${le("claudeKeyInvalid")}`,Yr),!1)}catch{return a(e,{isValid:false}),r&&Pi(`${t}: ${le("claudeKeyTest")} ${le("claudeKeyInvalid")}`,Yr),false}finally{c(t=>({...t,[e]:false}));}},E=async e=>{const n=t.find(t=>t.id===e);n&&await T(e,n.name,n.key,true);}; return De("div",{children:[ De(ry,{title:le("claudeSessionKeyTitle"),description:le("claudeSessionKeyDesc"),settingId:"claude-session-keys",children:[ De("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px",marginBottom:"20px",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"12px",border:"1px solid var(--gh-border)",flexWrap:"wrap",gap:"12px"},children:[ De("div",{style:{display:"flex",alignItems:"center",gap:"12px",flex:"1 1 auto"},children:[ Re("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:le("claudeCurrentUsing")}), Re("span",{style:{fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",gap:"8px"},children:w?De(Ne,{children:[ De("span",{style:{fontWeight:600},children:["🔑 ",w.name]}),w.accountType&&Re("span",{style:{padding:"2px 8px",borderRadius:"12px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text-secondary)"},children:w.accountType})]}):Re("span",{style:{color:"var(--gh-text-secondary)"},children:le("claudeNoKeySelected")})})]}), De("div",{style:{display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap"},children:[!x&&De("div",{style:{color:"#ca8a04",backgroundColor:"rgba(234, 179, 8, 0.1)",fontSize:"12px",display:"flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"6px",border:"1px solid rgba(234, 179, 8, 0.2)",whiteSpace:"nowrap"},children:[ Re("span",{children:"⚠️"}), Re("span",{children:le("claudeNotOnSiteHint")})]}), Re(od,{content:x?"":le("claudeNotOnSiteHint"),children:Re("select",{className:"settings-select",value:n,onChange:e=>k(e.target.value),disabled:!x||0===t.length||f,style:{minWidth:"200px",padding:"8px 12px",fontSize:"13px",borderRadius:"8px",opacity:!x||0===t.length||f?.6:1,cursor:!x||f?"not-allowed":"pointer",backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text)"},children:0===t.length?Re("option",{value:"",children:le("claudePleaseAddKey")}):t.map(e=>De("option",{value:e.id,children:["🔑 ",e.name," ",e.accountType?`(${e.accountType})`:""]},e.id))})})]})]}), De("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"nowrap"},children:[ De("button",{className:"settings-btn settings-btn-primary",onClick:()=>{u({type:"add"});},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["➕ ",le("claudeAddKey")]}), Re("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{if(0===t.length)return;if(f)return;b(true);let e=0,n=0;try{for(let r=0;rsetTimeout(e,co));}Pi(le("claudeBatchTestDone").replace("{valid}",String(e)).replace("{invalid}",String(n)),Xr);}catch{Pi(le("claudeBatchTestFailed"),Yr);}finally{b(false),v("");}},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,backgroundColor:f?"rgba(var(--gh-primary-rgb), 0.1)":void 0,color:f?"var(--gh-primary)":void 0,borderColor:f?"var(--gh-primary)":void 0,whiteSpace:"nowrap"},children:De(Ne,f?{children:[ Re("div",{style:{marginRight:"8px",width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}),y]}:{children:["⚡ ",le("claudeBatchTest")]})}),$i.hasCapability("cookies")&&Re(od,{content:x?"":le("claudeNotOnSiteHint"),children:De("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{try{if($i.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Pi(le("claudeRequestPermission"),Xr)}else {if(!(await md({type:ud,permissions:["cookies"]})).hasPermission)return await md({type:hd,permType:"cookies"}),void Pi(le("claudeRequestPermission"),Xr)}const e=await $i.getClaudeSessionKey();if(!e.success)return void Pi(e.error||le("claudeNoCookieFound"),Yr);const n=t.find(t=>t.key===e.sessionKey);if(n)return void Pi(le("claudeTokenExists").replace("{name}",n.name),Yr);u({type:"import-name",sessionKey:e.sessionKey});}catch(RS){Pi(le("claudeKeyCopyFailed")+": "+RS.message,Xr);}},disabled:!x||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:!x||f?.6:1,backgroundColor:x?"var(--gh-bg)":"var(--gh-bg-secondary)",color:x?"var(--gh-primary)":"var(--gh-text-secondary)",borderColor:x?"var(--gh-primary)":"var(--gh-border)",whiteSpace:"nowrap"},children:["🌐 ",le("claudeImportFromBrowser")]})}), De("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.onchange=async e=>{const n=e.target.files?.[0];if(n)try{const e=await n.text(),r=JSON.parse(e);if(!Array.isArray(r))return void Pi(le("claudeInvalidJSON"),Yr);const o=new Set(t.map(e=>e.key)),i=r.filter(e=>!o.has(e.key));if(0===i.length)return void Pi(le("claudeNoNewTokens"),Zr);s([...t,...i]),Pi(le("claudeImported").replace("{count}",String(i.length)),Yr);}catch(RS){Pi(le("claudeInvalidJSON")+": "+RS.message,Xr);}},e.click();},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["📥 ",le("claudeImportJSON")]}), De("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{if(0===t.length)return void Pi(le("claudeNoTokensToExport"),Zr);const e=JSON.stringify(t,null,2),n=new Blob([e],{type:"application/json"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=`claude-session-keys-${Date.now()}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r),Pi(le("claudeExported"),Zr);},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,whiteSpace:"nowrap"},children:["📤 ",le("claudeExportJSON")]})]}),0===t.length?De("div",{style:{padding:"48px 24px",textAlign:"center",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"8px",border:"1px dashed var(--gh-border)"},children:[ Re("div",{style:{marginBottom:"8px",fontSize:"24px"},children:"🔑"}), Re("div",{children:le("claudeNoKeys")}), Re("div",{style:{fontSize:"12px",marginTop:"4px"},children:le("claudeNoKeysHint")})]}):Re("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.map(e=>{const t=e.id===n,r=h===e.id; return De("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px",padding:"16px 20px",backgroundColor:t?"var(--gh-bg)":"var(--gh-bg-secondary)",borderRadius:"12px",border:t?"2px solid var(--gh-primary)":"1px solid var(--gh-border)",transition:"all 0.2s ease",boxShadow:t?"var(--gh-shadow-brand)":"none"},onMouseEnter:()=>g(e.id),onMouseLeave:()=>g(null),children:[ De("div",{style:{display:"flex",flexDirection:"column",gap:"6px",flex:"1 1 auto",minWidth:0},children:[ De("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Re("span",{style:{fontWeight:600,fontSize:"15px",color:"var(--gh-text)"},children:e.name}),t&&Re("span",{style:{fontSize:"11px",color:"var(--gh-primary)",backgroundColor:"var(--gh-bg-secondary)",padding:"1px 6px",borderRadius:"4px",fontWeight:500,border:"1px solid var(--gh-border)"},children:"当前使用"}),(i=e.accountType,Re("span",i?{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg-secondary)"},children:i}:{style:{color:"var(--gh-text-secondary)"},children:le("claudeKeyUntested")}))]}), De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re(od,{content:le("claudeKeyDoubleTapCopy"),children:De("code",{onDoubleClick:()=>C(e.id,e.key),style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-tertiary)",padding:"2px 6px",borderRadius:"4px",cursor:"pointer",maxWidth:"300px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.key.substring(0,32),"..."]})}),(r||p===e.id)&&Re(od,{content:p===e.id?le("claudeCopied"):le("claudeCopyKey"),children:Re("button",{onClick:t=>{t.stopPropagation(),C(e.id,e.key);},style:{background:"none",border:"none",cursor:p===e.id?"default":"pointer",fontSize:"12px",padding:"2px",color:p===e.id?"var(--gh-secondary)":"var(--gh-text-tertiary)"},children:p===e.id?"✓":Re(It,{size:14})})})]})]}), De("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[ Re("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:(o=e.isValid,void 0===o?Re("span",{style:{color:to},children:"-"}):De("span",o?{style:{color:Jr,fontWeight:500},children:["✓ ",le("claudeKeyValid")]}:{style:{color:eo,fontWeight:500},children:["✗ ",le("claudeKeyInvalid")]}))}), De("div",{style:{display:"flex",gap:"8px"},children:[ Re(od,{content:le(t?"claudeAlreadyUsing":x?"claudeKeyUse":"claudeNotOnSiteHint"),children:Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>k(e.id),disabled:!x||t,style:{padding:"6px 12px",fontSize:"13px",opacity:!x||t?.5:1,cursor:!x||t?"not-allowed":"pointer"},children:le(t?"claudeKeyUsing":"claudeKeyUse")})}), Re("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",minWidth:"60px",justifyContent:"center"},onClick:()=>E(e.id),disabled:l[e.id],children:l[e.id]?Re("div",{style:{width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}):le("claudeKeyTest")}), Re("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",color:"var(--gh-danger)",borderColor:"rgba(239, 68, 68, 0.2)",backgroundColor:"rgba(239, 68, 68, 0.05)"},onClick:()=>{return t=e.id,n=e.name,void u({type:"delete",id:t,name:n});var t,n;},children:le("claudeKeyDelete")}), Re("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n "})]})]})]},e.id);var o,i;})})]}),"add"===d.type&&Re(Iv,{onConfirm:(e,n)=>{e.trim()?n.trim()?lo.CLAUDE_KEY.test(n)?t.some(e=>e.key===n)?Pi(le("claudeKeyExists"),Yr):(r({name:e.trim(),key:n.trim()}),Pi(le("claudeKeyAdded"),Zr),S()):Pi(le("claudeKeyInvalidFormat"),Yr):Pi(le("claudeKeyRequired"),Zr):Pi(le("claudeNameRequired"),Zr);},onCancel:S}),"import-name"===d.type&&Re(Of,{title:le("claudeImportNameTitle"),defaultValue:`Import-${(new Date).toLocaleDateString()}`,placeholder:le("claudeImportNamePlaceholder"),onConfirm:e=>{if(!e.trim())return void Pi(le("claudeNameRequired"),Zr);const t=d,n=r({name:e.trim(),key:t.sessionKey});i(n.id),Pi(le("claudeKeyImported"),Zr),S(),setTimeout(()=>E(n.id),co);},onCancel:S}),"delete"===d.type&&Re(_f,{title:le("claudeDeleteConfirmTitle"),message:le("claudeDeleteConfirmMsg").replace("{name}",d.name),confirmText:le("claudeKeyDelete"),danger:true,onConfirm:()=>{o(d.id),Pi(le("claudeKeyDeleted"),Zr),S();},onCancel:S})]})},Iv=({onConfirm:e,onCancel:t})=>{const[n,r]=_(""),[o,a]=_(""),s=i.useRef(null);i.useEffect(()=>{s.current?.focus();},[]);const l=()=>{e(n,o);}; return De($f,{onClose:t,children:[ Re("div",{className:"gh-dialog-title",children:le("claudeAddKey")}), De("div",{style:{display:"flex",flexDirection:"column",gap:"16px",marginBottom:"24px"},children:[ De("div",{children:[ Re("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:le("claudeAddKeyNameTitle").split("-")[1].trim().replace("输入","")}), Re("input",{ref:s,type:"text",className:"gh-dialog-input",value:n,onChange:e=>r(e.target.value),placeholder:le("claudeAddKeyNamePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&document.getElementById("claude-key-input")?.focus()})]}), De("div",{children:[ Re("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:"Session Key"}), Re("input",{id:"claude-key-input",type:"text",className:"gh-dialog-input",value:o,onChange:e=>a(e.target.value),placeholder:le("claudeAddKeyValuePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&l()})]})]}), De("div",{className:"gh-dialog-buttons",children:[ Re("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:t,children:le("cancel")}), Re("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:l,children:le("confirm")})]})]})},Lv=({label:e,siteKey:t,settings:n,setSettings:r,placeholder:o,onDisabledClick:i,settingId:a})=>{const s=q(()=>n.modelLock?.[t]||{enabled:false,keyword:""},[n.modelLock,t]),[l,c]=_(s.keyword);L(()=>{c(s.keyword);},[s.keyword]);const d=E(()=>{l!==s.keyword&&r({modelLock:{...n.modelLock,[t]:{...s,keyword:l}}});},[l,s,n.modelLock,t,r]); return De("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:s.enabled?"default":"not-allowed"},"data-setting-id":a,children:[ Re("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:s.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:e}), Re("div",{onMouseDown:e=>{s.enabled||(e.preventDefault(),i?.());},children:Re("input",{type:"text",className:"settings-input",value:l,onChange:e=>c(e.target.value),onBlur:d,onKeyDown:e=>{"Enter"===e.key&&(d(),e.target.blur());},placeholder:o,disabled:!s.enabled,style:{width:"200px",opacity:s.enabled?1:.5,pointerEvents:s.enabled?"auto":"none"}})}), Re(qf,{checked:s.enabled,onChange:()=>{r({modelLock:{...n.modelLock,[t]:{...s,enabled:!s.enabled}}});}})]})},Nv=({settings:e,setSettings:t,onDisabledClick:n,settingId:r})=>{const o="aistudio",i=e.modelLock?.[o]||{enabled:false,keyword:""},[a,s]=_(e.aistudio?.cachedModels||[]),[l,c]=_(false);L(()=>{e.aistudio?.cachedModels&&s(e.aistudio.cachedModels);},[e.aistudio?.cachedModels]); return De("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:i.enabled?"default":"not-allowed"},"data-setting-id":r,children:[ Re("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:i.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:"AI Studio"}), Re(od,{content:le("aistudioRefreshModelListTooltip"),children:Re("button",{className:"icon-button",onClick:async()=>{c(true);try{const n=await md({type:"GET_AISTUDIO_MODELS"});if(n.success&&n.models)s(n.models),t({aistudio:{...e.aistudio,cachedModels:n.models}}),Pi(le("aistudioModelsFetched"),2e3);else {Pi("NO_AISTUDIO_TAB"===n.error?le("aistudioNoTabError"):le("aistudioModelsError"),3e3);}}catch(n){Pi(le("aistudioModelsError"),3e3),console.error("Refresh model list failed:",n);}finally{c(false);}},disabled:l,style:{padding:"4px",opacity:l?.5:1,cursor:l?"not-allowed":"pointer",background:"transparent",border:"none",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center"},children:Re(Ue,{size:16})})}), Re("div",{onMouseDown:e=>{i.enabled||(e.preventDefault(),n?.());},children:De("select",{className:"settings-select",value:i.keyword||"",onChange:n=>{return r=n.target.value,void t({modelLock:{...e.modelLock,[o]:{...i,keyword:r}}});var r;},disabled:!i.enabled||0===a.length,style:{width:"200px",opacity:i.enabled?1:.5,pointerEvents:i.enabled?"auto":"none"},children:[0===a.length&&Re("option",{value:"",children:le("aistudioRefreshModelListFirst")}),a.map(e=>Re("option",{value:e.id,children:e.name},e.id))]})}), Re(qf,{checked:i.enabled,onChange:()=>{t({modelLock:{...e.modelLock,[o]:{...i,enabled:!i.enabled}}});}})]})},Rv=({siteId:e,initialTab:t})=>{const[n,r]=_(t||qr);L(()=>{t&&r(t);},[t]);const{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l}=Mi(),c=le("enablePrerequisiteToast"),d=e=>qi(c.replace("{setting}",e),2e3,{},1500,e),u=le("enablePageWidth"),h=le("enableUserQueryWidth"),g=le("modelLockTitle"),p=o?.layout?.pageWidth?.[e]||o?.layout?.pageWidth?._default,m=o?.layout?.userQueryWidth?.[e]||o?.layout?.userQueryWidth?._default,f=o?.layout?.zenMode?.[e]||o?.layout?.zenMode?._default||{enabled:false,showExitButton:true},b=(e,t)=>{const n=Number.parseInt(e??t,10);return Number.isNaN(n)?Number.parseInt(t,10):n},y=b(p?.value,so.PAGE_WIDTH.DEFAULT_PERCENT),v=b(m?.value,so.USER_QUERY_WIDTH.DEFAULT_PERCENT),x=(t,n)=>{if(!o)return;const r="pageWidth"===t?so.PAGE_WIDTH:so.USER_QUERY_WIDTH,i=("pageWidth"===t?p:m)||{enabled:false,value:r.DEFAULT_PERCENT,unit:"%"},a=Math.min(r.MAX_PERCENT,Math.max(r.MIN_PERCENT,n));return {layout:{...o.layout,[t]:{...o.layout?.[t],[e]:{...i,value:String(a),unit:"%"}}}}},w=(e,t)=>{const n=x(e,t);n&&a(n);},S=(e,t)=>{const n=x(e,t);n&&i(n);};if(!o)return null;const C=[{id:qr,label:le("tabLayout")},{id:Br,label:le("tabModelLock")},{id:ho,label:le("tabGemini")},{id:bo,label:"AI Studio"},{id:go,label:"ChatGPT"},{id:uo,label:"Claude"}]; return De("div",{children:[ Re(sy,{title:le("navSiteSettings"),Icon:st}), Re("p",{className:"settings-page-desc",children:le("siteSettingsPageDesc")}), Re(ay,{tabs:C,activeTab:n,onTabChange:r}),n===qr&&De(Ne,{children:[ De(ry,{title:le("layoutSettingsTitle"),children:[ Re(iy,{label:le("enablePageWidth"),description:le("pageWidthDesc"),settingId:"layout-page-width-enabled",checked:p?.enabled??false,onChange:()=>{const t=p||{enabled:false,value:"81",unit:"%"};i({layout:{...o?.layout,pageWidth:{...o?.layout?.pageWidth,[e]:{...t,enabled:!t.enabled}}}});}}), Re(oy,{label:le("pageWidthValueLabel"),settingId:"layout-page-width-value",disabled:!p?.enabled,onDisabledClick:()=>d(u),children:Re(Hf,{value:y,onChange:e=>S("pageWidth",e),onPreviewChange:e=>w("pageWidth",e),onCancelPreview:s,min:so.PAGE_WIDTH.MIN_PERCENT,max:so.PAGE_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(so.PAGE_WIDTH.DEFAULT_PERCENT,10),disabled:!p?.enabled,formatValue:e=>`${e}%`,ariaLabel:le("pageWidthValueLabel")})})]}), De(ry,{title:le("userQueryWidthSettings"),children:[ Re(iy,{label:le("enableUserQueryWidth"),description:le("userQueryWidthDesc"),settingId:"layout-user-query-width-enabled",checked:m?.enabled??false,onChange:()=>{const t=m||{enabled:false,value:"81",unit:"%"};i({layout:{...o?.layout,userQueryWidth:{...o?.layout?.userQueryWidth,[e]:{...t,enabled:!t.enabled}}}});}}), Re(oy,{label:le("userQueryWidthValueLabel"),settingId:"layout-user-query-width-value",disabled:!m?.enabled,onDisabledClick:()=>d(h),children:Re(Hf,{value:v,onChange:e=>S("userQueryWidth",e),onPreviewChange:e=>w("userQueryWidth",e),onCancelPreview:s,min:so.USER_QUERY_WIDTH.MIN_PERCENT,max:so.USER_QUERY_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(so.USER_QUERY_WIDTH.DEFAULT_PERCENT,10),disabled:!m?.enabled,formatValue:e=>`${e}%`,ariaLabel:le("userQueryWidthValueLabel")})})]}), De(ry,{title:le("zenModeTitle"),children:[ Re(iy,{label:le("zenModeLabel"),description:le("zenModeDesc"),settingId:"layout-zen-mode-enabled",checked:f.enabled,onChange:()=>{const t=!f.enabled,n={...o.layout,zenMode:{...o.layout?.zenMode,[e]:{...f,enabled:t}}};t&&(n.cleanMode={...o.layout?.cleanMode,[e]:{enabled:true}}),i({layout:n});}}), Re(iy,{label:le("zenModeExitButtonVisibleLabel"),description:le("zenModeExitButtonVisibleDesc"),settingId:"layout-zen-mode-exit-button-visible",checked:f.showExitButton??true,onChange:()=>{i({layout:{...o.layout,zenMode:{...o.layout?.zenMode,[e]:{...f,showExitButton:!(f.showExitButton??1)}}}});}})]}), Re(ry,{title:le("cleanModeTitle"),children:Re(iy,{label:le("cleanModeLabel"),description:le("cleanModeDesc"),settingId:"layout-clean-mode-enabled",checked:o.layout?.cleanMode?.[e]?.enabled??true,onChange:()=>{const t=o.layout?.cleanMode?.[e]||{enabled:true};i({layout:{...o.layout,cleanMode:{...o.layout?.cleanMode,[e]:{...t,enabled:!t.enabled}}}});}})})]}),n===Br&&De(ry,{title:le("modelLockTitle"),description:le("modelLockDesc"),children:[ Re(Lv,{label:"Gemini",siteKey:"gemini",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini"}), Re(Lv,{label:"Gemini Enterprise",siteKey:"gemini-enterprise",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini-enterprise"}), Re(Nv,{settings:o,setSettings:i,onDisabledClick:()=>d(g),settingId:"model-lock-aistudio"}), Re(Lv,{label:"ChatGPT",siteKey:"chatgpt",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-chatgpt"}), Re(Lv,{label:"Claude",siteKey:"claude",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-claude"}), Re(Lv,{label:"Grok",siteKey:"grok",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-grok"}), Re(Lv,{label:"Kimi",siteKey:"kimi",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-kimi"}), Re(Lv,{label:"Qianwen",siteKey:"qianwen",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qianwen"}), Re(Lv,{label:"Qwen Studio",siteKey:"qwenai",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qwenai"}), Re(Lv,{label:"Yuanbao",siteKey:"yuanbao",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-yuanbao"}), Re(Lv,{label:"ima",siteKey:"ima",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-ima"}), Re(Lv,{label:"Z.ai",siteKey:"zai",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-zai"})]}),"gemini"===n&&De(ry,{title:le("geminiSettingsTab"),description:le("contentProcessingDesc"),children:[ Re(iy,{label:le("markdownFixLabel"),description:le("markdownFixDesc"),settingId:"gemini-markdown-fix",checked:o.content?.markdownFix??false,onChange:()=>l("content","markdownFix",!o.content?.markdownFix)}), Re(iy,{label:le("watermarkRemovalLabel"),description:le("watermarkRemovalDesc"),settingId:"gemini-watermark-removal",checked:o.content?.watermarkRemoval??false,onChange:async()=>{const e=o.content?.watermarkRemoval;if(e)l("content","watermarkRemoval",false);else {if(!$i.hasCapability("permissions"))return void l("content","watermarkRemoval",true);if(void 0!==chrome.permissions){await chrome.permissions.request({origins:[""]})&&l("content","watermarkRemoval",true);}else {const e=await md({type:ud,origins:[""]});e.success&&e.hasPermission?l("content","watermarkRemoval",true):(await md({type:hd,permType:"allUrls"}),Pi(le("permissionRequestToast"),3e3));}}}}), De("div",{className:"setting-subsection",style:{marginTop:"24px",paddingTop:"16px",borderTop:"1px solid var(--gh-border-color)"},children:[ Re("h3",{style:{fontSize:"14px",fontWeight:600,marginBottom:"12px"},children:"Gemini Enterprise"}), Re(iy,{label:le("policyRetryLabel"),description:le("policyRetryDesc"),settingId:"gemini-policy-retry",checked:o.geminiEnterprise?.policyRetry?.enabled??false,onChange:()=>{const e=o.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3};i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...e,enabled:!e.enabled}}});}}),o.geminiEnterprise?.policyRetry?.enabled&&Re(oy,{label:le("maxRetriesLabel"),settingId:"gemini-policy-max-retries",children:De("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Re(Ff,{value:o.geminiEnterprise?.policyRetry?.maxRetries??3,onChange:e=>i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...o.geminiEnterprise?.policyRetry,maxRetries:e}}}),min:1,max:10,defaultValue:3,style:{width:"60px"}}), Re("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("retryCountSuffix")})]})})]})]}),n===bo&&De(ry,{title:le("aistudioSettingsTitle"),description:le("aistudioSettingsDesc"),children:[ Re(iy,{label:le("aistudioCollapseNavbar"),description:le("aistudioCollapseNavbarDesc"),settingId:"aistudio-collapse-navbar",checked:o.aistudio?.collapseNavbar??false,onChange:()=>i({aistudio:{...o.aistudio,collapseNavbar:!o.aistudio?.collapseNavbar}})}), Re(iy,{label:le("aistudioCollapseRunSettings"),description:le("aistudioCollapseRunSettingsDesc"),settingId:"aistudio-collapse-run-settings",checked:o.aistudio?.collapseRunSettings??false,onChange:()=>i({aistudio:{...o.aistudio,collapseRunSettings:!o.aistudio?.collapseRunSettings}})}), Re(iy,{label:le("aistudioCollapseTools"),description:le("aistudioCollapseToolsDesc"),settingId:"aistudio-collapse-tools",checked:o.aistudio?.collapseTools??false,onChange:()=>i({aistudio:{...o.aistudio,collapseTools:!o.aistudio?.collapseTools}})}), Re(iy,{label:le("aistudioCollapseAdvanced"),description:le("aistudioCollapseAdvancedDesc"),settingId:"aistudio-collapse-advanced",checked:o.aistudio?.collapseAdvanced??false,onChange:()=>i({aistudio:{...o.aistudio,collapseAdvanced:!o.aistudio?.collapseAdvanced}})}), Re(iy,{label:le("aistudioEnableSearch"),description:le("aistudioEnableSearchDesc"),settingId:"aistudio-enable-search",checked:o.aistudio?.enableSearch??true,onChange:()=>i({aistudio:{...o.aistudio,enableSearch:!o.aistudio?.enableSearch}})}), Re(iy,{label:le("aistudioRemoveWatermark"),description:le("aistudioRemoveWatermarkDesc"),settingId:"aistudio-remove-watermark",checked:o.aistudio?.removeWatermark??false,onChange:()=>{i({aistudio:{...o.aistudio,removeWatermark:!o.aistudio?.removeWatermark}}),Pi(le("aistudioReloadHint"),3e3);}}), Re(iy,{label:le("aistudioMarkdownFixLabel"),description:le("aistudioMarkdownFixDesc"),settingId:"aistudio-markdown-fix",checked:o.aistudio?.markdownFix??false,onChange:()=>i({aistudio:{...o.aistudio,markdownFix:!o.aistudio?.markdownFix}})})]}),"claude"===n&&Re(Mv,{siteId:e}),n===go&&Re(ry,{title:le("chatgptSettingsTitle"),description:le("chatgptSettingsDesc"),children:Re(iy,{label:le("chatgptMarkdownFixLabel"),description:le("chatgptMarkdownFixDesc"),settingId:"chatgpt-markdown-fix",checked:o.chatgpt?.markdownFix??false,onChange:()=>i({chatgpt:{...o.chatgpt,markdownFix:!o.chatgpt?.markdownFix}})})})]})},Dv=(e,t)=>{const n=le(e);return n===e?t:n},Pv=[{id:fr,Icon:it,labelKey:"navGeneral",label:"基本设置"},{id:br,Icon:at,labelKey:"navAppearance",label:"外观主题"},{id:yr,Icon:lt,labelKey:"navFeatures",label:"功能模块"},{id:vr,Icon:st,labelKey:"navSiteSettings",label:"站点配置"},{id:xr,Icon:Qt,labelKey:"navGlobalSearch",label:"全局搜索"},{id:wr,Icon:Mt,labelKey:"navShortcuts",label:"快捷键位"},{id:Sr,Icon:({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("svg",{viewBox:"0 0 1027 1024",width:e,height:e,className:n,style:{display:"block",...r},children:Re("path",{d:"M983.716 651.25l42.5-42.5L847.466 431.25 668.716 608.75l42.5 42.5 106.25-106.25 0 373.75L876.216 918.75 876.216 545 983.716 651.25zM533.716 793.75 533.716 421.25l-60 0 0 373.75-106.25-106.25L326.216 730l177.5 177.5 178.75-178.75L639.966 687.5 533.716 793.75zM297.466 835 238.716 835c-98.75 0-178.75-80-178.75-178.75S139.966 477.5 238.716 477.5c1.25 0 2.5 0 2.5 0l28.75 0c1.25 0 11.25 1.25 21.25-10 10-11.25 6.25-21.25 6.25-33.75 0-148.75 121.25-270 268.75-270 70 0 133.75 26.25 181.25 70 5 5 3.75 5 10 10 6.25 8.75 15 13.75 26.25 13.75 16.25 0 30-13.75 30-30 0-10-5-18.75-12.5-26.25-5-5-3.75-3.75-10-8.75-58.75-56.25-137.5-90-225-90-176.25 0-320 138.75-328.75 312.5-131.25 0-237.5 106.25-237.5 237.5s106.25 237.5 237.5 237.5l57.5 0c16.25 0 30-13.75 30-30C326.216 847.5 313.716 835 297.466 835L297.466 835z",fill:t})}),labelKey:"navBackup",label:"数据管理"},{id:Cr,Icon:ct,labelKey:"navPermissions",label:"权限管理"},{id:kr,Icon:dt,labelKey:"navAbout",label:"关于"}],qv=({isOpen:e,onClose:t,siteId:n})=>{const[r,o]=_(fr),[i,a]=_(void 0),[s,l]=_(null),[c,d]=_(false),{settings:u}=Mi(),h=Ii(),g=$(null),p=$(null),m=$(void 0),f=$(null);if(L(()=>{h&&u?.language&&ae(u.language);},[h,u?.language]),L(()=>{g.current&&(g.current.scrollTop=0);},[r]),L(()=>{if(!e)return;const n=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[e,t]),L(()=>{const e=e=>{const t=(e=>{const t=zr(e.settingId),n=Fr(t);return {page:e.page??n?.page,subTab:e.subTab??(e.page&&e.page!==n?.page?void 0:n?.subTab),settingId:t}})(e.detail||{});t.page&&Pv.some(e=>e.id===t.page)&&o(t.page),a(t.subTab),t.settingId?l({settingId:t.settingId,token:Date.now()}):l(null);};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[]),L(()=>{if(!e||!s?.settingId)return;let t,n,r=false;const o=`[data-setting-id="${"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(s.settingId):JSON.stringify(s.settingId).slice(1,-1)}"]`,i=e=>{if(r)return;const n=g.current?.querySelector(o);return n?(void 0!==m.current&&(window.clearTimeout(m.current),m.current=void 0),f.current&&f.current!==n&&f.current.classList.remove("setting-locate-highlight"),n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.remove("setting-locate-highlight"),n.offsetWidth,n.classList.add("setting-locate-highlight"),f.current=n,m.current=window.setTimeout(()=>{n.classList.remove("setting-locate-highlight"),f.current===n&&(f.current=null),m.current=void 0;},2200),void l(null)):e>=12?(console.warn(`[Ophel] Failed to locate setting: ${s.settingId}`),void l(null)):void(t=window.setTimeout(()=>i(e+1),100))};return n=window.requestAnimationFrame(()=>i(0)),()=>{r=true,void 0!==n&&window.cancelAnimationFrame(n),void 0!==t&&window.clearTimeout(t);}},[e,r,i,s]),L(()=>()=>{ void 0!==m.current&&window.clearTimeout(m.current),f.current&&(f.current.classList.remove("setting-locate-highlight"),f.current=null);},[]),L(()=>{if(e){const e=p.current;if(!e)return;return as(e)}},[e,n]),L(()=>e?(document.body.style.overflow="hidden",()=>{document.body.style.overflow="";}):(document.body.style.overflow="",()=>{document.body.style.overflow="";}),[e]),!e)return null; return Re("div",{className:"settings-modal-overlay",...ns,onClick:t,children:De("div",{ref:p,className:"settings-modal-container "+(c?"maximized":""),onClick:e=>e.stopPropagation(),children:[ De("div",{className:"settings-modal-actions",children:[ Re(od,{content:le(c?"restore":"maximize"),children:Re("button",{className:"settings-modal-action-btn",onClick:()=>d(!c),children:Re(c?Tt:kt,{size:16})})}), Re(od,{content:le("close"),children:Re("button",{className:"settings-modal-action-btn close",onClick:t,children:Re($e,{size:16})})})]}), De("aside",{className:"settings-sidebar",children:[ Re("div",{className:"settings-sidebar-header",children:De("div",{className:"settings-sidebar-logo",children:[ Re("img",{src:Pf,alt:Rf}), Re("span",{children:Rf})]})}), De("nav",{className:"settings-sidebar-nav",children:[Pv.filter(e=>!(!$i.hasCapability("permissions")&&e.id===Cr)).map(e=>De("button",{className:"settings-nav-item "+(r===e.id?"active":""),onClick:()=>{o(e.id),a(void 0),l(null);},children:[ Re("span",{className:"settings-nav-item-icon",children:Re(e.Icon,{size:22})}), Re("span",{children:Dv(e.labelKey,e.label)})]},e.id)), Re(Yb,{})]}), Re(ey,{siteId:n})]}), Re("main",{className:"settings-content",ref:g,children:(()=>{if(!u||!h) return Re("div",{style:{padding:40,textAlign:"center"},children:le("loading")});switch(r){case fr: return Re(yv,{siteId:n,initialTab:i});case vr: return Re(Rv,{siteId:n,initialTab:i});case br: return Re(Iy,{siteId:n,initialTab:i});case yr: return Re(pv,{siteId:n,initialTab:i});case xr: return Re(fv,{siteId:n});case wr: return Re(kv,{siteId:n});case Cr: return Re(Sv,{siteId:n});case Sr: return Re(Qy,{siteId:n,onNavigate:o});case kr: return Re(ly,{});default: return Re(yv,{siteId:n,initialTab:i})}})()})]})})},Bv=e=>{const{isOpen:t,onClose:n,inputRef:r,resultsRef:o,activeOptionId:a,inputValue:s,inputPlaceholder:l,onInputChange:c,hotkeyLabel:d,fuzzySearchToggleLabel:u,fuzzySearchToggleAriaLabel:h,isFuzzySearchEnabled:g,onToggleFuzzySearch:p,syntaxHelpTriggerRef:m,syntaxHelpPopoverRef:f,showSyntaxHelp:b,onToggleSyntaxHelp:y,syntaxHelpTriggerAriaLabel:v,syntaxHelpTitle:x,syntaxHelpDescription:w,syntaxHelpItems:S,onApplySyntaxHelpItem:C,activeFilterChips:k,hasOverflowFilterChips:T,overflowFilterChipText:E,filterChipRemoveTitle:A,clearFiltersLabel:M,onRemoveFilterChip:I,onClearAllFilterChips:L,shouldShowSyntaxSuggestions:N,syntaxSuggestions:R,activeSyntaxSuggestionIndex:D,onHoverSyntaxSuggestion:P,onApplySyntaxSuggestion:q,syntaxDiagnostics:B,resolveSyntaxDiagnosticTitle:$,showShortcutNudge:_,shortcutNudgeMessage:O,closeLabel:z,dismissShortcutNudgeLabel:F,onHideShortcutNudge:U,onDismissShortcutNudgeForever:H,categoriesLabel:W,categories:j,activeCategoryId:G,onSelectCategory:V,activeContext:Q,listboxId:K,listboxLabel:Z,onResultsWheel:Y,visibleResults:X,groupedResults:J,getGroupLabel:ee,allCategoryItemLimit:te,isAllCategory:ne,emptyText:re,emptyGuideTitle:oe,emptyGuideDescription:ie,emptyGuideExamples:ae,renderSearchResultItem:se,resolveVisibleResultIndex:le,collapseLabel:ce,moreLabel:de,onToggleCategoryGroup:ue,footerTips:he,promptPreview:ge}=e,pe=i.useRef(null);return i.useEffect(()=>{if(!t)return;const e=pe.current;return e?as(e):void 0},[t]),t?De("div",{className:"settings-search-overlay gh-interactive",onClick:n,children:[ De("div",{ref:pe,className:"settings-search-modal",onClick:e=>e.stopPropagation(),children:[ De("div",{className:"settings-search-input-wrap",children:[ Re(Qt,{size:16}), Re("button",{type:"button",className:"settings-search-fuzzy-toggle "+(g?"active":""),"aria-pressed":g,"aria-label":h,onClick:p,children:u}), Re("input",{ref:r,className:"settings-search-input",role:"combobox","aria-autocomplete":"list","aria-expanded":true,"aria-haspopup":"listbox","aria-controls":K,"aria-activedescendant":a,value:s,onChange:e=>{c(e.target.value);},placeholder:l}), De("span",{className:"settings-search-hotkey",children:["⌨ ",d]}), De("div",{className:"settings-search-help",children:[ Re("button",{ref:m,type:"button",className:"settings-search-help-trigger "+(b?"active":""),"aria-expanded":b,"aria-label":v,onClick:y,children:"?"}),b?De("div",{ref:f,className:"settings-search-help-popover",role:"dialog","aria-label":x,children:[ Re("div",{className:"settings-search-help-title",children:x}), Re("div",{className:"settings-search-help-tip",children:w}), Re("div",{className:"settings-search-help-items",children:S.map(e=>De("button",{type:"button",className:"settings-search-help-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),C(e);},children:[ Re("span",{className:"settings-search-help-token",children:e.token}), Re("span",{className:"settings-search-help-desc",children:e.description})]},e.id))})]}):null]})]}),k.length>0?De("div",{className:"settings-search-filter-chips","aria-label":"active search filters",children:[k.map(e=>De("button",{type:"button",className:"settings-search-filter-chip",onClick:()=>I(e.id),title:A,children:[ Re("span",{className:"settings-search-filter-chip-label",children:e.label}), Re("span",{className:"settings-search-filter-chip-close","aria-hidden":true,children:"×"})]},e.id)),T?Re("span",{className:"settings-search-filter-chip-overflow",children:E}):null, Re("button",{type:"button",className:"settings-search-filter-chip-clear-all",onClick:L,children:M})]}):null,N?Re("div",{className:"settings-search-syntax-suggestions",role:"listbox",children:R.map((e,t)=>De("button",{type:"button",role:"option","aria-selected":D===t,className:"settings-search-syntax-suggestion "+(D===t?"active":""),onMouseEnter:()=>P(t),onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),q(e);},children:[ Re("span",{className:"settings-search-syntax-suggestion-token",children:e.label}), Re("span",{className:"settings-search-syntax-suggestion-desc",children:e.description})]},e.id))}):null,B.length>0?Re("div",{className:"settings-search-syntax-diagnostics",role:"status","aria-live":"polite",children:B.map(e=>De("div",{className:"settings-search-syntax-diagnostic",children:[ Re("span",{className:"settings-search-syntax-diagnostic-title",children:$(e.code)}), De("span",{className:"settings-search-syntax-diagnostic-detail",children:[e.operator,e.value?`:${e.value}`:"",e.suggestion?` → ${e.suggestion}:`:""]})]},e.id))}):null,_&&O?De("div",{className:"settings-search-shortcut-nudge",role:"status","aria-live":"polite",children:[ Re("span",{className:"settings-search-shortcut-nudge-text",children:O}), Re("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:U,children:z}), Re("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:H,children:F})]}):null,j.length>0?Re("div",{className:"settings-search-categories",role:"tablist","aria-label":W,children:j.map(e=>De("button",{type:"button",role:"tab","aria-selected":G===e.id,className:"settings-search-category "+(G===e.id?"active":""),onClick:()=>V(e.id),children:[ Re("span",{children:e.label}), Re("span",{className:"settings-search-category-count",children:null==e.count?"-":e.count})]},e.id))}):null,Q?De("div",{className:"settings-search-context-bar",children:[ Re("span",{className:"settings-search-context-label",children:Q.label}), Re("span",{className:"settings-search-context-meta",children:Q.meta})]}):null, Re("div",{id:K,className:"settings-search-results",role:"listbox","aria-label":Z,ref:o,onWheel:Y,children:0===X.length?De("div",{className:"settings-search-empty",children:[ Re("div",{children:re}), Re("div",{className:"settings-search-empty-guide-title",children:oe}), Re("div",{className:"settings-search-empty-guide-desc",children:ie}), Re("div",{className:"settings-search-empty-guide-examples",children:ae.map(e=>Re("button",{type:"button",className:"settings-search-empty-guide-example",onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),e.onClick();},children:e.token},e.id))})]}):ne?J.map(e=>De("section",{className:"settings-search-group",children:[ De("div",{className:"settings-search-group-title",children:[ Re("span",{children:ee(e.category)}),e.totalCount>te?De("span",{className:"settings-search-group-count",children:[e.items.length,"/",e.totalCount]}):null]}),e.items.map((e,t)=>se(e,le(e,t))),e.hasMore||e.isExpanded?Re("button",{type:"button",className:"settings-search-group-more",onClick:()=>ue(e.category),children:e.isExpanded?ce:`${de} (+${e.remainingCount})`}):null]},e.category)):X.map((e,t)=>se(e,t))}), Re("div",{className:"settings-search-footer",children:he})]}),ge]}):null},$v=new Map,_v=(e,t,n)=>{const r=((e,t)=>{if(!e||0===t.length)return [];const n=e.toLowerCase(),r=[];if(t.forEach(e=>{if(!e)return;let t=0;for(;te.start!==t.start?e.start-t.start:e.end-t.end);const o=[];return r.forEach(e=>{const t=o[o.length-1];!t||e.start>t.end?o.push({...e}):e.end>t.end&&(t.end=e.end);}),o})(e,t),o=((e,t)=>{if(!e||!t||0===t.length)return [];const n=Array.from(new Set(t.map(e=>Number(e)).filter(t=>Number.isInteger(t)&&t>=0&&te-t);if(0===n.length)return [];const r=[];let o=n[0],i=n[0];for(let a=1;a{for(let t=e.start;t{for(let t=e.start;te.text.length>0)},Ov=i.memo(({item:e,index:t,optionIdPrefix:n,isActive:r,highlightTokens:o,outlineRoleLabels:a,matchReasonLabels:s,onMouseMove:l,onMouseEnter:c,onMouseLeave:d,onClick:u})=>{const h=(e,t="default",n)=>{const r=((e,t,n)=>{if(!e)return [];const r=((e,t,n)=>`${e}\0${t.join("\0")}\0${n?n.join(","):""}`)(e,t,n),o=$v.get(r);if(o)return o;const i=_v(e,t,n);if($v.size>=500){const e=$v.keys().next().value;void 0!==e&&$v.delete(e);}return $v.set(r,i),i})(e,o,n);return r.map((e,n)=>{if("none"===e.matchType) return Re(i.Fragment,{children:e.text},`plain-${n}-${e.text.length}`);const r=["settings-search-highlight","tag"===t?"settings-search-highlight-tag":"","code"===t?"settings-search-highlight-code":"","fuzzy"===e.matchType?"settings-search-highlight-fuzzy":""].filter(Boolean).join(" "); return Re("mark",{className:r,children:e.text},`highlight-${n}-${e.text.length}`)})},g="outline"===e.category&&Boolean(e.outlineTarget),p="conversations"===e.category,m="prompts"===e.category,f=Boolean(e.tipId),b=g&&Boolean(e.outlineTarget?.isUserQuery),y=b?a.query:a.reply,v=Boolean(e.code)&&!g,x=e.fuzzyMatch?.field,w="title"===x?e.fuzzyMatch?.indexes:void 0,S="breadcrumb"===x?e.fuzzyMatch?.indexes:void 0,C="snippet"===x?e.fuzzyMatch?.indexes:void 0,k="code"===x?e.fuzzyMatch?.indexes:void 0,T="prompts"===e.category&&e.matchReasons?.includes("content")?`${s.content}: `:"",E=e.matchReasons&&e.matchReasons.length>0?e.matchReasons.map(e=>({reason:e,label:s[e]})):[]; return De("div",{id:`${n}-${t}`,role:"option","aria-selected":r,tabIndex:-1,"data-global-search-index":t,"data-global-search-item-id":e.id,className:`settings-search-item ${r?"active":""} ${f?"tip-item":""} ${g?b?"outline-item outline-query":"outline-item outline-reply":""} ${p?"conversation-item":""}`.trim(),onMouseMove:l,onMouseEnter:e=>{m&&c(e);},onMouseLeave:()=>{m&&d();},onClick:u,children:[ Re("div",{className:"settings-search-item-title",title:e.title,children:f?De("div",{className:"gs-tip-item-head",children:[ Re("span",{className:"gs-tip-icon","aria-hidden":"true",children:"💡"}), Re("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})]}):g?De("div",{className:"settings-search-outline-head",children:[ Re("span",{className:"settings-search-outline-role "+(b?"query":"reply"),title:y,children:y}),e.code?Re("span",{className:"settings-search-outline-code",title:e.code,children:h(e.code,"code",k)}):null, Re("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})]}):Re("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})}),e.snippet?De("div",{className:"settings-search-item-snippet",title:`${T}${e.snippet}`,children:[T?Re("span",{className:"settings-search-item-snippet-prefix",children:T}):null,h(e.snippet,"default",C)]}):null, De("div",{className:("settings-search-item-meta "+(v?"":"no-code")).trim(),children:[ De("div",{className:"settings-search-item-meta-left",children:[ Re("span",{className:"settings-search-item-breadcrumb",title:e.breadcrumb,children:h(e.breadcrumb,"default",S)}),"conversations"===e.category&&e.tagBadges&&e.tagBadges.length>0?Re("div",{className:"settings-search-tag-list",children:e.tagBadges.map(e=>Re("span",{className:"settings-search-tag",style:{backgroundColor:e.color},title:e.name,children:h(e.name,"tag")},e.id))}):null,E.length>0?Re("div",{className:"settings-search-match-reason-list",children:E.map(e=>Re("span",{className:"settings-search-match-reason-badge",children:e.label},e.reason))}):null]}),v?Re("code",{title:e.code,children:h(e.code,"code",k)}):null]})]})}),zv=["type","folder","tag","is","level","date"],Fv=["outline","conversations","prompts","settings"],Uv=["pinned","unpinned"],Hv=["0","1","2","3","4","5","6"],Wv=["7d","30d"],jv=e=>e.trim().toLowerCase(),Gv=e=>jv(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0),Vv=e=>e?e.replace(/^"|"$/g,"").replace(/\\([\\"\s:])/g,"$1").trim():"",Qv=e=>{const t=e.trim().toLowerCase().match(/^(\d{1,3})d$/);if(!t)return null;const n=Number(t[1]);return !Number.isFinite(n)||n<=0?null:n},Kv=(e,t)=>{const n=e.normalizedValue;return "type"===e.key?t.some(e=>"type"===e.key&&e.normalizedValue!==n):"is"===e.key?t.some(e=>"is"===e.key&&e.normalizedValue!==n):"level"===e.key?t.some(e=>"level"===e.key&&e.normalizedValue!==n):"date"===e.key&&t.some(e=>"date"===e.key&&e.normalizedValue!==n)},Zv=(e,t)=>!!t&&("type"===e?Fv.includes(t):"is"===e?Uv.includes(t):"level"===e?Hv.includes(t):"date"!==e||null!==Qv(t)),Yv=e=>"type"===e?"outline | conversations | prompts | settings":"is"===e?"pinned | unpinned":"level"===e?"0 ~ 6":"date"===e?"Nd (e.g. 7d, 30d)":void 0,Xv=(e,t,n)=>`${e}:${t}:${n}`,Jv=e=>{const t=e.trim().toLowerCase();if(!t)return null;const n=zv.find(e=>e.startsWith(t));if(n)return n;const r=zv.find(e=>t.startsWith(e));return r||null},ex=e=>{const t=e.match(/(^|\s)([^\s]*)$/);if(!t)return null;const n=t[2]||"",r=e.length;return {token:n,start:r-n.length,end:r}},tx=globalThis.fuzzysort,nx=tx&&"function"==typeof tx.single?tx:{single:()=>null,go:()=>[],prepare:e=>e,cleanup:()=>{}},rx=[{id:"passthrough"},{id:"panel-mode-toggle",highlightTarget:"header-title",shortcutIds:["togglePanelMode"]},{id:"shortcuts",highlightTarget:"shortcuts-btn",shortcutIds:["showShortcuts"]},{id:"global-search",highlightTarget:"search-btn",shortcutIds:["openGlobalSearch"]},{id:"copy-reply",shortcutIds:["copyLatestReply"]},{id:"prev-next-heading",highlightTarget:"outline-tab",shortcutIds:["prevHeading","nextHeading"]},{id:"export-conv",highlightTarget:"conversations-tab"},{id:"batch-select",highlightTarget:"conversations-tab"},{id:"export-markdown",highlightTarget:"toolbar-btn"},{id:"show-user-query",highlightTarget:"outline-tab"},{id:"notifications",highlightTarget:"settings-btn"}],ox=["outline","conversations","prompts","settings","tips"],ix=Object.entries(Or).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),ax=e=>{if("inbox"===e.id)return (()=>{const e=le("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},sx=({normalizedQuery:e,fields:t})=>{if(!e)return null;let n=null;const r=e.length>=8?2:1;return t.forEach(t=>{if(!t.value)return;const r=nx.single(e,t.value);!r||r.score<.24||(!n||r.score>n.score)&&(n={score:r.score,matchReason:t.matchReason,highlightField:t.highlightField,indexes:Array.from(r.indexes||[]),isTypoFallback:false});}),n||(e.length<4?null:(t.forEach(t=>{if(!t.value)return;var o;((o=t.value)?o.split(/[^a-z0-9\u4e00-\u9fff]+/gi).map(e=>e.trim()).filter(e=>e.length>0):[]).forEach(o=>{if(Math.abs(o.length-e.length)>r)return;const i=((e,t,n)=>{const r=e.length,o=t.length;if(e===t)return 0;if(Math.abs(r-o)>n)return n+1;const i=new Array(o+1).fill(0),a=new Array(o+1),s=new Array(o+1);for(let l=0;l<=o;l+=1)a[l]=l;for(let l=1;l<=r;l+=1){s[0]=l;let r=s[0];for(let n=1;n<=o;n+=1){const o=e[l-1]===t[n-1]?0:1;let c=Math.min(a[n]+1,s[n-1]+1,a[n-1]+o);l>1&&n>1&&e[l-1]===t[n-2]&&e[l-2]===t[n-1]&&(c=Math.min(c,i[n-2]+1)),s[n]=c,cn)return n+1;for(let e=0;e<=o;e+=1)i[e]=a[e],a[e]=s[e];}return a[o]})(e,o,r);if(i>r)return;const a=Math.max(.24,.58-.14*i-.03*Math.abs(o.length-e.length));(!n||a>n.score)&&(n={score:a,matchReason:t.matchReason,highlightField:t.highlightField,indexes:void 0,isTypoFallback:true});});}),n))},lx=({normalizedQuery:e,tokens:t,index:n,fields:r,enableFuzzySearch:o,baseScoreWhenEmpty:i=1e3})=>{const a=r.map(e=>e.value).join(" "),s=t.every(e=>a.includes(e)),l=o&&e?sx({normalizedQuery:e,fields:r}):null;if(!s&&!l)return null;if(!e)return {score:i-n,matchLevel:0,exactHitCount:0,prefixHitCount:0,includesHitCount:0,matchReasons:[]};let c=0,d=0,u=0,h=0,g=0;const p=new Set;r.forEach(n=>{const r=n.value;if(!r)return;let o=0,i=false,a=false;r===e?(c+=n.exact,o=3,u+=1):r.startsWith(e)?(c+=n.prefix,o=2,h+=1):r.includes(e)&&(c+=n.includes,o=1,g+=1),d=Math.max(d,o),o>0&&n.matchReason&&p.add(n.matchReason),t.forEach(e=>{r.startsWith(e)&&(c+=n.tokenPrefix,i=true),r.includes(e)&&(c+=n.tokenIncludes,a=true);}),0===o?i?(d=Math.max(d,2),h+=1,n.matchReason&&p.add(n.matchReason)):a&&(d=Math.max(d,1),g+=1,n.matchReason&&p.add(n.matchReason)):d=Math.max(d,o);});const m=Boolean(l&&0===d);if(m&&l){const e=Math.round(64*l.score);c+=e+16,p.add("fuzzy"),l.matchReason&&p.add(l.matchReason);}return 0!==d||l?{score:c,matchLevel:d,exactHitCount:u,prefixHitCount:h,includesHitCount:g,matchReasons:Array.from(p),fuzzyMatch:m?{field:l?.highlightField,indexes:l?.indexes,isTypoFallback:l?.isTypoFallback}:void 0}:null},cx=(e,t)=>{if(t.scoreMeta.matchLevel!==e.scoreMeta.matchLevel)return t.scoreMeta.matchLevel-e.scoreMeta.matchLevel;if(t.scoreMeta.exactHitCount!==e.scoreMeta.exactHitCount)return t.scoreMeta.exactHitCount-e.scoreMeta.exactHitCount;if(t.scoreMeta.prefixHitCount!==e.scoreMeta.prefixHitCount)return t.scoreMeta.prefixHitCount-e.scoreMeta.prefixHitCount;if(t.scoreMeta.includesHitCount!==e.scoreMeta.includesHitCount)return t.scoreMeta.includesHitCount-e.scoreMeta.includesHitCount;if(t.scoreMeta.score!==e.scoreMeta.score)return t.scoreMeta.score-e.scoreMeta.score;const n=e.recency||0,r=t.recency||0;return r!==n?r-n:e.index-t.index},dx=({activeGlobalSearchPlainQuery:e,enableFuzzySearch:t,activeGlobalSearchSyntaxFilters:n,settingsSearchResults:r,resolveSettingSearchTitle:o,getSettingsBreadcrumb:i,conversationManager:a,conversationsSnapshot:s,foldersSnapshot:l,tagsSnapshot:c,promptsSnapshot:d,outlineManager:u,outlineSearchVersion:h,getLocalizedText:g,resolveShortcutLabel:p,passThroughModifierLabel:m,activeGlobalSearchCategory:f,expandedGlobalSearchCategories:b,allCategoryItemLimit:y})=>{const v=e.trimStart(),x=v.startsWith("tip:")||"tips"===f,w=q(()=>{if(!x)return [];const e=v.startsWith("tip:")?v.slice(4).trim().toLowerCase():v.trim().toLowerCase(),t=g({key:"featureTipsCategory",fallback:"Feature Tips"}),n=g({key:"featureTipShortcutNotConfigured",fallback:"Shortcut not configured"}),r=(e,t,r)=>le(`featureTip-${e}-${t}`,{modifier:m,shortcut:r.length>0?r.join(" / "):n});return rx.map(e=>{const n=e.shortcutIds?.map(e=>p(e)).filter(e=>Boolean(e))??[],o=r(e.id,"title",n),i=r(e.id,"desc",n),a=r(e.id,"path",n),s=n.join(" / "),l=s?`${i} [${s}]`:i;return {id:`tips:${e.id}`,title:o,breadcrumb:`${t} / ${a}`,snippet:l,category:"tips",tipId:e.id,tipHighlightTarget:e.highlightTarget,tipActionText:a,tipShortcutIds:e.shortcutIds}}).filter(t=>!e||[t.title,t.snippet,t.tipActionText].filter(e=>Boolean(e)).some(t=>t.toLowerCase().includes(e)))},[f,g,x,m,p,v]),S=q(()=>{if(x)return [];const n=jv(e),a=Gv(e);return r.map((e,r)=>{const s=o(e),l=jv(s),c=jv((e.keywords||[]).join(" ")),d=jv(e.settingId),u=jv((ix[e.settingId]||[]).join(" ")),h=lx({normalizedQuery:n,tokens:a,index:r,enableFuzzySearch:t,fields:[{value:l,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:c,exact:0,prefix:0,includes:68,tokenPrefix:0,tokenIncludes:8,matchReason:"keyword"},{value:d,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"id",highlightField:"code"},{value:u,exact:0,prefix:0,includes:44,tokenPrefix:0,tokenIncludes:6,matchReason:"alias"}]});return null===h?null:{item:{id:`settings:${e.settingId}`,title:s,breadcrumb:i(e.settingId),code:e.settingId,category:"settings",settingId:e.settingId,matchReasons:h.matchReasons,fuzzyMatch:h.fuzzyMatch},scoreMeta:h,index:r}}).filter(e=>Boolean(e)).sort(cx).map(({item:e})=>e)},[e,t,i,x,o,r]),C=q(()=>{if(!a||x)return [];const n=a.getConversations(),r=a.getFolders(),o=a.getTags(),i=new Map(r.map(e=>[e.id,e])),s=new Map(o.map(e=>[e.id,e])),l=jv(e),c=Gv(e),d=g({key:"untitledConversation",fallback:"Untitled conversation"});return n.map((e,n)=>{const r=e.title?.trim()||d,o=i.get(e.folderId),a=o?`${o.icon?`${o.icon} `:""}${ax(o)}`.trim():e.folderId,u=(e.tagIds||[]).map(e=>{const t=s.get(e);return t?{id:t.id,name:t.name,color:t.color}:null}).filter(e=>Boolean(e)),h=jv(r),g=jv(a),p=jv(u.map(e=>e.name).join(" ")),m=lx({normalizedQuery:l,tokens:c,index:n,enableFuzzySearch:t,fields:[{value:h,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:72,tokenPrefix:0,tokenIncludes:8,matchReason:"folder",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:64,tokenPrefix:0,tokenIncludes:8,matchReason:"tag"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)};return {item:{id:`conversations:${e.id}`,title:r,breadcrumb:a,category:"conversations",conversationId:e.id,conversationUrl:e.url,tagBadges:u,folderName:a,tagNames:u.map(e=>e.name),isPinned:Boolean(e.pinned),searchTimestamp:e.updatedAt||0,matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch},scoreMeta:f,index:n,recency:e.updatedAt||0}}).filter(e=>Boolean(e)).sort(cx).map(({item:e})=>e)},[a,s,l,c,g,e,t,x]),k=q(()=>{if(x)return [];const n=jv(e),r=Gv(e),o=g({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),i=g({key:"uncategorized",fallback:"Uncategorized"}),a=d.map((e,a)=>{const s=e.title?.trim()||e.content?.trim().split("\n")[0]||`${o} #${a+1}`,l=e.content?.trim()||"",c=e.category?.trim()||i,d=`${o} / ${c}`,u=jv(s),h=jv(l),g=jv(c),p=jv(e.id),m=lx({normalizedQuery:n,tokens:r,index:a,enableFuzzySearch:t,fields:[{value:u,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:70,tokenPrefix:0,tokenIncludes:8,matchReason:"category",highlightField:"breadcrumb"},{value:h,exact:0,prefix:0,includes:60,tokenPrefix:0,tokenIncludes:6,matchReason:"content",highlightField:"snippet"},{value:p,exact:0,prefix:0,includes:20,tokenPrefix:0,tokenIncludes:4,matchReason:"id",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)},b=f.matchReasons.includes("content")?(({content:e,normalizedQuery:t,tokens:n,maxLength:r=84})=>{const o=e.replace(/\s+/g," ").trim();if(!o)return "";const i=Array.from(new Set([t,...n])).filter(Boolean),a=o.toLowerCase();let s=-1;if(i.forEach(e=>{const t=a.indexOf(e);-1!==t&&(-1===s||tr?`${o.slice(0,r).trim()}…`:o;let l=Math.max(0,s-Math.floor(.25*r));const c=Math.min(o.length,l+r);return c>=o.length&&(l=Math.max(0,o.length-r)),`${l>0?"…":""}${o.slice(l,c).trim()}${cBoolean(e)).sort(cx);return a.map(({item:e})=>e)},[e,t,g,x,d]),T=q(()=>{if(!u||x)return [];const n=(e=>{const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&n(e.children);});};return n(e),t})(u.getTree()),r=jv(e),o=Gv(e),i=g({key:"globalSearchCategoryOutline",fallback:"Outline"}),a=g({key:"outlineUserQueryRoleLabel",fallback:"User queries"}),s=g({key:"globalSearchOutlineReplies",fallback:"Replies"});return n.map((e,n)=>{const l=e.text?.trim();if(!l)return null;const c=e.isUserQuery?`Q${e.queryIndex??n+1}`:`H${e.level}`,d=e.isUserQuery?a:s,u=e.isUserQuery?`${i} / ${d}`:`${i} / ${d} / H${e.level}`,h=jv(l),g=jv(e.isUserQuery?d:`${d} h${e.level}`),p=jv(c),m=lx({normalizedQuery:r,tokens:o,index:n,enableFuzzySearch:t,fields:[{value:h,exact:200,prefix:120,includes:90,tokenPrefix:16,tokenIncludes:10,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"type",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:36,tokenPrefix:0,tokenIncludes:4,matchReason:"code",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.isBookmarked?4:0)};return {item:{id:`outline:${e.index}`,title:l,breadcrumb:u,code:c,category:"outline",matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch,outlineTarget:{index:e.index,level:e.level,text:l,isUserQuery:Boolean(e.isUserQuery),id:e.id,navigationId:e.navigationId,queryIndex:e.queryIndex,isGhost:Boolean(e.isGhost),scrollTop:e.scrollTop}},scoreMeta:f,index:n}}).filter(e=>Boolean(e)).sort(cx).map(({item:e})=>e)},[e,t,u,g,h,x]),E=q(()=>[...w,...S,...C,...T,...k],[w,C,T,k,S]),A=q(()=>E.filter(e=>((e,t)=>0===t.length||t.every(t=>{const n=t.normalizedValue;if("type"===t.key)return e.category.toLowerCase().includes(n);if("folder"===t.key)return (e.folderName||e.breadcrumb||"").toLowerCase().includes(n);if("tag"===t.key)return (e.tagNames||e.tagBadges?.map(e=>e.name)||[]).some(e=>e.toLowerCase().includes(n));if("is"===t.key)return "pinned"===n?Boolean(e.isPinned):"unpinned"===n&&!e.isPinned;if("level"===t.key)return "outline"===e.category&&String(e.outlineTarget?.level??"")===n;if("date"===t.key){if("conversations"!==e.category&&"prompts"!==e.category)return false;const t=Qv(n);if(null===t)return false;const r=e.searchTimestamp||0;return !(r<=0)&&Date.now()-r<=864e5*t}return true}))(e,n)),[n,E]),M=q(()=>{const e={all:0,outline:0,conversations:0,prompts:0,settings:0,tips:0};return A.forEach(t=>{e[t.category]+=1,e.all+=1;}),e},[A]),I=q(()=>"all"!==f?[]:ox.map(e=>{const t=A.filter(t=>t.category===e),n=Boolean(b[e]),r=n?t.length:y,o=t.slice(0,r),i=Math.max(0,t.length-o.length);return {category:e,items:o,totalCount:t.length,hasMore:i>0,isExpanded:n,remainingCount:i}}).filter(e=>e.items.length>0),[f,y,b,A]),L=q(()=>"all"!==f?A.filter(e=>e.category===f):I.flatMap(e=>e.items),[f,A,I]);return {filteredGlobalSearchResults:A,globalSearchResultCounts:M,groupedGlobalSearchResults:I,visibleGlobalSearchResults:L}},ux={"loading-history":"exportOverlayLoadingHistory",preparing:"exportOverlayPreparing",extracting:"exportOverlayExtracting",packaging:"exportOverlayPackaging",downloading:"exportOverlayDownloading",copying:"exportOverlayCopying",restoring:"exportOverlayRestoring"},hx={"loading-history":"outlineCopyOverlayLoadingHistory",preparing:"outlineCopyOverlayPreparing",extracting:"outlineCopyOverlayExtracting",packaging:"exportOverlayPackaging",downloading:"exportOverlayDownloading",copying:"outlineCopyOverlayCopying",restoring:"outlineCopyOverlayRestoring"},gx={[fr]:{key:"navGeneral",fallback:"General"},[yr]:{key:"navFeatures",fallback:"Features"},[vr]:{key:"navSiteSettings",fallback:"Site Config"},[xr]:{key:"navGlobalSearch",fallback:"Global Search"},[br]:{key:"navAppearance",fallback:"Appearance"},[wr]:{key:"navShortcuts",fallback:"Keyboard Shortcuts"},[Sr]:{key:"navBackup",fallback:"Data Management"},[Cr]:{key:"navPermissions",fallback:"Permissions"},[kr]:{key:"navAbout",fallback:"About"}},px={panel:{key:"panelTab",fallback:"Panel"},tabOrder:{key:"tabOrderTab",fallback:"Tab Order"},shortcuts:{key:"shortcutsTab",fallback:"Quick Buttons"},toolsMenu:{key:"toolboxMenu",fallback:"Toolbox"},[Mr]:{key:"tabSettingsTab",fallback:"Tab Settings"},[Ir]:{key:"reminderTab",fallback:"Alerts"},[Tr]:{key:"outlineSettingsTitle",fallback:"Outline"},[Er]:{key:"conversationsSettingsTitle",fallback:"Conversations"},[Ar]:{key:"promptSettingsTitle",fallback:"Prompts"},[Nr]:{key:"readingHistorySettings",fallback:"Reading History"},[Lr]:{key:"contentProcessing",fallback:"Content"},[Rr]:{key:"toolboxMenu",fallback:"Toolbox"},[qr]:{key:"layoutTab",fallback:"Layout"},[Br]:{key:"tabModelLock",fallback:"Model Lock"},gemini:{key:"geminiSettingsTab",fallback:"Gemini"},aistudio:{key:"aistudioSettingsTitle",fallback:"AI Studio"},chatgpt:{key:"chatgptSettingsTitle",fallback:"ChatGPT"},claude:{key:"claudeSettingsTab",fallback:"Claude"},[Dr]:{key:"themePresetsTab",fallback:"Theme Presets"},[Pr]:{key:"customStylesTab",fallback:"Custom Styles"}},mx=new Set(["Meta","OS","Command","Cmd"]),fx=new Set(["Control","Ctrl"]),bx=[{id:"all",label:{key:"globalSearchCategoryAll",fallback:"All"},placeholder:{key:"globalSearchPlaceholderAll",fallback:"Search all"},emptyText:{key:"globalSearchEmptyAll",fallback:"No matching results"}},{id:"outline",label:{key:"globalSearchCategoryOutline",fallback:"Outline"},placeholder:{key:"globalSearchPlaceholderOutline",fallback:"Search outline"},emptyText:{key:"globalSearchEmptyOutline",fallback:"No outline results"}},{id:"conversations",label:{key:"globalSearchCategoryConversations",fallback:"Conversations"},placeholder:{key:"globalSearchPlaceholderConversations",fallback:"Search conversations on current site"},emptyText:{key:"globalSearchEmptyConversations",fallback:"No conversation results"}},{id:"prompts",label:{key:"globalSearchCategoryPrompts",fallback:"Prompts"},placeholder:{key:"globalSearchPlaceholderPrompts",fallback:"Search prompts"},emptyText:{key:"globalSearchEmptyPrompts",fallback:"No prompt results"}},{id:"settings",label:{key:"globalSearchCategorySettings",fallback:"Settings"},placeholder:{key:"globalSearchPlaceholderSettings",fallback:"Search settings"},emptyText:{key:"globalSearchEmptySettings",fallback:"No matching settings"}},{id:"tips",label:{key:"featureTipsCategory",fallback:"Tips"},placeholder:{key:"featureTipSearchPlaceholder",fallback:"Search feature tips…"},emptyText:{key:"globalSearchEmptyTips",fallback:"No matching tips"}}],yx={outline:{key:"globalSearchCategoryOutline",fallback:"Outline"},settings:{key:"globalSearchCategorySettings",fallback:"Settings"},conversations:{key:"globalSearchCategoryConversations",fallback:"Conversations"},prompts:{key:"globalSearchCategoryPrompts",fallback:"Prompts"},tips:{key:"featureTipsCategory",fallback:"Tips"}},vx={title:{key:"globalSearchMatchReasonTitle",fallback:"Title match"},folder:{key:"globalSearchMatchReasonFolder",fallback:"Folder match"},tag:{key:"globalSearchMatchReasonTag",fallback:"Tag match"},type:{key:"globalSearchMatchReasonType",fallback:"Type match"},code:{key:"globalSearchMatchReasonCode",fallback:"Code match"},category:{key:"globalSearchMatchReasonCategory",fallback:"Category match"},content:{key:"globalSearchMatchReasonContent",fallback:"Content match"},id:{key:"globalSearchMatchReasonId",fallback:"ID match"},keyword:{key:"globalSearchMatchReasonKeyword",fallback:"Keyword match"},alias:{key:"globalSearchMatchReasonAlias",fallback:"Alias match"},fuzzy:{key:"globalSearchMatchReasonFuzzy",fallback:"Fuzzy match"}},xx="settings-search-option",wx="ophel:global-search-shortcut-nudge:v1",Sx={"aistudio-collapse-advanced":"aistudioCollapseAdvanced","aistudio-collapse-navbar":"aistudioCollapseNavbar","aistudio-collapse-run-settings":"aistudioCollapseRunSettings","aistudio-collapse-tools":"aistudioCollapseTools","aistudio-enable-search":"aistudioEnableSearch","aistudio-markdown-fix":"aistudioMarkdownFixLabel","aistudio-remove-watermark":"aistudioRemoveWatermark","appearance-custom-styles":"customCSS","appearance-sync-native-page-theme":"syncNativePageThemeLabel","appearance-preset-dark":"darkModePreset","appearance-preset-light":"lightModePreset","chatgpt-markdown-fix":"chatgptMarkdownFixLabel","conversation-sync-delete":"conversationsSyncDeleteLabel","global-search-fuzzy-search":"globalSearchEnableFuzzySearchLabel","global-search-double-shift":"doubleShiftToSearch","global-search-shortcut-setting-link":"globalSearchShortcutSettingLabel","global-search-prompt-enter-behavior":"globalSearchPromptEnterBehaviorLabel","claude-session-keys":"claudeSessionKeyTitle","content-assistant-mermaid":"assistantMermaidLabel","content-formula-copy":"formulaCopyLabel","content-formula-copy-format":"formulaCopyFormatLabel","content-formula-delimiter":"formulaDelimiterLabel","content-table-copy":"tableCopyLabel","content-user-query-markdown":"userQueryMarkdownLabel","conversation-folder-rainbow":"folderRainbowLabel","conversation-sync-unpin":"conversationsSyncUnpinLabel","export-custom-model-name":"exportCustomModelName","export-custom-user-name":"exportCustomUserName","export-filename-timestamp":"exportFilenameTimestamp","export-include-thoughts":"exportIncludeThoughtsLabel","export-images-base64":"exportImagesToBase64Label","export-packaging":"exportPackagingLabel","gemini-markdown-fix":"markdownFixLabel","gemini-policy-max-retries":"maxRetriesLabel","gemini-policy-retry":"policyRetryLabel","gemini-watermark-removal":"watermarkRemovalLabel","layout-page-width-enabled":"enablePageWidth","layout-page-width-value":"pageWidthValueLabel","layout-user-query-width-enabled":"enableUserQueryWidth","layout-user-query-width-value":"userQueryWidthValueLabel","layout-zen-mode-enabled":"zenModeTitle","layout-zen-mode-exit-button-visible":"zenModeExitButtonVisibleLabel","outline-auto-update":"outlineAutoUpdateLabel","outline-follow-mode":"outlineFollowModeLabel","outline-inline-bookmark-mode":"inlineBookmarkModeLabel","outline-panel-bookmark-mode":"panelBookmarkModeLabel","outline-prevent-auto-scroll":"preventAutoScrollLabel","outline-show-word-count":"outlineShowWordCountLabel","outline-update-interval":"outlineUpdateIntervalLabel","panel-default-position":"defaultPositionLabel","panel-edge-distance":"defaultEdgeDistanceLabel","panel-edge-snap-threshold":"edgeSnapThresholdLabel","panel-height":"panelHeightLabel","panel-mode":"panelModeLabel","panel-width":"panelWidthLabel","prompt-double-click-send":"promptDoubleClickSendLabel","prompt-queue":"queueSettingLabel","quick-buttons-hide-when-panel-open":"quickButtonsHideWhenPanelOpenLabel","quick-buttons-opacity":"quickButtonsOpacityLabel","quick-buttons-proximity-radius":"quickButtonsProximityRadiusLabel","reading-history-auto-restore":"readingHistoryAutoRestoreLabel","reading-history-cleanup-days":"readingHistoryCleanup","reading-history-persistence":"readingHistoryPersistenceLabel","shortcuts-enabled":"enableShortcuts","shortcuts-global-url":"globalShortcutUrl","shortcuts-browser-shortcuts":"globalShortcutsTitle","shortcuts-prompt-submit-shortcut":"promptSubmitShortcutLabel","tab-auto-focus":"autoFocusLabel","tab-auto-rename":"autoRenameTabLabel","tab-notification-sound":"notificationSoundLabel","tab-notification-sound-preset":"notificationSoundPresetLabel","tab-notification-volume":"notificationVolumeLabel","tab-notification-repeat-count":"notificationRepeatCountLabel","tab-notification-repeat-interval":"notificationRepeatIntervalLabel","tab-notify-when-focused":"notifyWhenFocusedLabel","tab-open-new":"openNewTabLabel","tab-privacy-mode":"privacyModeLabel","tab-privacy-title":"privacyTitleLabel","tab-rename-interval":"renameIntervalLabel","tab-show-notification":"showNotificationLabel","tab-show-status":"showStatusLabel","tab-hide-status-when-read":"hideStatusWhenReadLabel","tab-title-format":"titleFormatLabel","tools-menu-export":"export","tools-menu-copyMarkdown":"exportToClipboard","tools-menu-move":"conversationsMoveTo","tools-menu-setTag":"conversationsSetTag","tools-menu-scrollLock":"shortcutToggleScrollLock","tools-menu-modelLock":"modelLockTitle","tools-menu-cleanup":"cleanup","tools-menu-settings":"tabSettings","usage-monitor-enabled":"usageMonitorEnabledLabel","usage-monitor-daily-limit":"usageMonitorDailyLimitLabel","usage-monitor-auto-reset":"usageMonitorAutoResetLabel"},Cx={gemini:{key:"globalSearchSiteGemini",fallback:"Gemini"},"gemini-enterprise":{key:"globalSearchSiteGeminiEnterprise",fallback:"Gemini Enterprise"},aistudio:{key:"globalSearchSiteAIStudio",fallback:"AI Studio"},chatgpt:{key:"globalSearchSiteChatGPT",fallback:"ChatGPT"},claude:{key:"globalSearchSiteClaude",fallback:"Claude"},grok:{key:"globalSearchSiteGrok",fallback:"Grok"},qwenai:{key:"globalSearchSiteQwenAi",fallback:"Qwen Studio"},ima:{key:"globalSearchSiteIma",fallback:"ima"},zai:{key:"globalSearchSiteZai",fallback:"Z.ai"}},kx=e=>e.replace(/[-_]/g," ").replace(/\s+/g," ").trim().replace(/\b([a-z])/g,(e,t)=>t.toUpperCase()),Tx=Object.freeze(Object.defineProperty({__proto__:null,App:()=>{const{settings:e,setSettings:t,updateDeepSetting:n,updateNestedSetting:r}=Mi(),o=Ii(),i=e?.features?.prompts?.submitShortcut??"enter";Mi(e=>e._syncVersion);const[a,s]=_(0),l=E(e=>{const t=le(e.key);return t===e.key?e.fallback:t},[a]),c=E((e,t)=>{let n=l(e);return Object.keys(t).forEach(e=>{n=n.replace(new RegExp(`{${e}}`,"g"),t[e]);}),n},[l]),d=q(()=>(()=>{if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"";return e.includes("mac")||t.includes("mac os")})(),[]),u=q(()=>cr(e?.shortcuts)||ti.shortcuts,[e?.shortcuts]),h=q(()=>{if(!u.enabled)return null;const e=u.keybindings[jn];return null===e?null:e||rr[jn]},[u]),g=h?dr(h,d):"",p=e?.globalSearch?.doubleShift??ti.globalSearch.doubleShift,m=q(()=>{const e=[];return g&&e.push(g),p&&e.push("double shift"),e.join(" / ")},[g,p]),f=d?"⌘":"Ctrl",b=E(e=>{if(e===jn)return m||null;if(!u.enabled)return null;const t=u.keybindings[e];if(null===t)return null;const n=t||rr[e];return n?dr(n,d):null},[m,d,u]),y=m||le("shortcutNotSet"),v=e?.globalSearch?.enableFuzzySearch??ti.globalSearch.enableFuzzySearch,x=q(()=>m?c({key:"globalSearchShortcutNudge",fallback:"下次可按 {shortcut} 快速打开"},{shortcut:m}):"",[c,m]),w=E(()=>{if("undefined"==typeof window)return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0};try{const e=window.localStorage.getItem(wx);if(!e)return {shownCount:0,lastShownAt:0,dismissed:!1,shortcutUsedCount:0};const t=JSON.parse(e);return {shownCount:Number.isFinite(t.shownCount)?Math.max(0,Number(t.shownCount)):0,lastShownAt:Number.isFinite(t.lastShownAt)?Math.max(0,Number(t.lastShownAt)):0,dismissed:Boolean(t.dismissed),shortcutUsedCount:Number.isFinite(t.shortcutUsedCount)?Math.max(0,Number(t.shortcutUsedCount)):0}}catch{return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0}}},[]),S=E(e=>{if("undefined"!=typeof window)try{window.localStorage.setItem(wx,JSON.stringify(e));}catch{}},[]),C=E(()=>{Ye.current&&(clearTimeout(Ye.current),Ye.current=null);},[]),k=E(e=>{e.stopPropagation();const t=e.target.closest(".gh-code-copy-btn");if(!t)return;const n=t.nextElementSibling?.textContent||"";n&&(navigator.clipboard?.writeText?navigator.clipboard.writeText(n).then(()=>{ld(t,{size:14});}).catch(()=>{Pi(l({key:"copyFailed",fallback:"Copy failed"}));}):Pi(l({key:"copyFailed",fallback:"Copy failed"})));},[l]),T=E(()=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null);},[]),A=E(e=>{T(),ye(e),xe(e);},[T]),M=E(e=>{const t=e.trimStart();A(e),fe(e=>t.startsWith("tip:")?"tips"===e?e:"tips":"tips"===e?"all":e);},[A]),I=E(()=>{t({globalSearch:{...ti.globalSearch,...e?.globalSearch||{},enableFuzzySearch:!v}});},[v,t,e?.globalSearch]),N=E(e=>{ye(e),T(),Ke.current=setTimeout(()=>{xe(e),Ke.current=null;},140);},[T]),R=E(()=>{C(),Le(false),qe("");},[C]),D=E(()=>{const e=w();S({...e,dismissed:true}),R();},[w,R,S]),P=E(()=>{const e=w(),t=e.shortcutUsedCount+1;S({...e,shortcutUsedCount:t,dismissed:e.dismissed||t>=2}),R();},[w,R,S]),B=E(()=>{if(!x)return;const e=w();if(e.dismissed)return;if(e.shortcutUsedCount>=2)return void S({...e,dismissed:true});if(e.shownCount>=3)return;const t=Date.now();e.lastShownAt>0&&t-e.lastShownAt<864e5||(S({...e,shownCount:e.shownCount+1,lastShownAt:t}),qe(x),Le(true),C(),Ye.current=setTimeout(()=>{Le(false),qe(""),Ye.current=null;},6e3));},[C,w,x,S]),z=E(e=>{const t=gx[e];return t?l(t):e},[l]),F=E(e=>{const t=px[e];return t?l(t):e},[l]),U=E(e=>{const t=Sx[e.settingId];if(t)return l({key:t,fallback:kx(e.settingId)});if(e.settingId.startsWith("model-lock-")){const t=e.settingId.slice(11),n=Cx[t];if(n){return `${l({key:"tabModelLock",fallback:"Model Lock"})}: ${l(n)}`}}if(e.settingId.startsWith("shortcut-binding-")){const t=e.settingId.slice(17),n=tr[t];if(n){return `${l({key:"navShortcuts",fallback:"Keyboard Shortcuts"})}: ${l({key:n.labelKey,fallback:n.label})}`}}return kx(e.settingId)},[l]),H=E(e=>{const t=Fr(e);if(!t)return l({key:"globalSearchCategorySettings",fallback:"Settings"});const n=z(t.page);if(!t.subTab)return n;return `${n} / ${F(t.subTab)}`},[l,z,F]),W=q(()=>am(),[]),j=q(()=>W?new zm(W):null,[W]),G=q(()=>W&&j?new Hm(W,j):null,[W,j]);L(()=>{if(!G)return;return e?.features?.prompts?.promptQueue??false?G.start():G.stop(),()=>G.stop()},[G,e?.features?.prompts?.promptQueue]);const V=q(()=>W?new Sm(W):null,[W]),[Q,K]=_(null);L(()=>{if(V)return K(null),V.onExportProgress(K);K(null);},[V]);const Z=q(()=>{if(!W)return null;return new Lm(W,e?.features?.outline??ti.features.outline,e=>{n("features","outline","expandLevel",e);},e=>{n("features","outline","showUserQueries",e);})},[W,n]),[Y,X]=_(false),J=$(false),ee=E(e=>{J.current=e,X(e);},[]),te=E(e=>{ee(e),r("panel","panelExpanded",e);},[ee,r]),ne=$(e);L(()=>{ne.current=e;},[e]),L(()=>{if(o&&e&&!wt.current){wt.current=true;const t=e.panel?.panelMode??"edge-snap",n=e.panel?.defaultPosition??"right";ee(e.panel?.panelExpanded??true),yt("edge-snap"===t?n:null);}},[o,ee,e]),L(()=>{if(!wt.current||!e)return;const t=e.panel?.panelExpanded??true;t!==J.current&&ee(t);},[ee,e]);const[re,oe]=_(false),ie=$(new Set),se=$(null);L(()=>{const e=d?"Meta":"Control",t=d?mx:fx,n=e=>mx.has(e)?"Meta":fx.has(e)?"Control":e,r=e=>!!e&&(d?e.ctrlKey||e.altKey||e.shiftKey:e.metaKey||e.altKey||e.shiftKey),o=()=>{const e=Array.from(ie.current);return e.length>0&&e.every(e=>t.has(e))},i=()=>{null!==se.current&&(window.clearTimeout(se.current),se.current=null);},a=a=>{if(!((a?d?a.metaKey||t.has(n(a.key)):a.ctrlKey||t.has(n(a.key)):ie.current.has(e))&&o()&&!r(a)))return i(),void oe(false);re||null!==se.current||(se.current=window.setTimeout(()=>{se.current=null,o()&&ie.current.has(e)&&oe(true);},200));},s=t=>{const o=n(t.key);o!==e||r(t)||ie.current.clear(),ie.current.add(o),a(t);},l=e=>{ie.current.delete(n(e.key)),a(e);},c=()=>{ie.current.clear(),a();};return window.addEventListener("keydown",s,true),window.addEventListener("keyup",l,true),window.addEventListener("blur",c),()=>{i(),window.removeEventListener("keydown",s,true),window.removeEventListener("keyup",l,true),window.removeEventListener("blur",c);}},[d,re]);const[ce,de]=_(null),[ue,he]=_(false),[ge,pe]=_(false),[me,fe]=_("all"),[be,ye]=_(""),[ve,xe]=_(""),[we,Se]=_(0),[Ce,ke]=_(false),[Te,Ee]=_("pointer"),[Ae,Me]=_({}),[Ie,Le]=_(false),[Pe,qe]=_(""),[Be,$e]=_(false),[_e,Oe]=_(-1),[ze,Fe]=_(()=>"undefined"!=typeof window&&Boolean(window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__)),[Ue,He]=_(()=>"undefined"!=typeof window&&window.__OPHEL_PENDING_UPDATE_VERSION__||null),We=$(null),je=$(null),Ge=$(null),Ve=$(null),Qe=$(null),Ke=$(null),Ze=$(0),Ye=$(null),Xe=$("ui"),Je=$(0),[et,tt]=_(0),nt=$(0),rt=$(null),{globalSearchPromptPreview:ot,globalSearchPromptPreviewPosition:it,clearPromptPreviewTimer:at,clearPromptPreviewHideTimer:st,hideGlobalSearchPromptPreview:lt,scheduleHideGlobalSearchPromptPreview:ct,scheduleGlobalSearchPromptPreview:dt,scheduleGlobalSearchPointerPreview:ut,refreshGlobalSearchPromptPreviewAnchorRect:ht}=(({settingsSearchResultsRef:e,pointerDelayMs:t,hideDelayMs:n})=>{const[r,o]=_(null),i=$(null),a=$(null),s=$(null),l=E(()=>{i.current&&(clearTimeout(i.current),i.current=null);},[]),c=E(()=>{a.current&&(clearTimeout(a.current),a.current=null);},[]),d=E(e=>"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):JSON.stringify(e).slice(1,-1),[]),u=E(t=>{const n=e.current;return n?n.querySelector(`[data-global-search-item-id="${d(t)}"]`):null},[d,e]),h=E(()=>{l(),c(),s.current=null,o(null);},[c,l]),g=E((e=n)=>{c(),a.current=setTimeout(()=>{h(),a.current=null;},e);},[c,n,h]),p=E(({item:e,anchorElement:t,delay:n,source:r})=>{"prompts"===e.category&&e.promptId&&e.promptContent&&e.promptContent.trim()&&(l(),c(),"keyboard"===r&&(s.current=e.id),i.current=setTimeout(()=>{"keyboard"===r&&s.current!==e.id||(o({itemId:e.id,content:e.promptContent,anchorRect:t.getBoundingClientRect()}),i.current=null);},n));},[c,l]),m=E(({item:e,anchorElement:n})=>{s.current=null,p({item:e,anchorElement:n,delay:t,source:"pointer"});},[t,p]),f=E(()=>{o(e=>{if(!e)return e;const t=u(e.itemId);if(!t)return null;const n=t.getBoundingClientRect();return Math.abs(n.top-e.anchorRect.top)<.5&&Math.abs(n.left-e.anchorRect.left)<.5&&Math.abs(n.right-e.anchorRect.right)<.5&&Math.abs(n.bottom-e.anchorRect.bottom)<.5?e:{...e,anchorRect:n}});},[u]),b=q(()=>{if(!r||"undefined"==typeof window)return null;const e=16,t=Math.max(280,Math.min(420,window.innerWidth-32)),n=Math.max(220,Math.min(420,window.innerHeight-32));let o=r.anchorRect.right+12;return o+t>window.innerWidth-e&&(o=r.anchorRect.left-t-12),o=Math.max(e,Math.min(o,window.innerWidth-t-e)),{top:Math.max(e,Math.min(r.anchorRect.top,window.innerHeight-e-n)),left:o}},[r]);return {globalSearchPromptPreview:r,globalSearchPromptPreviewPosition:b,clearPromptPreviewTimer:l,clearPromptPreviewHideTimer:c,hideGlobalSearchPromptPreview:h,scheduleHideGlobalSearchPromptPreview:g,scheduleGlobalSearchPromptPreview:p,scheduleGlobalSearchPointerPreview:m,refreshGlobalSearchPromptPreviewAnchorRect:f}})({settingsSearchResultsRef:Ve,pointerDelayMs:450,hideDelayMs:220}),[gt,pt]=_(null),[mt,ft]=_(false),[bt,yt]=_(null),vt=$(false),xt=$(false),wt=$(false),St=E(()=>{const e=[],t=document.querySelectorAll("plasmo-csui, #ophel-userscript-root");for(const n of t)n.shadowRoot&&e.push(n.shadowRoot);return document.body&&e.push(document.body),e},[]),Ct=E(e=>{for(const t of St()){const n=t.querySelector(e);if(n instanceof HTMLElement)return n}return null},[St]),{isEdgePeeking:kt,showEdgePeek:Tt,hideEdgePeek:Et,scheduleEdgePeekSync:At,showEdgePeekFromShortcut:Mt,markSuppressOverlayInit:It,markSyncAfterOpen:Lt,handlePanelMouseEnter:Nt,handlePanelMouseLeave:Rt,handleInteractionChange:Dt}=ef({edgeSnapState:bt,panelMode:e?.panel?.panelMode,isPanelExpanded:Y,findUiElement:Ct,getQueryRoots:St,isSettingsOpenRef:vt}),[Pt,qt]=_(false),[Bt,$t]=_(null),_t=$(false),Ot=$(false),zt=$(null),Ft=$(null),Ut=$(null),Ht=$(false),Wt=E(()=>{zt.current&&(clearTimeout(zt.current),zt.current=null);},[]),jt=E(()=>{Ft.current&&(clearTimeout(Ft.current),Ft.current=null);},[]),Gt=E(()=>{Wt(),jt(),_t.current=false,Ot.current=false,qt(false),$t(null);},[Wt,jt]),Vt=E(()=>{if(Ht.current)return false;const e=[".gh-main-panel",".quick-btn-group"],t=Ut.current;for(const n of e){const e=Ct(n);if(e){if(t){const n=e.getBoundingClientRect();if(t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom)return true;continue}if(e.matches(":hover"))return true}}return false},[Ct]),Qt=E(()=>{Wt(),jt();const e=()=>{Ft.current=null,_t.current&&(Ot.current||os(St())||Vt()?Ft.current=setTimeout(e,250):(_t.current=false,qt(false),$t(null)));};Ft.current=setTimeout(e,250);},[Wt,jt,St,Vt]),Kt=E(e=>{Dt(e),Ot.current=e,_t.current&&(e?jt():Qt());},[jt,Dt,Qt]),Zt=E((e,t)=>{if(J.current)return;Ht.current=false,Wt(),jt();const n={left:e.left,right:e.right,top:e.top,bottom:e.bottom,width:e.width,height:e.height};if($t(n),_t.current)return;const r=300+(t?.waitForGroupDwell?300:0);zt.current=setTimeout(()=>{zt.current=null,J.current||($t(n),_t.current=true,qt(true));},r);},[Wt,jt]),Yt=E(()=>{_t.current?Qt():Wt();},[Wt,Qt]),Xt=E(e=>{if(_t.current)return Wt(),void jt();Nt();},[Wt,jt,Nt]),Jt=E(e=>{_t.current?Qt():Rt();},[Rt,Qt]);L(()=>{Y&&Pt&&Gt();},[Gt,Pt,Y]),L(()=>{const e=e=>{Ht.current=false,Ut.current={clientX:e.clientX,clientY:e.clientY};},t=()=>{Ht.current=true,Ut.current=null,Wt(),_t.current&&Qt();},n=()=>{"hidden"===document.visibilityState&&t();},r=e=>{null===e.relatedTarget&&t();},o=e=>{null===e.relatedTarget&&t();};return window.addEventListener("pointermove",e,true),window.addEventListener("pointerdown",e,true),window.addEventListener("blur",t),document.addEventListener("visibilitychange",n),document.addEventListener("pointerout",r,true),document.addEventListener("mouseout",o,true),()=>{window.removeEventListener("pointermove",e,true),window.removeEventListener("pointerdown",e,true),window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",n),document.removeEventListener("pointerout",r,true),document.removeEventListener("mouseout",o,true);}},[Wt,Qt]),L(()=>{if(!Pt)return;let e=os(St());e&&jt();const t=new MutationObserver(()=>{const t=os(St());t?jt():e&&Qt(),e=t;});for(const n of St())t.observe(n,{childList:true,subtree:true});return ()=>{t.disconnect();}},[jt,St,Pt,Qt]),L(()=>()=>{Wt(),jt();},[Wt,jt]),L(()=>{const e=e=>{ge&&(xt.current=false,rt.current=null,T(),pe(false),fe("all"),ye(""),xe(""),Oe(-1),Se(0),ke(false),Ee("pointer"),Me({}),Ze.current=0),vt.current||(vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&Tt(),he(true));};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[T,bt,ge,Tt]);const en=cm(e=>e.conversations),tn=mm(e=>e.folders),nn=vm(e=>e.tags),rn=Rm(e=>e.prompts),on=q(()=>(e=>{const t=/(^|\s)([a-z]+):((?:"(?:\\.|[^"])+")|(?:\\.|[^\s])+)/gi,n=[],r=[],o=[],i={};let a=t.exec(e);for(;a;){const s=(a[2]||"").toLowerCase(),l=a[3]||"",c=(a.index||0)+(a[1]?.length||0),d=c+`${s}:${l}`.length,u=l.startsWith('"')!==l.endsWith('"'),h=Jv(s),g=Vv(l),p=jv(g);if(!zv.includes(s)){r.push({id:`unknown:${s}:${a.index||0}`,code:"unknownOperator",operator:s,suggestion:h||void 0}),a=t.exec(e);continue}const m=s;if(u){r.push({id:`invalid:${m}:quote:${a.index||0}`,code:"invalidValue",operator:m,value:l}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!g){r.push({id:`invalid:${m}:empty:${a.index||0}`,code:"invalidValue",operator:m}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!Zv(m,p)){r.push({id:`invalid:${m}:${p}:${a.index||0}`,code:"invalidValue",operator:m,value:g,suggestion:Yv(m)}),o.push({start:c,end:d}),a=t.exec(e);continue}const f=(i[m]||0)+1;i[m]=f;const b={id:Xv(m,p,f),key:m,value:g,normalizedValue:p};Kv(b,n)?(r.push({id:`conflict:${m}:${p}:${a.index||0}`,code:"conflict",operator:m,value:g}),o.push({start:c,end:d}),a=t.exec(e)):(o.push({start:c,end:d}),n.push(b),a=t.exec(e));}if(0===o.length)return {rawQuery:e,plainQuery:e.trim(),filters:n,diagnostics:r};o.sort((e,t)=>e.start-t.start);let s="",l=0;return o.forEach(t=>{lon.filters,[on.filters]),sn=q(()=>on.diagnostics,[on.diagnostics]),ln=q(()=>on.plainQuery,[on.plainQuery]),cn=q(()=>jr(""),[]);L(()=>{if(!Z||!ge)return;const e=()=>{Z.refresh(),tt(e=>e+1);};e();const t=Z.subscribe(()=>{tt(e=>e+1);}),n=window.setInterval(()=>{e();},1200);return ()=>{t(),window.clearInterval(n);}},[ge,Z]);const dn=q(()=>Array.from(new Set(Gv(ln))).sort((e,t)=>t.length-e.length),[ln]),{filteredGlobalSearchResults:un,globalSearchResultCounts:hn,groupedGlobalSearchResults:gn,visibleGlobalSearchResults:pn}=dx({activeGlobalSearchPlainQuery:ln,enableFuzzySearch:v,activeGlobalSearchSyntaxFilters:an,settingsSearchResults:cn,resolveSettingSearchTitle:U,getSettingsBreadcrumb:H,conversationManager:V,conversationsSnapshot:en,foldersSnapshot:tn,tagsSnapshot:nn,promptsSnapshot:rn,outlineManager:Z,outlineSearchVersion:et,getLocalizedText:l,resolveShortcutLabel:b,passThroughModifierLabel:f,activeGlobalSearchCategory:me,expandedGlobalSearchCategories:Ae,allCategoryItemLimit:12}),mn=q(()=>{const e=new Map;return pn.forEach((t,n)=>{e.set(t.id,n);}),e},[pn]),fn=q(()=>0===pn.length?-1:Math.min(we,pn.length-1),[we,pn.length]),bn=fn>=0?`${xx}-${fn}`:void 0,yn=q(()=>bx.find(e=>e.id===me)||bx[0],[me]),vn=q(()=>({label:l(yn.label),placeholder:l(yn.placeholder),emptyText:l(yn.emptyText)}),[yn,l]),xn=q(()=>bx.reduce((e,t)=>(e[t.id]=l(t.label),e),{}),[l]),wn=q(()=>Object.entries(yx).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),Sn=q(()=>Object.entries(vx).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),{activeGlobalSearchFilterChips:Cn,hasOverflowGlobalSearchFilterChips:kn,globalSearchSyntaxDiagnosticMessages:Tn,globalSearchSyntaxHelpTitle:En,globalSearchSyntaxHelpDescription:An,globalSearchSyntaxHelpItems:Mn,globalSearchSyntaxSuggestions:In,shouldShowGlobalSearchSyntaxSuggestions:Ln}=(({getLocalizedText:e,activeGlobalSearchSyntaxFilters:t,filterChipMaxCount:n,isGlobalSettingsSearchOpen:r,settingsSearchInputValue:o,filteredGlobalSearchResults:i,suggestionLimit:a})=>{const s=q(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),l=q(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),c=q(()=>e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),[e]),d=q(()=>e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"}),[e]),u=q(()=>({type:e({key:"globalSearchSyntaxSuggestionTypeDesc",fallback:"Filter by result type"}),folder:e({key:"globalSearchSyntaxSuggestionFolderDesc",fallback:"Filter by folder or category"}),tag:e({key:"globalSearchSyntaxSuggestionTagDesc",fallback:"Filter by tag name"}),is:e({key:"globalSearchSyntaxSuggestionIsDesc",fallback:"Filter by status"}),level:e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),date:e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"})}),[e]),h=q(()=>({outline:e({key:"globalSearchCategoryOutline",fallback:"Outline"}),conversations:e({key:"globalSearchCategoryConversations",fallback:"Conversations"}),prompts:e({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),settings:e({key:"globalSearchCategorySettings",fallback:"Settings"})}),[e]),g=q(()=>({pinned:e({key:"globalSearchSyntaxPinned",fallback:"Pinned"}),unpinned:e({key:"globalSearchSyntaxUnpinned",fallback:"Unpinned"})}),[e]),p=q(()=>({unknownOperator:e({key:"globalSearchSyntaxDiagnosticUnknownOperator",fallback:"Unknown operator"}),invalidValue:e({key:"globalSearchSyntaxDiagnosticInvalidValue",fallback:"Invalid filter value"}),conflict:e({key:"globalSearchSyntaxDiagnosticConflict",fallback:"Conflicting filters removed"})}),[e]),m=q(()=>e({key:"globalSearchSyntaxHelpTitle",fallback:"Search syntax examples"}),[e]),f=q(()=>e({key:"globalSearchSyntaxHelpDesc",fallback:"Click to insert. Keywords are English-only."}),[e]),b=q(()=>e({key:"featureTipSearchPlaceholder",fallback:"Search feature tips…"}),[e]),y=q(()=>[{id:"help:tip:",token:"tip:",label:"tip:",description:b},{id:"help:type:outline",token:"type:outline",label:"type:outline",description:h.outline},{id:"help:type:conversations",token:"type:conversations",label:"type:conversations",description:h.conversations},{id:"help:type:prompts",token:"type:prompts",label:"type:prompts",description:h.prompts},{id:"help:type:settings",token:"type:settings",label:"type:settings",description:h.settings},{id:"help:is:pinned",token:"is:pinned",label:"is:pinned",description:g.pinned},{id:"help:is:unpinned",token:"is:unpinned",label:"is:unpinned",description:g.unpinned},{id:"help:level:0",token:"level:0",label:"level:0",description:e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"})},{id:"help:date:7d",token:"date:7d",label:"date:7d",description:d},{id:"help:date:30d",token:"date:30d",label:"date:30d",description:d},{id:"help:folder:inbox",token:"folder:inbox",label:"folder:inbox",description:u.folder},{id:"help:tag:work",token:"tag:work",label:"tag:work",description:u.tag}],[b,e,d,g.pinned,g.unpinned,u.folder,u.tag,h.conversations,h.outline,h.prompts,h.settings]),v=q(()=>t.slice(0,n).map(e=>({id:e.id,key:e.key,value:e.value,label:`${s[e.key]}: ${e.value}`})),[t,n,s]),x=t.length>n,w=q(()=>{if(!r)return [];const t=ex(o),n=t?.token||"",s=n.length>0,p=n.toLowerCase(),m=n.match(/^([a-z]+):(.*)$/i);if(m){const t=m[1].toLowerCase();if(!zv.includes(t))return [];const n=m[2]||"",r=n.toLowerCase(),o=[],s=e=>{o.some(t=>t.id===e.id)||o.push(e);};if("type"===t)Fv.forEach(e=>{n&&!e.toLowerCase().startsWith(r)||s({id:`type:${e}`,token:`type:${e}`,label:`type:${e} · ${h[e]}`,description:u.type});});else if("is"===t)n&&!"pinned".startsWith(r)||s({id:"is:pinned",token:"is:pinned",label:`is:pinned · ${g.pinned}`,description:u.is}),n&&!"unpinned".startsWith(r)||s({id:"is:unpinned",token:"is:unpinned",label:`is:unpinned · ${g.unpinned}`,description:u.is});else if("level"===t)Hv.forEach(t=>{n&&!t.startsWith(r)||s({id:`level:${t}`,token:`level:${t}`,label:`level:${t}`,description:"0"===t?e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"}):c});});else if("date"===t){const e=r.match(/^(\d{0,3})d?$/);if(e){const t=e[1];if(t){const e=`${t}d`;Number(t)>0&&s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});}}Wv.forEach(e=>{n&&!e.startsWith(r)||s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});});}if("folder"===t){const e=new Map;i.forEach(t=>{const o=(t.folderName||"").trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`folder:"${e}"`:`folder:${e}`;s({id:`folder:${e.toLowerCase()}`,token:t,label:`folder:${e}`,description:u.folder});});}if("tag"===t){const e=new Map;i.forEach(t=>{(t.tagNames||t.tagBadges?.map(e=>e.name)||[]).forEach(t=>{const o=t.trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);});}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`tag:"${e}"`:`tag:${e}`;s({id:`tag:${e.toLowerCase()}`,token:t,label:`tag:${e}`,description:u.tag});});}return o.slice(0,a)}return zv.filter(e=>!s||e.startsWith(p)).map(e=>({id:`operator:${e}`,token:`${e}:`,label:`${e}: ${l[e]}`,description:u[e]})).slice(0,a)},[i,e,d,g,c,u,l,h,r,o,a]);return {activeGlobalSearchFilterChips:v,hasOverflowGlobalSearchFilterChips:x,globalSearchSyntaxDiagnosticMessages:p,globalSearchSyntaxHelpTitle:m,globalSearchSyntaxHelpDescription:f,globalSearchSyntaxHelpItems:y,globalSearchSyntaxSuggestions:w,shouldShowGlobalSearchSyntaxSuggestions:w.length>0&&Boolean(ex(o)?.token)}})({getLocalizedText:l,activeGlobalSearchSyntaxFilters:an,filterChipMaxCount:4,isGlobalSettingsSearchOpen:ge,settingsSearchInputValue:be,filteredGlobalSearchResults:un,suggestionLimit:8}),Nn=q(()=>l({key:"globalSearchResultsLabel",fallback:"Global search results"}),[l]),Rn=E(e=>{const t=ex(be),n=!e.token.endsWith(":"),r=`${e.token}${n?" ":""}`,o=t?`${be.slice(0,t.start)}${r}`:be.trim().length>0?`${be}${be.endsWith(" ")?"":" "}${r}`:r;M(o),Oe(-1),Se(0),window.requestAnimationFrame(()=>{const e=We.current;if(!e)return;const t=o.length;e.focus({preventScroll:true}),e.setSelectionRange(t,t);});},[be,M]),Dn=E(e=>{Rn(e),$e(false);},[Rn]),Pn=E(e=>{const t=an.filter(t=>t.id!==e),n=(({plainQuery:e,filters:t})=>`${e} ${t.map(e=>{const t=e.value.replace(/([\\"])/g,"\\$1"),n=/\s/.test(e.value)?`"${t}"`:t;return `${e.key}:${n}`}).join(" ")}`.replace(/\s+/g," ").trim())({plainQuery:ln,filters:t});A(n),Oe(-1),Se(0);},[ln,an,A]),qn=E(()=>{A(ln),Oe(-1),Se(0);},[ln,A]),Bn=q(()=>{if(fn<0)return null;const e=pn[fn];if(!e)return null;const t=wn[e.category],n=c({key:"globalSearchContextCurrentItem",fallback:"第 {current} 项"},{current:String(fn+1)});if("all"!==me)return {label:t,meta:`${n} · ${c({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(pn.length)})}`};const r=gn.find(t=>t.category===e.category);return r?{label:t,meta:`${n} · ${c({key:"globalSearchContextShownProgress",fallback:"已显示 {shown}/{total}"},{shown:String(r.items.length),total:String(r.totalCount)})}`}:{label:t,meta:`${n} · ${c({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(pn.length)})}`}},[me,fn,c,gn,wn,pn]),$n=E(()=>{vt.current=false,he(false);const e=ne.current;if("edge-snap"!==e?.panel?.panelMode)return;const t=Ct(".gh-main-panel");if(!t)return;if(!(t.classList.contains("edge-snapped-left")||t.classList.contains("edge-snapped-right"))){const n=t.getBoundingClientRect(),r=e?.panel?.edgeSnapThreshold??30;n.left{Xe.current=e,vt.current?(xt.current=true,$n()):xt.current=false,bt&&"edge-snap"===ne.current?.panel?.panelMode&&Tt();const t=document.activeElement;t instanceof HTMLElement&&t!==document.body?rt.current=t:rt.current=null,T(),ye(""),xe(""),$e(false),Oe(-1),fe("all"),Se(0),ke(false),Ee("pointer"),Me({}),Ze.current=0,pe(true);},[T,$n,bt,Tt]),On=E(e=>{const t=e?.restoreFocus??true,n=e?.reopenSettings??false,r=rt.current;if(rt.current=null,xt.current=false,T(),pe(false),fe("all"),ye(""),xe(""),$e(false),Oe(-1),Se(0),ke(false),Ee("pointer"),Me({}),Ze.current=0,n)return vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&Tt(),void he(true);At(),t&&r&&r.isConnected&&window.requestAnimationFrame(()=>{if(r.isConnected)try{r.focus({preventScroll:!0});}catch{r.focus();}});},[T,bt,At,Tt]),zn=E(()=>{ge&&On({restoreFocus:false}),xt.current=false,vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&Tt(),he(true);},[On,bt,ge,Tt]),Fn=E(async t=>{const n=++nt.current;if(On({restoreFocus:false}),t.tipId){if(t.tipHighlightTarget){const e=Ct(`[data-tip-target="${t.tipHighlightTarget}"]`);if(e)return e.classList.remove("feature-highlight"),e.offsetWidth,e.classList.add("feature-highlight"),setTimeout(()=>e.classList.remove("feature-highlight"),2500),void e.scrollIntoView({behavior:"smooth",block:"nearest"})}Pi(t.tipActionText||t.snippet||t.title,3e3);}else if("settings"===t.category&&t.settingId)window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:t.settingId}}));else {if("outline"===t.category&&t.outlineTarget&&Z){const e=(t,n)=>{for(const r of t){if(r.index===n)return r;if(r.children&&r.children.length>0){const t=e(r.children,n);if(t)return t}}return null},r=e(Z.getTree(),t.outlineTarget.index);let o=r?.element||null;if(!o||!o.isConnected){const e=await Z.resolveOutlineTarget(t.outlineTarget,t.outlineTarget.queryIndex);e&&(o=e);}if(n!==nt.current)return;if(o&&o.isConnected)return Z.scrollToOutlineTarget(o),o.classList.add("outline-highlight"),void setTimeout(()=>o?.classList.remove("outline-highlight"),2e3);if(t.outlineTarget.isGhost&&void 0!==t.outlineTarget.scrollTop){const e=Z.getScrollContainer();if(e)return e.scrollTo({top:t.outlineTarget.scrollTop,behavior:"smooth"}),void Pi(le("bookmarkContentMissing"),3e3)}return}if("prompts"===t.category&&t.promptId){const n=rn.find(e=>e.id===t.promptId);if(!n)return;const o=()=>{te(true);const t=(e?.features?.order||ti.features.order).indexOf(hr);t>=0&&window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:t}}));},i=()=>{de(null),o();const e={promptId:n.id};window.__ophelPendingLocatePrompt=e,window.dispatchEvent(new CustomEvent("ophel:locatePrompt",{detail:e}));};if("locate"===(e?.globalSearch?.promptEnterBehavior??"smart"))return void i();if(!j)return void o();if(r=n.content,/\{\{([^\s{}]+)\}\}/.test(r)){de(null),o();const e={promptId:n.id,submitAfterInsert:false};return window.__ophelPendingPromptVariableDialog=e,void window.dispatchEvent(new CustomEvent("ophel:openPromptVariableDialog",{detail:e}))}return void(async()=>{if(await j.insertPrompt(n.content))return j.updateLastUsed(n.id),de(n),void Pi(`${le("inserted")}: ${n.title}`);i(),Pi(le("insertFailed"));})()}var r;"conversations"===t.category&&t.conversationId&&W?.navigateToConversation(t.conversationId,t.conversationUrl);}},[W,On,Ct,Z,te,j,rn,e]);L(()=>{ge&&(We.current?.focus(),We.current?.select());},[ge]),L(()=>{ge&&"ui"===Xe.current&&B();},[ge,B]),L(()=>()=>{C();},[C]);const Un=$(ge);L(()=>{Un.current=ge;},[ge]);const Hn=E(()=>{Un.current||(Je.current=0,P(),_n("shortcut"));},[P,_n]);L(()=>{const e=e=>{if(Un.current)return;if("Shift"!==e.key&&(Je.current=0),"Shift"!==e.key||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;const t=Date.now();if((ne.current?.globalSearch?.doubleShift??ti.globalSearch.doubleShift)&&t-Je.current<=360)return e.preventDefault(),e.stopPropagation(),Je.current=0,P(),void _n("shortcut");Je.current=t;};return window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}},[P,_n]),L(()=>{const e=()=>{_n("event");};return window.addEventListener("ophel:openSettingsSearch",e),()=>{window.removeEventListener("ophel:openSettingsSearch",e);}},[_n]),L(()=>()=>{T();},[T]),L(()=>{if(!ge||!Be)return;const e=e=>{const t=e.composedPath?e.composedPath():[e.target];je.current&&t.includes(je.current)||Ge.current&&t.includes(Ge.current)||$e(false);};return document.addEventListener("mousedown",e,true),()=>{document.removeEventListener("mousedown",e,true);}},[ge,Be]),L(()=>{if(!ge)return void lt();if("keyboard"!==Te)return;const e=pn[we];if(!e||"prompts"!==e.category)return void lt();const t=Ve.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${we}"]`);n&&dt({item:e,anchorElement:n,delay:700,source:"keyboard"});},[lt,ge,dt,we,Te,pn]),L(()=>{Se(0),ke(false),Ee("pointer"),Me({}),Ze.current=0,lt();},[me,lt,ve]),L(()=>{ge||lt();},[lt,ge]),L(()=>{ot&&Qe.current&&cd(Qe.current,{size:14});},[ot]),L(()=>{if(!ge||!ot)return;const e=()=>{ht();},t=Ve.current;return window.addEventListener("resize",e),window.addEventListener("scroll",e,true),t?.addEventListener("scroll",e),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,true),t?.removeEventListener("scroll",e);}},[ot,ge,ht]),L(()=>()=>{at(),st();},[st,at]),(({isGlobalSettingsSearchOpen:e,showGlobalSearchSyntaxHelp:t,setShowGlobalSearchSyntaxHelp:n,activeGlobalSearchCategory:r,categoryIds:o,setActiveGlobalSearchCategory:i,settingsSearchActiveIndex:a,setSettingsSearchActiveIndex:s,settingsSearchNavigationMode:l,setSettingsSearchNavigationMode:c,setSettingsSearchHoverLocked:d,shouldShowGlobalSearchSyntaxSuggestions:u,globalSearchSyntaxSuggestions:h,activeSearchSyntaxSuggestionIndex:g,setActiveSearchSyntaxSuggestionIndex:p,applyGlobalSearchSyntaxSuggestion:m,visibleGlobalSearchResults:f,navigateToSearchResult:b,closeGlobalSettingsSearch:y,getShouldReturnToSettingsOnEscape:v,settingsSearchResultsRef:x,keyboardSafeTop:w,keyboardSafeBottom:S})=>{const C=$(void 0);C.current=e=>{if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),t)return void n(false);const r=v();return void y({restoreFocus:!r,reopenSettings:r})}if("Tab"===e.key){e.preventDefault(),e.stopPropagation();const t=o.findIndex(e=>e===r);if(t<0)return i("all"),s(0),d(false),void c("keyboard");const n=o.length,a=e.shiftKey?(t-1+n)%n:(t+1)%n;return i(o[a]),s(0),d(false),void c("keyboard")}if(u){if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e+1;return t>=h.length?0:t});if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e-1;return t<0?h.length-1:t});if("Enter"===e.key&&g>=0){const t=h[g];if(!t)return;return e.preventDefault(),e.stopPropagation(),void m(t)}}if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e+1)%f.length);if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e-1+f.length)%f.length);if("Enter"===e.key){if(0===f.length)return;const t=f[a]||f[0];if(!t)return;f[a]||s(0),e.preventDefault(),e.stopPropagation(),b(t);}},L(()=>{if(!e)return;const t=e=>C.current?.(e);return window.addEventListener("keydown",t,true),()=>{window.removeEventListener("keydown",t,true);}},[e]),L(()=>{0!==f.length?a>=f.length&&s(0):0!==a&&s(0);},[a,s,f.length]),L(()=>{u?g>=h.length&&p(h.length-1):-1!==g&&p(-1);},[g,h.length,p,u]);const k=E((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),o=n.top+w,i=n.bottom-S;if(r.topi){const t=r.bottom-i,n=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.min(n,e.scrollTop+t);}},[S,w]);L(()=>{if(!e)return;if("keyboard"!==l)return;const t=x.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${a}"]`);n&&k(t,n);},[k,e,a,l,x,f]);})({isGlobalSettingsSearchOpen:ge,showGlobalSearchSyntaxHelp:Be,setShowGlobalSearchSyntaxHelp:$e,activeGlobalSearchCategory:me,categoryIds:bx.map(e=>e.id),setActiveGlobalSearchCategory:fe,settingsSearchActiveIndex:we,setSettingsSearchActiveIndex:Se,settingsSearchNavigationMode:Te,setSettingsSearchNavigationMode:Ee,setSettingsSearchHoverLocked:ke,shouldShowGlobalSearchSyntaxSuggestions:Ln,globalSearchSyntaxSuggestions:In,activeSearchSyntaxSuggestionIndex:_e,setActiveSearchSyntaxSuggestionIndex:Oe,applyGlobalSearchSyntaxSuggestion:Rn,visibleGlobalSearchResults:pn,navigateToSearchResult:Fn,closeGlobalSettingsSearch:On,getShouldReturnToSettingsOnEscape:()=>xt.current,settingsSearchResultsRef:Ve,keyboardSafeTop:8,keyboardSafeBottom:12}),L(()=>{o&&e?.language&&(ae(e.language),s(e=>e+1));},[e?.language,o]);const Wn=E(e=>{de(e);},[]),Gn=E(()=>{de(null),W&&W.clearTextarea();},[W]);L(()=>{Z&&e&&Z.updateSettings(e.features?.outline);},[Z,e]),L(()=>{V&&e&&V.updateSettings({syncUnpin:e.features?.conversations?.syncUnpin??false});},[V,e]);const Vn=q(()=>{const t=am(),n=t?.getSiteId()||"_default",r=e?.theme?.sites?.[n]||e?.theme?.sites?._default;return Ym({mode:r?.mode||"light",adapter:W,lightPresetId:r?.lightStyleId||"google-gradient",darkPresetId:r?.darkStyleId||"classic-dark",syncNativePageTheme:e?.theme?.syncNativePageTheme??true})},[]),Qn=O(Vn.subscribe,Vn.getSnapshot);L(()=>{if(!o)return;return Vn.setOnModeChange((e,n)=>{if(!Mi.getState()._hasHydrated)return;const r=n||e,o=ne.current,i=o?.theme?.sites||{},a=am(),s=a?.getSiteId()||"_default",l={lightStyleId:"google-gradient",darkStyleId:"classic-dark",mode:"light",...i[s]||i._default};t({theme:{...o?.theme,sites:{...i,[s]:{...l,mode:r}}}});}),()=>{Vn.setOnModeChange(void 0);}},[Vn,t,o]);const Kn=e?.theme?.sites,Zn=e?.features?.conversations?.syncUnpin,Yn=e?.features?.conversations?.syncDelete,Xn=e?.features?.outline?.enabled??true,Jn=e?.features?.outline?.inlineBookmarkMode,er=Boolean(e),nr=e?.quickButtons||ti.quickButtons,or=nr.collapsed,ir=or.find(e=>"floatingToolbar"===e.id)?.enabled??true,ar=nr.floatingToolbar?.open??true,sr=e?.panel?.preventAutoScroll??false,lr=Z?.getGhostBookmarkIds().length??0;L(()=>{ir&&ar||(pt(null),ft(false));},[ir,ar]),L(()=>{if(!o)return;const e=am(),t=e?.getSiteId()||"_default",n=Kn?.[t]||Kn?._default,r=n?.lightStyleId,i=n?.darkStyleId;r&&i&&Vn.setPresets(r,i);},[Kn,Vn,o]),L(()=>{o&&Vn.setCustomStyles(e?.theme?.customStyles||[]);},[e?.theme?.customStyles,Vn,o]),L(()=>{o&&Vn.setNativeThemeOverrideEnabled(e?.theme?.syncNativePageTheme??true);},[e?.theme?.syncNativePageTheme,Vn,o]);const ur=E(async e=>{await Vn.toggle(e);},[Vn]);L(()=>{if(o)return Vn.startThemeMonitoring(),()=>{Vn.stopThemeMonitoring();}},[Vn,o]),L(()=>{if(j&&j.init(),V&&V.init(),Z){Z.refresh();const e=setInterval(()=>{Z.refresh();},2e3),t=()=>Z.handleUrlChange(),n=()=>Z.refresh();return window.addEventListener("gh-url-change",t),window.addEventListener("ophel:refreshOutline",n),()=>{clearInterval(e),window.removeEventListener("gh-url-change",t),window.removeEventListener("ophel:refreshOutline",n),V?.destroy();}}},[j,V,Z]),L(()=>{if(!V||"undefined"==typeof chrome)return;const e=(e,t,n)=>e?.type===gd&&(V.destroy(),n({success:true}),true);return chrome.runtime.onMessage.addListener(e),()=>{chrome.runtime.onMessage.removeListener(e);}},[V]),L(()=>{const e=e=>{if(window.__OPHEL_EXTENSION_UPDATE_DISMISSED__)return;const t=e,n=t.detail?.version||window.__OPHEL_PENDING_UPDATE_VERSION__||null;He(n),Fe(true);};return window.addEventListener(wd,e),window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__&&!window.__OPHEL_EXTENSION_UPDATE_DISMISSED__&&(Fe(true),He(window.__OPHEL_PENDING_UPDATE_VERSION__||null)),()=>{window.removeEventListener(wd,e);}},[]),L(()=>(window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=ze,ze&&document.getElementById("ophel-extension-update-fallback")?.remove(),()=>{window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=false;}),[ze]);const gr=E(()=>{window.__OPHEL_EXTENSION_UPDATE_DISMISSED__=true,window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__=false,Fe(false);},[]),pr=E(()=>{window.location.reload();},[]);L(()=>{V&&V.updateSettings({syncUnpin:Zn??false,syncDelete:Yn??true});},[V,Zn,Yn]),L(()=>{if(!(o&&Z&&W&&er))return;const e=Jn||"always";if(!Xn||"hidden"===e)return void Im.cleanupInjectedArtifacts();const t=new Im(Z,W,e);return ()=>{t.cleanup();}},[Z,W,Xn,Jn,er,o]);const mr=E(()=>{const e=ne.current;if(!e)return;const n=!e.panel?.preventAutoScroll;t({panel:{...e.panel,preventAutoScroll:n}}),Pi(le(n?"preventAutoScrollEnabled":"preventAutoScrollDisabled"));},[t]),fr=E(async()=>{if(!V||!W)return;const e=W.getSessionId();if(!e)return void Pi(le("exportNeedOpenFirst"));await V.exportConversation(e,"markdown")||Pi(le("exportFailed"));},[V,W]),br=E(()=>{if(!V||!W)return;const e=W.getSessionId();if(!e)return void Pi(le("noConversationToLocate"));const t=V.getConversation(e);pt({convId:e,activeFolderId:t?.folderId});},[V,W]),yr=E(()=>{if(!Z)return;const e=Z.clearGhostBookmarks();Pi(0!==e?`${le("cleared")} (${e})`:le("floatingToolbarClearGhostEmpty"));},[Z]),vr=E(async()=>{if(!V||!W)return;const e=W.getSessionId();if(!e)return void Pi(le("exportNeedOpenFirst"));await V.exportConversation(e,"clipboard")||Pi(le("exportFailed"));},[V,W]),xr=E(()=>{if(!W)return;const e=W.getSiteId(),n=ne.current;if(!n)return;const r=n.modelLock?.[e]||{enabled:false,keyword:""};if(!r.keyword)return void(r.enabled?(t({modelLock:{...n.modelLock,[e]:{...r,enabled:false}}}),Pi(le("modelLockDisabled"))):(Pi(le("modelLockNoKeyword")),t({modelLock:{...n.modelLock,[e]:{...r,enabled:true}}}),zn(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"siteSettings",subTab:"modelLock"}}));},100)));const o=!r.enabled;t({modelLock:{...n.modelLock,[e]:{...r,enabled:o}}}),Pi(le(o?"modelLockEnabled":"modelLockDisabled"));},[W,zn,t]),wr=q(()=>{if(!W||!e)return false;const t=W.getSiteId();return e.modelLock?.[t]?.enabled||false},[W,e]),Sr=E(()=>{Gt();const e=!J.current;e&&"edge-snap"===ne.current?.panel?.panelMode?(bt||yt(ne.current?.panel?.defaultPosition??"right"),Tt(),Lt()):e||Et(),te(e);},[bt,Et,Gt,Lt,te,Tt]);Lf({settings:e,adapter:W,outlineManager:Z,conversationManager:V,onPanelToggle:Sr,onThemeToggle:ur,onOpenSettings:zn,onOpenGlobalSearch:Hn,isPanelVisible:Y,isSnapped:!!bt&&!kt,onShowSnappedPanel:Mt,onToggleScrollLock:mr});const Cr=$(void 0);L(()=>{const t=e?.panel?.panelMode??"edge-snap";if(void 0!==Cr.current){if(Cr.current!==t)if(Cr.current=t,"edge-snap"===t){const t=e?.panel?.defaultPosition??"right";It(J.current),yt(t),Et();}else yt(null),Et();}else Cr.current=t;},[Et,It,e?.panel?.defaultPosition,e?.panel?.panelMode]);const kr=$(e?.panel?.defaultPosition);L(()=>{const t=e?.panel?.defaultPosition;void 0===kr.current&&t?kr.current=t:t&&kr.current!==t&&(kr.current=t,bt&&(yt(t),Et()));},[bt,Et,e?.panel?.defaultPosition]);const Tr=E(e=>{if(!W||W.getSiteId()!==bo)return;const t="ophel:aistudio-submit-shortcut-sync-toast",n=`synced:${e}`;let r=true;try{sessionStorage.getItem(t)===n?r=!1:sessionStorage.setItem(t,n);}catch{}if(!r)return;const o="ctrlEnter"===e?"Ctrl + Enter":"Enter";Pi(`AI Studio ${le("promptSubmitShortcutLabel")}: ${o}`);},[W]);L(()=>{if(!W||W.getSiteId()!==bo)return;const e=e=>{const t=e.detail;if(t?.forcedByMobile)return;const n=t?.submitShortcut;"enter"!==n&&"ctrlEnter"!==n||Tr(n);};return window.addEventListener(Om,e),()=>{window.removeEventListener(Om,e);}},[W,Tr]),L(()=>{W&&j&&W.getSiteId()===bo&&j.syncAiStudioSubmitShortcut(i);},[W,j,i]),L(()=>{if(!W||!j)return;const e=e=>{if(!e.isTrusted)return;if("Enter"!==e.key)return;if(e.isComposing||229===e.keyCode)return;const t=e.composedPath();if(t.some(e=>e instanceof HTMLElement&&(e.classList?.contains("gh-queue-panel")||e.classList?.contains("gh-queue-input")||e.classList?.contains("gh-queue-item-edit-input"))))return;const n=t.find(e=>e instanceof HTMLElement&&W.isValidTextarea(e));if(!n)return;const r=e.ctrlKey||e.metaKey,o=r||e.altKey;if(W.getSiteId()===bo&&_m()&&!o&&!e.shiftKey)return;const a="ctrlEnter"===i?r&&!e.altKey&&!e.shiftKey:!o&&!e.shiftKey,s="ctrlEnter"===i&&!o&&!e.shiftKey;if(a)return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),void(async()=>{j.syncAiStudioSubmitShortcut(i);await j.submitPrompt(i)&&de(null);})();s&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),(e=>{if(e instanceof HTMLTextAreaElement){const t=e.selectionStart??e.value.length,n=e.selectionEnd??e.value.length;return e.setRangeText("\n",t,n,"end"),void e.dispatchEvent(new Event("input",{bubbles:true}))}if("true"!==e.getAttribute("contenteditable"))return;e.focus();const t={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,shiftKey:true},n=e.innerHTML;e.dispatchEvent(new KeyboardEvent("keydown",t)),e.dispatchEvent(new KeyboardEvent("keypress",t)),e.dispatchEvent(new KeyboardEvent("keyup",t)),e.innerHTML===n&&(document.execCommand("insertLineBreak")||document.execCommand("insertParagraph"),e.dispatchEvent(new Event("input",{bubbles:true})));})(n));};return W.getSiteId()===uo?(window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}):(document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);})},[W,j,i]),L(()=>{if(!W||!ce)return;const e=()=>{de(null);},t=t=>{const n=W.getSubmitButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)try{if(o.matches?.(t))return void setTimeout(e,100)}catch{}}};return document.addEventListener("click",t,true),()=>{document.removeEventListener("click",t,true);}},[W,ce]),L(()=>{if(!ce||!W)return;let e=window.location.href;const t=()=>{de(null),W.clearTextarea();},n=()=>{window.location.href!==e&&t();},r=setInterval(()=>{window.location.href!==e&&(e=window.location.href,t());},500);return window.addEventListener("popstate",n),()=>{clearInterval(r),window.removeEventListener("popstate",n);}},[ce,W]);const[Er,Ar]=_(null),Mr=E(()=>{if(!V||!W)return;const e=W.getSessionId();e?Ar({convId:e}):Pi(le("noConversationToLocate"));},[V,W]),{tags:Ir,addTag:Lr,updateTag:Nr,deleteTag:Rr}=vm(),Dr=E(e=>{Ee("pointer"),Me(t=>({...t,[e]:!t[e]}));},[]),Pr=l({key:"extensionUpdateNoticeKicker",fallback:"Extension updated"}),qr=Ue?c({key:"extensionUpdateNoticeWithVersion",fallback:`${Rf} has been updated to v{version}. Reload this page to keep using the latest version.`},{version:Ue}):l({key:"extensionUpdateNotice",fallback:`${Rf} has been updated. Reload this page to keep using the latest version.`}),Br=l({key:"extensionUpdateNoticeAction",fallback:"Reload page"}),$r=le("close"),_r=Q?le(("outline-copy"===Q.operation?hx:ux)[Q.stage]):"",Or=le("outline-copy"===Q?.operation?"outlineCopyOverlayHint":"exportOverlayHint"),zr=q(()=>({query:l({key:"outlineUserQueryRoleLabel",fallback:"User queries"}),reply:l({key:"globalSearchOutlineReplies",fallback:"Replies"})}),[l]);return W&&j&&V&&Z?De("div",{className:"gh-root "+(re?"gh-pass-through":""),children:[ Re(Hb,{isOpen:Y||Pt,isLauncherPeeking:Pt,launcherPeekAnchorRect:Bt,onClose:()=>{Gt(),Et(),te(false);},promptManager:j,conversationManager:V,outlineManager:Z,adapter:W,onThemeToggle:ur,themeMode:Qn,selectedPromptId:ce?.id,onPromptSelect:Wn,edgeSnapState:bt,isEdgePeeking:kt,onEdgeSnap:e=>yt(e),onUnsnap:()=>{yt(null),Et();},onInteractionStateChange:Kt,onOpenSettings:()=>{zn();},onMouseEnter:Xt,onMouseLeave:Jt}), Re(Qb,{isPanelExpanded:Y,onPanelToggle:Sr,onPanelLogoHoverStart:Zt,onPanelLogoHoverEnd:Yt,onThemeToggle:ur,themeMode:Qn,onExport:fr,onMove:br,onSetTag:Mr,onScrollLock:()=>mr(),onSettings:()=>{zn(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"general",subTab:"toolsMenu"}}));},50);},scrollLocked:sr,onCleanup:()=>{0!==lr?ft(true):Pi(le("floatingToolbarClearGhostEmpty"));},onGlobalSearch:_n,onCopyMarkdown:vr,onModelLockToggle:xr,isModelLocked:wr,onOpenSettings:zn}),ce&&Re(Zb,{title:ce.title,onClear:Gn,adapter:W}), Re(qv,{isOpen:ue,onClose:$n,siteId:W.getSiteId()}), Re(Bv,{isOpen:ge,onClose:()=>{lt(),On();},inputRef:We,resultsRef:Ve,activeOptionId:bn,inputValue:be,inputPlaceholder:g?`${vn.placeholder}(${g})`:vn.placeholder,onInputChange:e=>{N(e),Oe(-1),Se(0);const t=e.trimStart();t.startsWith("tip:")&&"tips"!==me?fe("tips"):t.startsWith("tip:")||"tips"!==me||fe("all");},hotkeyLabel:y,fuzzySearchToggleLabel:l({key:"globalSearchFuzzySearchToggle",fallback:"Fuzzy"}),fuzzySearchToggleAriaLabel:l({key:"globalSearchFuzzySearchToggleAria",fallback:"Toggle fuzzy search"}),isFuzzySearchEnabled:v,onToggleFuzzySearch:I,syntaxHelpTriggerRef:je,syntaxHelpPopoverRef:Ge,showSyntaxHelp:Be,onToggleSyntaxHelp:()=>$e(e=>!e),syntaxHelpTriggerAriaLabel:l({key:"globalSearchSyntaxHelpTriggerAria",fallback:"Open search syntax help"}),syntaxHelpTitle:En,syntaxHelpDescription:An,syntaxHelpItems:Mn,onApplySyntaxHelpItem:Dn,activeFilterChips:Cn,hasOverflowFilterChips:kn,overflowFilterChipText:c({key:"globalSearchSyntaxChipOverflow",fallback:"+{count} more"},{count:String(an.length-4)}),filterChipRemoveTitle:l({key:"globalSearchSyntaxChipRemove",fallback:"Click to remove filter"}),clearFiltersLabel:l({key:"clear",fallback:"Clear"}),onRemoveFilterChip:Pn,onClearAllFilterChips:qn,shouldShowSyntaxSuggestions:Ln,syntaxSuggestions:In,activeSyntaxSuggestionIndex:_e,onHoverSyntaxSuggestion:Oe,onApplySyntaxSuggestion:Rn,syntaxDiagnostics:sn,resolveSyntaxDiagnosticTitle:e=>Tn[e]||Tn.invalidValue,showShortcutNudge:Ie,shortcutNudgeMessage:Pe,closeLabel:l({key:"close",fallback:"Close"}),dismissShortcutNudgeLabel:l({key:"globalSearchShortcutNudgeDismiss",fallback:"Don’t remind me"}),onHideShortcutNudge:R,onDismissShortcutNudgeForever:D,categoriesLabel:l({key:"globalSearchCategoriesLabel",fallback:"Global search categories"}),categories:bx.map(e=>({id:e.id,label:xn[e.id],count:"tips"===e.id&&"tips"!==me?null:hn[e.id]})),activeCategoryId:me,onSelectCategory:e=>{fe(e),Se(0);},activeContext:Bn,listboxId:"settings-search-results-listbox",listboxLabel:Nn,onResultsWheel:()=>{Ee("pointer"),Ze.current=Date.now()+200,lt();},visibleResults:pn,groupedResults:gn,getGroupLabel:e=>wn[e],allCategoryItemLimit:12,isAllCategory:"all"===me,emptyText:vn.emptyText,emptyGuideTitle:l({key:"globalSearchSyntaxEmptyGuideTitle",fallback:"Try search filters"}),emptyGuideDescription:l({key:"globalSearchSyntaxEmptyGuideDesc",fallback:"Use filter syntax to narrow results quickly"}),emptyGuideExamples:[{id:"example:type-prompts",token:"type:prompts",onClick:()=>Rn({id:"example:type-prompts",token:"type:prompts",label:"type:prompts",description:""})},{id:"example:is-pinned",token:"is:pinned",onClick:()=>Rn({id:"example:is-pinned",token:"is:pinned",label:"is:pinned",description:""})},{id:"example:folder-inbox",token:"folder:inbox",onClick:()=>Rn({id:"example:folder-inbox",token:"folder:inbox",label:"folder:inbox",description:""})},{id:"example:tag-work",token:"tag:work",onClick:()=>Rn({id:"example:tag-work",token:"tag:work",label:"tag:work",description:""})},{id:"example:level-0",token:"level:0",onClick:()=>Rn({id:"example:level-0",token:"level:0",label:"level:0",description:""})},{id:"example:date-7d",token:"date:7d",onClick:()=>Rn({id:"example:date-7d",token:"date:7d",label:"date:7d",description:""})}],renderSearchResultItem:(e,t)=>Re(Ov,{item:e,index:t,optionIdPrefix:xx,isActive:t===we,highlightTokens:dn,outlineRoleLabels:zr,matchReasonLabels:Sn,onMouseMove:()=>{Ee("pointer"),Date.now(){Ee("pointer"),ut({item:e,anchorElement:t.currentTarget});},onMouseLeave:()=>{ct();},onClick:()=>Fn(e)},e.id),resolveVisibleResultIndex:(e,t)=>mn.get(e.id)??t,collapseLabel:l({key:"collapse",fallback:"Collapse"}),moreLabel:l({key:"floatingToolbarMore",fallback:"More"}),onToggleCategoryGroup:Dr,footerTips:l({key:"globalSearchFooterTips",fallback:"Enter to jump · ↑↓ to select · Tab category · Esc to close"}),promptPreview:ot&&it?De(Ne,{children:[ Re("div",{ref:Qe,className:"settings-search-prompt-preview-float gh-markdown-preview",style:{top:it.top,left:it.left},onMouseEnter:()=>{at(),st();},onMouseLeave:()=>{ct();},onClick:k,dangerouslySetInnerHTML:{__html:Ad($l(ot.content,false))}}), Re("style",{children:_l()})]}):void 0}),gt&&Re(Jf,{folders:V.getFolders(),excludeFolderId:V.getConversation(gt.convId)?.folderId,activeFolderId:gt.activeFolderId,onSelect:async e=>{await V.moveConversation(gt.convId,e),pt(null);},onCancel:()=>pt(null)}),Er&&Re(eb,{tags:Ir,conv:V.getConversation(Er.convId),onCancel:()=>Ar(null),onCreateTag:async(e,t)=>Lr(e,t),onUpdateTag:async(e,t,n)=>Nr(e,t,n),onDeleteTag:async e=>{Rr(e);},onSetConversationTags:async(e,t)=>{await V.updateConversation(e,{tagIds:t});},onRefresh:()=>{}}),mt&&Re(Zf,{title:le("floatingToolbarClearGhost"),message:le("floatingToolbarClearGhostConfirm").replace("{count}",String(lr)),danger:true,onConfirm:()=>{ft(false),yr();},onCancel:()=>ft(false)}),W&&G&&(e?.features?.prompts?.promptQueue??false)&&Re(Wb,{adapter:W,dispatcher:G}), Re(rb,{isVisible:Boolean(Q),text:_r,hint:Or,tone:"export",blockPageInteraction:true}),ze&&De("section",{className:"gh-update-notice gh-interactive",role:"status","aria-live":"polite",children:[ Re("button",{type:"button",className:"gh-update-notice-close","aria-label":$r,onClick:gr,children:De("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ Re("path",{d:"M18 6 6 18"}), Re("path",{d:"m6 6 12 12"})]})}), De("div",{className:"gh-update-notice-kicker",children:[ Re("svg",{className:"gh-update-notice-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Re("path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"})}),Pr]}), Re("p",{className:"gh-update-notice-message",children:qr}), Re("div",{className:"gh-update-notice-actions",children:Re("button",{type:"button",className:"gh-update-notice-button gh-update-notice-button--primary",onClick:pr,children:Br})})]}), Re(nb,{})]}):null}},Symbol.toStringTag,{value:"Module"})),Ex="[GeminiMyStuffBridge]",Ax=[1,1,1,0,0,0,1,0],Mx=[1,1,1,1,1,0,1,0],Ix={"x-same-domain":"1","x-goog-ext-525001261-jspb":"[1,null,null,null,null,null,null,null,[4]]","x-goog-ext-73010989-jspb":"[]"};let Lx=false;const Nx=new Map,Rx=new Map;function Dx(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function Px(e=window.location.pathname){return e.replace(/^\/u\/\d+/,"")}function qx(e){return "document"===e?Mx:Ax}function Bx(e){let t=Nx.get(e);return t||(t=new Map,Nx.set(e,t)),t}function $x(e){return "string"==typeof e&&/^boq_assistant-bard-web-server_/i.test(e)}function _x(e){return "string"==typeof e&&/^\d{10,}$/.test(e)}function Ox(e){return "string"==typeof e&&/^[A-Za-z0-9._:-]+:\d{13}$/.test(e)}function zx(e,t){for(const n of Object.values(e))if("string"==typeof n&&t(n))return n;return null}function Fx(e,t){const n=e.match(t);return n?.[1]||n?.[0]||null}function Ux(){const e=Dx(),t=e.WIZ_global_data||{},n=document.querySelector('script[data-id="_gd"]')?.textContent||"",r=($x(t.cfb2h)?t.cfb2h:null)||zx(t,$x)||Fx(n,/"cfb2h":"([^"]+)"/)||Fx(n,/boq_assistant-bard-web-server_[^"]+/),o=(_x(t.FdrFJe)?t.FdrFJe:null)||zx(t,_x)||Fx(n,/"FdrFJe":"([^"]+)"/)||Fx(n,/"\d{10,}"/)?.replace(/"/g,"")||null,i=(Ox(t.SNlM0e)?t.SNlM0e:null)||zx(t,Ox)||Fx(n,/"SNlM0e":"([^"]+)"/)||Fx(n,/[A-Za-z0-9._:-]+:\d{13}/)||null;return $x(r)&&_x(o)&&Ox(i)?{bl:r,fSid:o,at:i,hl:document.documentElement.lang||navigator.language||"zh-CN"}:(console.warn(`${Ex} failed to resolve runtime tokens`,{hasGlobalData:Boolean(e.WIZ_global_data),bl:r,fSid:o,at:i}),null)}function Hx(e){const t=new URL("/_/BardChatUi/data/batchexecute",window.location.origin);return t.searchParams.set("rpcids","jGArJ"),t.searchParams.set("source-path",Px()),t.searchParams.set("bl",e.bl),t.searchParams.set("f.sid",e.fSid),t.searchParams.set("hl",e.hl),t.searchParams.set("_reqid",String(Date.now()%1e6)),t.searchParams.set("rt","c"),t.toString()}function Wx(e,t,n){const r=new URLSearchParams,o=n?[qx(t),30,n]:[qx(t),30];return r.set("f.req",JSON.stringify([[["jGArJ",JSON.stringify(o),null,"generic"]]])),r.set("at",e.at),r.toString()}function jx(e,t){const n=e.replace(/^\)\]\}'\s*\n\s*\n/,"").split("\n").map(e=>e.trim()).filter(Boolean);if(n.length<2)throw new Error("mystuff-response-lines-missing");const r=JSON.parse(n[1]),o=Array.isArray(r)?r[0]:null,i=Array.isArray(o)&&"string"==typeof o[2]?o[2]:null;if(!i)throw new Error("mystuff-payload-missing");const a=JSON.parse(i);return {items:(Array.isArray(a[0])?a[0]:[]).map(e=>function(e,t){if(!Array.isArray(t)||t.length<3)return null;const n=Array.isArray(t[0])?t[0]:[];if(n.length<2||"string"!=typeof n[0]||"string"!=typeof n[1])return null;const r=Array.isArray(t[1])?t[1]:[],o=Array.isArray(t[4])?t[4]:[];return {kind:e,conversationId:n[0],responseId:n[1],timestamp:"number"==typeof r[0]?r[0]:0,timestampNano:"number"==typeof r[1]?r[1]:0,status:"number"==typeof t[2]?t[2]:0,title:"string"==typeof t[3]&&t[3].trim()?t[3].trim():void 0,thumbnailUrl:"string"==typeof o[1]&&o[1]?o[1]:void 0,resourceId:"string"==typeof t[5]&&t[5]?t[5]:void 0}}(t,e)).filter(e=>null!==e),nextPageToken:"string"==typeof a[1]&&a[1]?a[1]:null}}function Gx(e){return e.flatMap(e=>Array.from(Bx(e).values()))}function Vx(e){window.postMessage({type:xd,payload:e},"*"),window.dispatchEvent(new CustomEvent(xd,{detail:e}));}async function Qx(e){if(!e?.requestId||!function(e=window.location.pathname){const t=Px(e);return "/mystuff"===t||"/mystuff/"===t||t.startsWith("/mystuff/")||"/library"===t||"/library/"===t||t.startsWith("/library/")}())return;const t=function(e){return Array.isArray(e)&&0!==e.length?Array.from(new Set(e.filter(e=>"media"===e||"document"===e))):["media","document"]}(e.kinds),n=e.force||t.some(e=>0===Bx(e).size);try{n&&await Promise.all(t.map(t=>async function(e,t){const n=Bx(e);if(!t&&n.size>0)return Array.from(n.values());const r=Rx.get(e);if(r)return r;const o=(async()=>{const t=new Map;let r;for(let n=0;n<80;n+=1){const o=Ux();if(!o)throw new Error("mystuff-runtime-tokens-missing");const i=await Dx().fetch(Hx(o),{method:"POST",credentials:"include",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",...Ix},body:Wx(o,e,r)}),a=await i.text();if(!i.ok)throw console.warn(`${Ex} fetch failed`,{kind:e,page:n,status:i.status,preview:a.slice(0,240)}),new Error(`mystuff-fetch-failed:${i.status}`);const s=jx(a,e);if(s.items.forEach(e=>{return t.set(`${(n=e).conversationId}:${n.responseId}`,e);var n;}),console.info(`${Ex} fetched page`,{kind:e,page:n,itemCount:s.items.length,nextPageToken:s.nextPageToken}),!s.nextPageToken)break;r=s.nextPageToken;}return n.clear(),t.forEach((e,t)=>n.set(t,e)),Array.from(n.values())})();Rx.set(e,o);try{return await o}finally{Rx.delete(e);}}(t,Boolean(e.force))));const r=Gx(t);Vx({requestId:e.requestId,items:r,kinds:t,reason:n?"sync":"snapshot",timestamp:Date.now()});}catch(RS){console.warn(`${Ex} sync request failed`,{requestId:e.requestId,kinds:t,error:RS}),Vx({requestId:e.requestId,items:Gx(t),kinds:t,reason:"snapshot",timestamp:Date.now()});}}function Kx(){Lx||"gemini.google.com"!==window.location.hostname||(Lx=true,window.addEventListener("message",e=>{e.data?.type===vd&&Qx(e.data.payload);}),window.addEventListener(vd,e=>{Qx(e.detail);}),console.info(`${Ex} initialized`));}function Zx(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}class Yx{urlPatterns;urlPathEndsWith;silenceThreshold;requestBodyRules;onComplete;onStart;domValidation;_activeCount=0;_silenceTimer=null;_isMonitoring=false;_originalFetch=null;_originalXhrOpen=null;_originalXhrSend=null;_lastUrl="";_hasTriggeredStart=false;_boundHookedFetch;constructor(e={}){this.urlPatterns=e.urlPatterns||[],this.urlPathEndsWith=e.urlPathEndsWith||[],this.silenceThreshold=e.silenceThreshold||3e3,this.requestBodyRules=e.requestBodyRules||[],this.onComplete=e.onComplete||(()=>{}),this.onStart=e.onStart||null,this.domValidation=e.domValidation||null,this._boundHookedFetch=this._hookedFetch.bind(this);}start(){if(this._isMonitoring)return;const e=Zx();this._originalFetch=e.fetch,e.fetch=this._boundHookedFetch,this._hookXHR(),this._isMonitoring=true;}stop(){if(!this._isMonitoring)return;const e=Zx();this._originalFetch&&(e.fetch=this._originalFetch,this._originalFetch=null),this._unhookXHR(),this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),this._isMonitoring=false,this._activeCount=0,this._hasTriggeredStart=false;}_isTargetUrl(e){if(!e)return false;if(!(0===this.urlPatterns.length||this.urlPatterns.some(t=>e.includes(t))))return false;if(0===this.urlPathEndsWith.length)return true;try{const t=new URL(e,window.location.origin).pathname;return this.urlPathEndsWith.some(e=>t.endsWith(e))}catch{return this.urlPathEndsWith.some(t=>e.endsWith(t))}}_tryTriggerComplete(){if(this._activeCount>0)return;const e={activeCount:this._activeCount,lastUrl:this._lastUrl,timestamp:Date.now()};if(this.domValidation)try{if(!this.domValidation(e))return void(this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),1e3))}catch(t){console.error(t);}this._hasTriggeredStart=false;try{this.onComplete(e);}catch(t){console.error(t);}}async _hookedFetch(...e){const t=Zx(),n=this._extractFetchUrl(e);if(!this._isTargetUrl(n))return this._originalFetch.call(t,...e);if(this._activeCount++,this._lastUrl=n,this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),!this._hasTriggeredStart&&this.onStart){this._hasTriggeredStart=true;try{const t=await this._extractFetchRequestMetadata(e);this.onStart({url:n,timestamp:Date.now(),type:"fetch",...t});}catch{}}try{const n=await this._originalFetch.call(t,...e),r=n.clone();return this._readStream(r).catch(()=>{}),n}catch(RS){throw this._decrementAndSchedule(),RS}}async _readStream(e){try{if(!e.body)return;const t=e.body.getReader();for(;;){const{done:e}=await t.read();if(e)break}}catch{}finally{this._decrementAndSchedule();}}_decrementAndSchedule(){this._activeCount=Math.max(0,this._activeCount-1),this._silenceTimer&&clearTimeout(this._silenceTimer),this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),this.silenceThreshold);}_hookXHR(){const e=this,t=Zx().XMLHttpRequest;this._originalXhrOpen=t.prototype.open,this._originalXhrSend=t.prototype.send,t.prototype.open=function(t,n,...r){return this._networkMonitorUrl=n?n.toString():"",e._originalXhrOpen.call(this,t,n,...r)},t.prototype.send=function(t){const n=this._networkMonitorUrl||"";if(!e._isTargetUrl(n))return e._originalXhrSend.call(this,t);if(e._activeCount++,e._lastUrl=n,e._silenceTimer&&(clearTimeout(e._silenceTimer),e._silenceTimer=null),!e._hasTriggeredStart&&e.onStart){e._hasTriggeredStart=true;try{const r=e._extractRequestMetadata(t);e.onStart({url:n,timestamp:Date.now(),type:"xhr",...r});}catch{}}const r=()=>{e._decrementAndSchedule();};return this.addEventListener("load",r),this.addEventListener("error",r),this.addEventListener("abort",r),this.addEventListener("timeout",r),e._originalXhrSend.call(this,t)};}_unhookXHR(){const e=Zx().XMLHttpRequest;this._originalXhrOpen&&(e.prototype.open=this._originalXhrOpen,this._originalXhrOpen=null),this._originalXhrSend&&(e.prototype.send=this._originalXhrSend,this._originalXhrSend=null);}_extractFetchUrl(e){const t=e[0];return t?"string"==typeof t?t:t instanceof URL?t.toString():"object"==typeof t&&"string"==typeof t.url?t.url:"function"==typeof t.toString?t.toString():"":""}async _extractFetchRequestMetadata(e){if(0===this.requestBodyRules.length)return {};const t=await this._bodyToText(e[1]?.body);if(null!==t)return this._extractRequestMetadata(t);const n=e[0];if(n&&"object"==typeof n&&"function"==typeof n.clone&&"function"==typeof n.text)try{const e=n.clone();if(e&&"function"==typeof e.text){const t=await e.text();return this._extractRequestMetadata(t)}}catch{}return {}}async _bodyToText(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e)return null;const t=Object.prototype.toString.call(e);if("[object URLSearchParams]"===t)return "function"==typeof e.toString?e.toString():null;if("[object Blob]"===t&&"function"==typeof e.text)try{return await e.text()}catch{return null}if(ArrayBuffer.isView(e))try{return (new TextDecoder).decode(e)}catch{return null}if(e instanceof ArrayBuffer)try{return (new TextDecoder).decode(e)}catch{return null}return null}_extractRequestMetadata(e){if("string"!=typeof e||0===e.trim().length||0===this.requestBodyRules.length)return {};try{const t=JSON.parse(e),n={};for(const e of this.requestBodyRules)"json-field-exists"===e.type&&void 0!==t[e.field]&&Object.assign(n,e.metadata);return {...n}}catch{return {}}}}let Xx=null,Jx=false;const ew=Object.freeze(Object.defineProperty({__proto__:null,initNetworkMonitor:function(){Jx||(Jx=true,Kx(),window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==fd&&t!==yd&&t!==bd||t===fd&&(Xx&&Xx.stop(),Xx=new Yx({urlPatterns:n?.urlPatterns,urlPathEndsWith:n?.urlPathEndsWith,silenceThreshold:n?.silenceThreshold,requestBodyRules:n?.requestBodyRules,onStart:e=>window.postMessage({type:bd,payload:e},"*"),onComplete:e=>window.postMessage({type:yd,payload:e},"*")}),Xx.start());}));}},Symbol.toStringTag,{value:"Module"}));let tw=false,nw=null,rw=false;function ow(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function iw(){const e=ow().document.documentElement?.getAttribute(qa)?.trim();return e||null}function aw(e){const t=e.trim();if(!t)return;const n=ow(),r=n.document.documentElement;r?.setAttribute(Ba,t),r?.setAttribute($a,n.location.pathname);}function sw(){if(rw)return;const e=ow(),t=e.document,n=iw();n&&t.title!==n&&(aw(t.title),rw=true,t.title=n,e.queueMicrotask(()=>{rw=false;}));}const lw=Object.freeze(Object.defineProperty({__proto__:null,initGeminiTitleGuard:function(){tw||"gemini.google.com"!==ow().location.hostname||(tw=true,function(){const e=ow(),t=[e.Document.prototype,e.HTMLDocument.prototype].find(e=>Object.prototype.hasOwnProperty.call(e,"title"))||e.Document.prototype,n=Object.getOwnPropertyDescriptor(t,"title");n?.get&&n?.set&&false!==n.configurable&&Object.defineProperty(t,"title",{configurable:true,enumerable:n.enumerable,get(){return n.get?.call(this)??""},set(t){const r=String(t??"");if(this===e.document){const e=iw();if(e&&r!==e)return aw(r),void n.set?.call(this,e)}this===e.document&&r!==iw()&&aw(r),n.set?.call(this,r);}});}(),function(){const e=ow(),t=e.document;if(nw||void 0===e.MutationObserver)return;nw=new e.MutationObserver(()=>{rw||sw();});const n=()=>{t.head&&nw?.observe(t.head,{childList:true,subtree:true,characterData:true});};n(),t.head||t.addEventListener("DOMContentLoaded",n,{once:true}),t.documentElement&&nw.observe(t.documentElement,{attributes:true,attributeFilter:[qa]});}(),sw());}},Symbol.toStringTag,{value:"Module"})),cw="gh-assistant-mermaid-style",dw=".gh-assistant-mermaid",uw="data-ophel-assistant-mermaid-managed",hw="data-ophel-assistant-mermaid-original-display",gw="data-ophel-assistant-mermaid-preview-id",pw="data-ophel-assistant-mermaid-render-token",mw="data-ophel-assistant-mermaid-fullscreen",fw="data-ophel-assistant-mermaid-restore-zoom",bw="data-ophel-assistant-mermaid-fullscreen-max-zoom",yw="OPHEL_ASSISTANT_MERMAID_RENDER_RESPONSE",vw="http://www.w3.org/2000/svg";function xw(e){{const t=window.__OPHEL_USERSCRIPT_ASSET_URLS__?.[e];return "string"==typeof t&&t.length>0?t:null}}function ww(){return "1"===document.documentElement.getAttribute("data-ophel-assistant-mermaid-runner")}function Sw(e,t){const n=e.createElementNS(vw,"svg");return n.setAttribute("viewBox",t),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.classList.add("gh-assistant-mermaid-btn-icon"),n}class Cw{adapter;enabled;stopWatch=null;rescanTimer=null;clickHandler=null;messageHandler=null;fullscreenChangeHandler=null;runtimePromise=null;processedBlocks=new WeakMap;blockPanels=new WeakMap;panelBlocks=new WeakMap;injectedRoots=new WeakSet;pendingRequests=new Map;previewIdCounter=0;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(window.clearInterval(this.rescanTimer),this.rescanTimer=null),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.fullscreenChangeHandler&&(document.removeEventListener("fullscreenchange",this.fullscreenChangeHandler),document.removeEventListener("webkitfullscreenchange",this.fullscreenChangeHandler),this.fullscreenChangeHandler=null);for(const e of this.pendingRequests.values())window.clearTimeout(e.timeoutId),e.reject(new Error("Assistant Mermaid renderer stopped"));this.pendingRequests.clear(),this.processedBlocks=new WeakMap,this.blockPanels=new WeakMap,this.panelBlocks=new WeakMap,this.cleanupInjectedPanels();}refreshLocalizedTexts(){ds.query(dw,{all:true,shadow:true}).forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector("[data-mermaid-action='preview']"),n=e.querySelector("[data-mermaid-action='code']"),r=e.querySelector("[data-mermaid-action='copy']"),o=e.querySelector("[data-mermaid-action='download']"),i=e.querySelector("[data-mermaid-action='zoom-reset']"),a=e.querySelector("[data-mermaid-action='zoom-out']"),s=e.querySelector("[data-mermaid-action='zoom-in']"),l=e.querySelector("[data-mermaid-action='fullscreen']");t&&(t.textContent=le("assistantMermaidPreviewTab")),n&&(n.textContent=le("assistantMermaidCodeTab")),r&&(r.textContent=le("assistantMermaidCopyCode")),o&&(o.textContent=le("assistantMermaidDownloadPng")),i&&this.configureZoomResetButton(i),a&&this.configureZoomOutButton(a),s&&this.configureZoomInButton(s),l&&this.configureFullscreenButton(l);});}init(){if("fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const e=this.getAssistantSelector();e&&(this.injectStyles(document),this.initClickHandler(),this.initMessageHandler(),this.initFullscreenChangeHandler(),this.stopWatch=ds.each(e,e=>{this.processResponseElement(e);},{shadow:true}),this.startRescanTimer());}getAssistantSelector(){return this.adapter.getExportConfig()?.assistantResponseSelector||null}initClickHandler(){this.clickHandler||(this.clickHandler=e=>{const t=e.composedPath(),n=t.find(e=>e instanceof HTMLElement&&e.hasAttribute("data-mermaid-action"))||e.target?.closest("[data-mermaid-action]");if(!n)return;const r=t.find(e=>e instanceof HTMLElement&&e.matches(dw))||n.closest(dw);if(!r)return;const o=this.panelBlocks.get(r);if(!o)return;e.preventDefault(),e.stopPropagation();const i=n.dataset.mermaidAction;"preview"!==i&&"code"!==i?"zoom-in"!==i&&"zoom-out"!==i&&"zoom-reset"!==i?"fullscreen"!==i?"copy"!==i?"download"===i&&this.downloadMermaidPng(r).catch(e=>{console.error("[AssistantMermaidRenderer] PNG download failed:",e),Pi(le("assistantMermaidDownloadFailed"),2e3);}):this.copyMermaidSource(r).catch(e=>{console.error("[AssistantMermaidRenderer] Copy failed:",e);}):this.togglePreviewFullscreen(r).catch(e=>{console.error("[AssistantMermaidRenderer] Fullscreen failed:",e),Pi(le("assistantMermaidFullscreenFailed"),2e3);}):this.adjustPreviewZoom(r,i):this.setView(o,r,i);},document.addEventListener("click",this.clickHandler,true));}initMessageHandler(){this.messageHandler||(this.messageHandler=e=>{const t=e.data;if(e.source!==window&&t?.type!==yw)return;if(t?.type!==yw)return;const n="string"==typeof t.requestId?t.requestId:"";if(!n)return;const r=this.pendingRequests.get(n);r&&(window.clearTimeout(r.timeoutId),this.pendingRequests.delete(n),t.success?r.resolve():r.reject(new Error(t.error||"Mermaid render failed")));},window.addEventListener("message",this.messageHandler));}initFullscreenChangeHandler(){this.fullscreenChangeHandler||(this.fullscreenChangeHandler=()=>{const e=ds.query(`${dw}[${mw}='1']`,{shadow:true});if(!e)return;const t=e.querySelector(".gh-assistant-mermaid-preview");t?document.fullscreenElement!==t?this.restorePreviewZoomAfterFullscreen(e):this.fitPreviewToFullscreen(e,t):this.clearFullscreenState(e);},document.addEventListener("fullscreenchange",this.fullscreenChangeHandler),document.addEventListener("webkitfullscreenchange",this.fullscreenChangeHandler));}startRescanTimer(){this.rescanTimer||(window.setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.getAssistantSelector();if(!e)return;const t=ds.query(e,{all:true,shadow:true});for(const n of t)this.processResponseElement(n);}processResponseElement(e){if(!this.enabled||"fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const t=e.getRootNode();t instanceof ShadowRoot&&this.injectStyles(t);this.adapter.getAssistantMermaidBlocks(e).forEach(({element:e,source:t})=>{this.processMermaidBlock(e,t);});}async processMermaidBlock(e,t){if(!e.isConnected)return;const n=e.getRootNode();n instanceof ShadowRoot&&this.injectStyles(n);const r=ms(t);if(!r)return;const o=this.getMermaidTheme(),i=`${o}::${r}`;if(this.processedBlocks.get(e)===i)return;const a=this.ensurePanel(e),s=a.querySelector(".gh-assistant-mermaid-preview");if(!s)return;const l=a.dataset.view||"preview",c=this.ensurePreviewId(s),d=this.createRequestId();s.setAttribute(pw,d);try{if(await this.ensureRuntime(),await this.requestRender(d,c,r,o),!e.isConnected)return;if(!a.isConnected||!s.isConnected)return;if(s.getAttribute(pw)!==d)return;a.hidden=!1,a.dataset.source=r,this.setPreviewEnabled(a,!0),this.setDownloadEnabled(a,!0),this.setZoomEnabled(a,!0),this.applyPreviewZoom(a,1),this.processedBlocks.set(e,i),this.setView(e,a,l);}catch(RS){if(!e.isConnected||!a.isConnected||!s.isConnected||s.getAttribute(pw)!==d)return;console.warn("[AssistantMermaidRenderer] Mermaid render skipped:",RS),!function(e){const t=e instanceof Error?e.message:String(e);return ["runtime asset url is unavailable","failed to load script","runner did not initialize","runtime is unavailable","render timed out","preview container not found"].some(e=>t.toLowerCase().includes(e))}(RS)?(this.processedBlocks.set(e,i),this.applyRenderFallback(e,a,r)):(this.processedBlocks.delete(e),this.cleanupPanel(e));}}ensurePanel(e){const t=this.blockPanels.get(e)||(e.previousElementSibling?.matches?.(dw)?e.previousElementSibling:null);if(t?.isConnected)return this.blockPanels.set(e,t),this.panelBlocks.set(t,e),t;const n=document.createElement("div");n.className="gh-assistant-mermaid",n.hidden=true;const r=document.createElement("div");r.className="gh-assistant-mermaid-toolbar";const o=document.createElement("div");o.className="gh-assistant-mermaid-toolbar-group";const i=document.createElement("div");i.className="gh-assistant-mermaid-actions";const a=document.createElement("button");a.type="button",a.className="gh-assistant-mermaid-btn",a.dataset.mermaidAction="preview",a.textContent=le("assistantMermaidPreviewTab");const s=document.createElement("button");s.type="button",s.className="gh-assistant-mermaid-btn",s.dataset.mermaidAction="code",s.textContent=le("assistantMermaidCodeTab");const l=document.createElement("button");l.type="button",l.className="gh-assistant-mermaid-btn",l.dataset.mermaidAction="copy",l.textContent=le("assistantMermaidCopyCode");const c=document.createElement("button");c.type="button",c.className="gh-assistant-mermaid-btn",c.dataset.mermaidAction="download",c.textContent=le("assistantMermaidDownloadPng");const d=document.createElement("div");d.className="gh-assistant-mermaid-toolbar-group";const u=document.createElement("div");u.className="gh-assistant-mermaid-zoom";const h=document.createElement("button");h.type="button",h.className="gh-assistant-mermaid-btn is-icon",h.dataset.mermaidAction="zoom-out",this.configureZoomOutButton(h);const g=document.createElement("button");g.type="button",g.className="gh-assistant-mermaid-btn is-icon",g.dataset.mermaidAction="zoom-reset",this.configureZoomResetButton(g);const p=document.createElement("button");p.type="button",p.className="gh-assistant-mermaid-btn is-icon",p.dataset.mermaidAction="zoom-in",this.configureZoomInButton(p);const m=document.createElement("button");m.type="button",m.className="gh-assistant-mermaid-btn is-icon",m.dataset.mermaidAction="fullscreen",this.configureFullscreenButton(m),u.append(h,g,p,m),o.append(i,u),i.append(a,s),d.append(c,l),r.append(o,d);const f=document.createElement("div");return f.className="gh-assistant-mermaid-preview",this.ensurePreviewId(f),n.append(r,f),e.before(n),e.setAttribute(uw,"true"),e.hasAttribute(hw)||e.setAttribute(hw,e.style.display||""),this.blockPanels.set(e,n),this.panelBlocks.set(n,e),n}configureZoomResetButton(e){const t=le("assistantMermaidFitToPage");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=Sw(e,"0 0 24 24"),n=e.createElementNS(vw,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M9 3a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v4.5a1 1 0 0 0 2 0V4h4a1 1 0 0 0 1-1m6 0a1 1 0 0 1 1-1h4a2 2 0 0 1 2 2v4.5a1 1 0 1 1-2 0V4h-4a1 1 0 0 1-1-1m1 19a1 1 0 1 1 0-2h4v-4.5a1 1 0 1 1 2 0V20a2 2 0 0 1-2 2zm-7-1a1 1 0 0 1-1 1H4a2 2 0 0 1-2-2v-4.5a1 1 0 1 1 2 0V20h4a1 1 0 0 1 1 1M8 10h8v4H8zm-2 0a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomOutButton(e){const t=le("assistantMermaidZoomOut");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=Sw(e,"0 0 24 24"),n=e.createElementNS(vw,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M10.5 17a6.5 6.5 0 1 0 0-13 6.5 6.5 0 0 0 0 13m0 2a8.46 8.46 0 0 0 5.263-1.825l.03.032 5 5a1 1 0 0 0 1.414-1.414l-5-5-.032-.03A8.5 8.5 0 1 0 10.5 19M8 9.5a1 1 0 0 0 0 2h5a1 1 0 1 0 0-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomInButton(e){const t=le("assistantMermaidZoomIn");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=Sw(e,"0 0 24 24"),n=e.createElementNS(vw,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M17 10.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0m-1.237 6.675a8.5 8.5 0 1 1 1.413-1.413l.031.03 5 5a1 1 0 0 1-1.414 1.415l-5-5zM7 10.5a1 1 0 0 1 1-1h1.5V8a1 1 0 0 1 2 0v1.5H13a1 1 0 1 1 0 2h-1.5V13a1 1 0 1 1-2 0v-1.5H8a1 1 0 0 1-1-1"),t.appendChild(n),t}(e.ownerDocument||document));}configureFullscreenButton(e){const t=le("assistantMermaidFullscreen");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=Sw(e,"0 0 24 24"),n=e.createElementNS(vw,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("d","M22 3v7a1 1 0 1 1-2 0V4h-6a1 1 0 1 1 0-2h7a1 1 0 0 1 1 1M11.005 21a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-7a1 1 0 0 1 2.002 0v6h6.003a1 1 0 0 1 1 1"),t.appendChild(n),t}(e.ownerDocument||document));}ensurePreviewId(e){const t=e.getAttribute(gw);if(t)return t;this.previewIdCounter+=1;const n=`gh-assistant-mermaid-preview-${Date.now()}-${this.previewIdCounter}`;return e.setAttribute(gw,n),n}setView(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");if(!r)return;t.dataset.view=n,r.hidden="preview"!==n,e.style.display="preview"===n?"none":e.getAttribute(hw)||"";t.querySelectorAll("[data-mermaid-action='preview'], [data-mermaid-action='code']").forEach(e=>{e instanceof HTMLElement&&e.classList.toggle("is-active",e.dataset.mermaidAction===n);});}setPreviewEnabled(e,t){const n=e.querySelector("[data-mermaid-action='preview']");n&&(n.disabled=!t);}setZoomEnabled(e,t){e.querySelectorAll("[data-mermaid-action='zoom-out'], [data-mermaid-action='zoom-reset'], [data-mermaid-action='zoom-in'], [data-mermaid-action='fullscreen']").forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}setDownloadEnabled(e,t){const n=e.querySelector("[data-mermaid-action='download']");n&&(n.disabled=!t);}adjustPreviewZoom(e,t){const n=Number.parseFloat(e.dataset.zoom||"1");if("zoom-reset"===t)return void this.applyPreviewZoom(e,1);const r="zoom-in"===t?n+.25:n-.25;this.applyPreviewZoom(e,r);}applyPreviewZoom(e,t){const n=e.querySelector(".gh-assistant-mermaid-preview"),r=n?.querySelector("svg");if(!n||!r)return void this.setZoomEnabled(e,false);const o=Math.min(this.getMaxPreviewZoom(e),Math.max(.5,t));e.dataset.zoom=`${o}`;const i=this.getPreviewBaseWidth(r);r.style.maxWidth="none",r.style.width=`${Math.max(1,Math.round(i*o))}px`,r.style.height="auto",this.updateZoomButtonState(e,o);}getMaxPreviewZoom(e){const t=Number.parseFloat(e.getAttribute(bw)||"");return Math.max(3,Number.isFinite(t)?t:0)}getPreviewBaseWidth(e){const t=Number.parseFloat(e.dataset.ophelBaseWidth||"");if(Number.isFinite(t)&&t>0)return t;const n=e.getBoundingClientRect().width,r=Number.parseFloat(e.getAttribute("width")||"")||e.viewBox?.baseVal?.width||320,o=n>0?n:r;return e.dataset.ophelBaseWidth=`${o}`,o}getPreviewBaseDimensions(e){const t=this.getPreviewBaseWidth(e),n=e.getBoundingClientRect(),r=Number.parseFloat(e.getAttribute("width")||""),o=Number.parseFloat(e.getAttribute("height")||""),i=e.viewBox?.baseVal?.width||0,a=e.viewBox?.baseVal?.height||0;return {width:t,height:t*(i>0&&a>0&&a/i||n.width>0&&n.height>0&&n.height/n.width||r>0&&o>0&&o/r||.75)}}updateZoomButtonState(e,t){const n=e.querySelector("[data-mermaid-action='zoom-out']"),r=e.querySelector("[data-mermaid-action='zoom-reset']"),o=e.querySelector("[data-mermaid-action='zoom-in']"),i=this.getMaxPreviewZoom(e);n&&(n.disabled=t<=.5),r&&(r.disabled=Math.abs(t-1)<.001),o&&(o.disabled=t>=i);}applyRenderFallback(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");r&&r.replaceChildren(),t.hidden=false,t.dataset.source=n,this.setPreviewEnabled(t,false),this.setDownloadEnabled(t,false),this.setZoomEnabled(t,false),this.setView(e,t,"code");}async togglePreviewFullscreen(e){const t=e.querySelector(".gh-assistant-mermaid-preview");if(!t)throw new Error("Mermaid preview container not found");const n=this.panelBlocks.get(e);if(n&&"preview"!==e.dataset.view&&this.setView(n,e,"preview"),document.fullscreenElement!==t){if("function"!=typeof t.requestFullscreen)throw new Error("Fullscreen API is unavailable");e.setAttribute(mw,"1"),e.setAttribute(fw,e.dataset.zoom||"1");try{await t.requestFullscreen();}catch(RS){throw this.clearFullscreenState(e),RS}}else await document.exitFullscreen();}fitPreviewToFullscreen(e,t){const n=t.querySelector("svg");if(!n)return void this.setZoomEnabled(e,false);const{width:r,height:o}=this.getPreviewBaseDimensions(n);if(r<=0||o<=0)return;const i=Math.max(1,t.clientWidth-48),a=Math.max(1,t.clientHeight-48),s=Math.min(i/r,a/o);e.setAttribute(bw,`${Math.max(3,s)}`),this.applyPreviewZoom(e,s),t.scrollTop=0,t.scrollLeft=0;}restorePreviewZoomAfterFullscreen(e){const t=Number.parseFloat(e.getAttribute(fw)||"")||1;this.clearFullscreenState(e),this.applyPreviewZoom(e,t);}clearFullscreenState(e){e.removeAttribute(mw),e.removeAttribute(fw),e.removeAttribute(bw);}async copyMermaidSource(e){const t=e.dataset.source||"";t&&(await navigator.clipboard.writeText(t),Pi(le("copySuccess"),1500));}async downloadMermaidPng(e){const t=e.querySelector(".gh-assistant-mermaid-preview"),n=t?.querySelector("svg");if(!n)throw new Error("Mermaid preview svg not found");const{width:r,height:o}=this.getSvgExportDimensions(n),i=Math.max(1,Math.round(r)),a=Math.max(1,Math.round(o));let s;try{s=await this.renderSvgToPngBlob(n,i,a);}catch(RS){if(!n.querySelector("foreignObject")||!function(e){const t=e instanceof Error?e.message:String(e),n=e instanceof DOMException||e instanceof Error?e.name:"",r=t.toLowerCase();return n.toLowerCase().includes("securityerror")||r.includes("tainted canvas")||r.includes("tainted canvases may not be exported")}(RS))throw RS;s=await this.renderSvgToPngBlob(n,i,a,{downgradeForeignObjects:true});}const l=URL.createObjectURL(s);try{const e=document.createElement("a");e.href=l,e.download=this.createPngFilename(),e.click();}finally{URL.revokeObjectURL(l);}Pi(le("assistantMermaidDownloadSuccess"),1500);}getSvgExportDimensions(e){const t=e.getBoundingClientRect(),n=Number.parseFloat(e.style.width||""),r=Number.parseFloat(e.style.height||""),o=Number.parseFloat(e.getAttribute("width")||""),i=Number.parseFloat(e.getAttribute("height")||""),a=e.viewBox?.baseVal?.width||0,s=e.viewBox?.baseVal?.height||0,l=t.width||n||o||this.getPreviewBaseWidth(e)||a||320;return {width:l,height:l*(t.width>0&&t.height>0&&t.height/t.width||n>0&&r>0&&r/n||o>0&&i>0&&i/o||a>0&&s>0&&s/a||.75)}}serializeSvgForPng(e,t,n,r={}){const o=e.cloneNode(true);return o.setAttribute("xmlns",vw),o.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.style.width=`${t}px`,o.style.height=`${n}px`,o.style.maxWidth="none",r.downgradeForeignObjects&&this.downgradeForeignObjectsForPng(e,o),(new XMLSerializer).serializeToString(o)}async renderSvgToPngBlob(e,t,n,r={}){const o=this.serializeSvgForPng(e,t,n,r),i=URL.createObjectURL(new Blob([o],{type:"image/svg+xml;charset=utf-8"}));try{const e=await this.loadSvgImage(i),r=document.createElement("canvas");r.width=Math.ceil(2*(t+48)),r.height=Math.ceil(2*(n+48));const o=r.getContext("2d");if(!o)throw new Error("Canvas 2D context is unavailable");return o.scale(2,2),o.fillStyle="dark"===this.getMermaidTheme()?"#0f172a":"#ffffff",o.fillRect(0,0,r.width/2,r.height/2),o.drawImage(e,24,24,t,n),await this.canvasToBlob(r)}finally{URL.revokeObjectURL(i);}}downgradeForeignObjectsForPng(e,t){const n=Array.from(e.querySelectorAll("foreignObject"));Array.from(t.querySelectorAll("foreignObject")).forEach((e,r)=>{const o=this.createForeignObjectTextFallback(n[r],t.ownerDocument);e.replaceWith(o);});}createForeignObjectTextFallback(e,t){const n=t.createElementNS(vw,"g");if(!e)return n;const r=this.getForeignObjectMetric(e,"x"),o=this.getForeignObjectMetric(e,"y"),i=this.getForeignObjectMetric(e,"width"),a=this.getForeignObjectMetric(e,"height"),s=this.getForeignObjectLines(e);if(0===s.length||i<=0||a<=0)return n;const l=e.querySelector("*")||null,c=l?window.getComputedStyle(l):null,d=Math.max(10,Number.parseFloat(c?.fontSize||"")||Math.min(16,Math.max(12,.35*a))),u=Number.parseFloat(c?.lineHeight||"")||Math.max(1.2*d,a/Math.max(s.length,1)),h=r+i/2,g=o+a/2-(s.length-1)*u/2,p=c?.color||("dark"===this.getMermaidTheme()?"#e5e7eb":"#111827"),m=c?.fontFamily||"Arial, sans-serif",f=c?.fontWeight||"400";return s.forEach((e,r)=>{const o=t.createElementNS(vw,"text");o.setAttribute("x",`${h}`),o.setAttribute("y",`${g+r*u}`),o.setAttribute("text-anchor","middle"),o.setAttribute("dominant-baseline","middle"),o.setAttribute("fill",p),o.setAttribute("font-size",`${d}`),o.setAttribute("font-family",m),o.setAttribute("font-weight",f),o.textContent=e,n.appendChild(o);}),n}getForeignObjectMetric(e,t){const n=Number.parseFloat(e.getAttribute(t)||"");if(Number.isFinite(n))return n;const r=e instanceof SVGGraphicsElement?e.getBBox():{x:0,y:0,width:0,height:0};return "x"===t?r.x:"y"===t?r.y:"width"===t?r.width:"height"===t?r.height:0}getForeignObjectLines(e){const t=e.querySelector("*")||null;return (t&&"string"==typeof t.innerText&&t.innerText||t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").split("\n").map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean)}loadSvgImage(e){return new Promise((t,n)=>{const r=new Image;r.decoding="async",r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load Mermaid SVG image")),r.src=e;})}canvasToBlob(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(new Error("Failed to convert Mermaid canvas to PNG blob"));},"image/png");})}createPngFilename(){return `ophel-mermaid-${(new Date).toISOString().replace(/[:.]/g,"-")}.png`}cleanupInjectedPanels(){ds.query(`[${uw}]`,{all:true,shadow:true}).forEach(e=>{e instanceof HTMLElement&&(e.style.display=e.getAttribute(hw)||"",e.removeAttribute(uw),e.removeAttribute(hw));});ds.query(dw,{all:true,shadow:true}).forEach(e=>e.remove());}cleanupPanel(e){const t=this.blockPanels.get(e);t?.isConnected&&t.remove(),e.style.display=e.getAttribute(hw)||"",e.removeAttribute(uw),e.removeAttribute(hw);}injectStyles(e){if(this.injectedRoots.has(e))return;if(e.querySelector?.(`#${cw}`))return;const t=document.createElement("style");t.id=cw,t.textContent="\n.gh-assistant-mermaid {\n margin: 12px 0;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n border-radius: 10px;\n background: var(--gh-bg-secondary, rgba(255, 255, 255, 0.9));\n overflow: hidden;\n}\n\n.gh-assistant-mermaid-toolbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n padding: 8px 10px;\n border-bottom: 1px solid var(--gh-border, rgba(148, 163, 184, 0.2));\n background: var(--gh-bg-primary, rgba(248, 250, 252, 0.96));\n}\n\n.gh-assistant-mermaid-actions {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-toolbar-group {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-zoom {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-btn {\n appearance: none;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n background: transparent;\n color: var(--gh-text-secondary, #64748b);\n border-radius: 999px;\n padding: 4px 10px;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;\n}\n\n.gh-assistant-mermaid-btn.is-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 30px;\n padding: 4px 8px;\n}\n\n.gh-assistant-mermaid-btn-icon {\n width: 14px;\n height: 14px;\n display: block;\n flex: 0 0 auto;\n}\n\n.gh-assistant-mermaid-btn:hover {\n background: rgba(59, 130, 246, 0.08);\n color: var(--gh-text, #0f172a);\n border-color: rgba(59, 130, 246, 0.28);\n}\n\n.gh-assistant-mermaid-btn.is-active {\n background: rgba(59, 130, 246, 0.14);\n color: #2563eb;\n border-color: rgba(59, 130, 246, 0.3);\n}\n\n.gh-assistant-mermaid-btn:disabled {\n opacity: 0.56;\n cursor: not-allowed;\n}\n\n.gh-assistant-mermaid-preview {\n padding: 12px;\n overflow-x: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.96));\n}\n\n.gh-assistant-mermaid-preview:fullscreen,\n.gh-assistant-mermaid-preview:-webkit-full-screen {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n padding: 24px;\n box-sizing: border-box;\n overflow: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.98));\n}\n\n.gh-assistant-mermaid-preview[hidden] {\n display: none !important;\n}\n\n.gh-assistant-mermaid-preview svg {\n display: block;\n max-width: 100%;\n height: auto;\n margin: 0 auto;\n}\n\n.gh-assistant-mermaid-preview:fullscreen svg,\n.gh-assistant-mermaid-preview:-webkit-full-screen svg {\n margin: auto;\n flex: 0 0 auto;\n}\n\nbody.dark-theme .gh-assistant-mermaid,\nhtml.dark .gh-assistant-mermaid,\nhtml[dark-theme] .gh-assistant-mermaid {\n background: rgba(15, 23, 42, 0.88);\n}\n\nbody.dark-theme .gh-assistant-mermaid-toolbar,\nhtml.dark .gh-assistant-mermaid-toolbar,\nhtml[dark-theme] .gh-assistant-mermaid-toolbar,\nbody.dark-theme .gh-assistant-mermaid-preview,\nhtml.dark .gh-assistant-mermaid-preview,\nhtml[dark-theme] .gh-assistant-mermaid-preview {\n background: rgba(15, 23, 42, 0.92);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn,\nhtml.dark .gh-assistant-mermaid-btn,\nhtml[dark-theme] .gh-assistant-mermaid-btn {\n color: rgba(226, 232, 240, 0.82);\n border-color: rgba(148, 163, 184, 0.26);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn:hover,\nhtml.dark .gh-assistant-mermaid-btn:hover,\nhtml[dark-theme] .gh-assistant-mermaid-btn:hover {\n color: #eff6ff;\n background: rgba(59, 130, 246, 0.18);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn.is-active,\nhtml.dark .gh-assistant-mermaid-btn.is-active,\nhtml[dark-theme] .gh-assistant-mermaid-btn.is-active {\n color: #93c5fd;\n}\n",e instanceof ShadowRoot?e.prepend(t):document.head.appendChild(t),this.injectedRoots.add(e);}getMermaidTheme(){const e=document.documentElement.className,t=document.body.className,n=/\bdark\b/i.test(e),r=/\bdark-theme\b/i.test(t),o=document.documentElement.hasAttribute("dark-theme");return n||r||o?"dark":"default"}createRequestId(){return `gh-assistant-mermaid-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}async ensureRuntime(){if(!ww())return this.runtimePromise||(this.runtimePromise=(async()=>{const e=xw("assistantMermaidVendor"),t=xw("assistantMermaidRunner");if(!e||!t)throw new Error("Assistant Mermaid runtime asset URL is unavailable");if(await this.injectScript(e,"ophel-assistant-mermaid-vendor"),await this.injectScript(t,"ophel-assistant-mermaid-runner"),!ww())throw new Error("Assistant Mermaid runner did not initialize")})().catch(e=>{throw this.runtimePromise=null,e})),this.runtimePromise}injectScript(e,t){const n=`script[data-ophel-runtime="${t}"]`,r=document.querySelector(n);return "true"===r?.dataset.loaded?Promise.resolve():new Promise((n,o)=>{const i=r||document.createElement("script"),a=()=>{i.removeEventListener("load",s),i.removeEventListener("error",l);},s=()=>{a(),i.dataset.loaded="true",n();},l=()=>{a(),o(new Error(`Failed to load script: ${e}`));};i.addEventListener("load",s,{once:true}),i.addEventListener("error",l,{once:true});try{i.dataset.ophelRuntime=t,i.dataset.loaded="false",i.async=!1;if((i.getAttribute("src")||i.src)!==e&&!Ld(i,e))throw new Error(`Failed to set trusted script src: ${e}`);r||(document.head||document.documentElement).appendChild(i);}catch(RS){a(),o(RS instanceof Error?RS:new Error(`Failed to load script: ${e}`));}})}requestRender(e,t,n,r){return new Promise((o,i)=>{const a=window.setTimeout(()=>{this.pendingRequests.delete(e),i(new Error("Assistant Mermaid render timed out"));},15e3);this.pendingRequests.set(e,{resolve:o,reject:i,timeoutId:a}),window.postMessage({type:"OPHEL_ASSISTANT_MERMAID_RENDER_REQUEST",requestId:e,previewId:t,source:n,theme:r},"*");})}}const kw="ghTableCopy",Tw=[".ProseMirror",".ql-editor",".cm-editor",".monaco-editor"],Ew=".gh-user-query-markdown, .gh-markdown-preview";class Aw{settings;siteAdapter=null;formulaCopyInitialized=false;tableCopyInitialized=false;formulaDblClickHandler=null;stopTableWatch=null;rescanTimer=null;static FORMULA_HOST_SELECTOR=[".math-block",".math-inline",".katex",".katex-display","math","[data-math]","[data-custom-copy-text]",'annotation[encoding="application/x-tex"]'].join(", ");constructor(e,t){this.settings=e,this.siteAdapter=t||null;}updateSettings(e){e.formulaCopy!==this.settings.formulaCopy&&(e.formulaCopy?(this.settings=e,this.initFormulaCopy()):this.destroyFormulaCopy()),e.tableCopy!==this.settings.tableCopy&&(e.tableCopy?(this.settings=e,this.initTableCopy()):this.destroyTableCopy()),this.settings=e;}initFormulaCopy(){if(this.formulaCopyInitialized)return;this.formulaCopyInitialized=true;const e=false!==this.siteAdapter?.supportsFormulaCopy(),t="gh-formula-copy-style";if(e&&!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent="\n .math-block, .math-inline, .katex {\n user-select: none !important;\n cursor: pointer !important;\n }\n .math-block:hover, .math-inline:hover, .katex:hover {\n outline: none !important;\n box-shadow: inset 0 0 0 2px #4285f4;\n border-radius: 4px;\n }\n .math-block:hover .katex,\n .math-inline:hover .katex {\n outline: none !important;\n box-shadow: none !important;\n }\n ",document.head.appendChild(e);}this.formulaDblClickHandler=t=>{const n=t.target instanceof Element?t.target:t.target instanceof Node?t.target.parentElement:null;if(n)try{const r=n.closest(Aw.FORMULA_HOST_SELECTOR);if(!r)return;if(!e)return Pi(le("formulaFormatUnsupported")),t.preventDefault(),void t.stopPropagation();const o=this.extractFormulaCopyPayload(n,r);if(o?.latex||o?.mathml)return this.copyFormula(o),t.preventDefault(),void t.stopPropagation();Pi(le("formulaSourceUnavailable")),t.preventDefault(),t.stopPropagation();}catch(r){console.error("[FormulaCopy] Unexpected error:",r),Pi(le("copyFailed"));}},document.addEventListener("dblclick",this.formulaDblClickHandler,true);}extractFormulaCopyPayload(e,t){const n=this.siteAdapter?.extractFormulaCopySource(e,t),r=this.normalizeFormulaCopySource(n);if(r)return r;const o=t.closest(".math-block, .math-inline, [data-math], [data-custom-copy-text]");if(o){const e=this.unwrapMathDelimiters(o.getAttribute("data-math")||o.getAttribute("data-custom-copy-text")||o.getAttribute("copy-text")||""),t=this.serializeMathElement(o.querySelector("math"));if(e||t)return {latex:e,mathml:t,isBlock:o.classList.contains("math-block")||o.matches(".math-block")||this.isBlockMathElement(o)}}const i=t.closest(".katex, .katex-display")||e.closest(".katex, .katex-display"),a=t.closest("math")||e.closest("math")||i?.querySelector("math")||null,s=t.matches('annotation[encoding="application/x-tex"]')?t:i?.querySelector('annotation[encoding="application/x-tex"]')||a?.querySelector('annotation[encoding="application/x-tex"]')||null,l=this.unwrapMathDelimiters(s?.textContent||""),c=this.serializeMathElement(a);return l||c?{latex:l,mathml:c,isBlock:!!i?.closest(".katex-display")||this.isBlockMathElement(a)}:null}normalizeFormulaCopySource(e){if(!e)return null;const t=this.unwrapMathDelimiters(e.latex||""),n=e.mathml?.trim()||"";return t||n?{latex:t,mathml:n,isBlock:e.isBlock??this.isBlockMathml(n)}:null}isBlockMathElement(e){return !!e&&"block"===e.getAttribute("display")}isBlockMathml(e){return /\sdisplay=(["'])block\1/i.test(e)}serializeMathElement(e){if(!e)return "";try{return (new XMLSerializer).serializeToString(e).trim()}catch(t){return console.warn("[FormulaCopy] Failed to serialize MathML:",t),e instanceof HTMLElement?e.outerHTML.trim():""}}unwrapMathDelimiters(e){const t=e.trim();if(!t)return "";const n=[["$$","$$"],["\\(","\\)"],["\\[","\\]"],["$","$"]];for(const[r,o]of n)if(t.startsWith(r)&&t.endsWith(o)&&t.length>r.length+o.length)return t.slice(r.length,t.length-o.length).trim();return t}copyFormula(e){if("latex"===("mathml"===this.settings.formulaCopyFormat?"mathml":"latex"))return e.latex?void this.copyLatex(e.latex,e.isBlock):void Pi(le("formulaSourceUnavailable"));const t=e.mathml||this.renderLatexToMathml(e.latex||"",e.isBlock);t?this.copyText(t):Pi(le("formulaFormatUnsupported"));}copyLatex(e,t){const n=e.replace(/\r\n?/g,"\n").trim();let r=n;if(this.settings.formulaDelimiter){const e=t&&(n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n));r=t?e?`$$\n${n}\n$$`:`$$${n}$$`:`$${n}$`;}this.copyText(r);}renderLatexToMathml(e,t){const n=e.replace(/\r\n?/g,"\n").trim();if(!n)return "";try{const e=Bl(n,{displayMode:t}),r=document.createElement("template");return r.innerHTML=e,this.serializeMathElement(r.content.querySelector("math"))}catch(r){return console.warn("[FormulaCopy] Failed to convert LaTeX to MathML:",r),""}}copyText(e){navigator.clipboard?.writeText?navigator.clipboard.writeText(e).then(()=>Pi(le("formulaCopied"))).catch(e=>{console.error("[FormulaCopy] Copy failed:",e),Pi(le("copyFailed"));}):Pi(le("copyFailed"));}destroyFormulaCopy(){this.formulaCopyInitialized=false;const e=document.getElementById("gh-formula-copy-style");e&&e.remove(),this.formulaDblClickHandler&&(document.removeEventListener("dblclick",this.formulaDblClickHandler,true),this.formulaDblClickHandler=null);}initTableCopy(){if(this.tableCopyInitialized)return;this.tableCopyInitialized=true;const e="gh-table-copy-style";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n .gh-table-copy-btn {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: rgba(255,255,255,0.9);\n color: #374151;\n cursor: pointer;\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n transition: opacity 0.2s, background 0.2s;\n z-index: 10;\n box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n }\n .gh-table-container:hover .gh-table-copy-btn,\n table-block:hover .gh-table-copy-btn,\n ucs-markdown-table:hover .gh-table-copy-btn {\n opacity: 1;\n }\n .gh-table-copy-btn:hover {\n background: #4285f4;\n color: white;\n }\n ",document.head.appendChild(t);}this.siteAdapter?.usesShadowDOM()??false?this.startRescanTimer():this.stopTableWatch=ds.each("table",e=>{this.injectTableButton(e);},{shadow:true});}startRescanTimer(){this.rescanTables(),this.rescanTimer=setInterval(()=>{this.rescanTables();},1e3);}rescanTables(){if(document.hidden)return;const e=ds.query("table",{all:true,shadow:true});for(const t of e)this.injectTableButton(t);}injectTableButton(e){if(e.dataset[kw])return;const t=!!e.closest(Ew);if(t||!this.isTableInsideEditableHost(e))try{let n;if(t)n=e,e.style.position="relative";else {if(n=e.closest("table-block, ucs-markdown-table"),!n){if(n=e.parentNode,!n)return;n.classList.add("gh-table-container");}n.style.position="relative";}const r=document.createElement("button");r.className="gh-table-copy-btn",r.appendChild(sd({size:14,color:"#6b7280"})),r.title=le("tableCopyLabel");const o=n.tagName?.toLowerCase(),i="ucs-markdown-table"===o||n.closest("ucs-markdown-table")||n.classList.contains("gh-table-container")?"80px":"4px";Object.assign(r.style,{position:"absolute",top:"4px",right:i,width:"28px",height:"28px",border:"none",borderRadius:"6px",background:"rgba(255,255,255,0.9)",color:"#374151",cursor:"pointer",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",opacity:"0.6",transition:"opacity 0.2s, background 0.2s, transform 0.2s",zIndex:"10",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",pointerEvents:"auto"}),r.addEventListener("mouseenter",()=>{r.style.opacity="1",r.style.transform="scale(1.1)";}),r.addEventListener("mouseleave",()=>{r.style.opacity="0.6",r.style.transform="scale(1)";}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation();const n=this.tableToMarkdown(e);navigator.clipboard.writeText(n).then(()=>{Pi(le("tableCopied")),ld(r,{size:14});}).catch(e=>{console.error("[TableCopy] Copy failed:",e),Pi(le("copyFailed"));});}),n.appendChild(r),e.dataset[kw]="true";}catch(n){console.error("[TableCopy] Error injecting button:",n);}}isTableInsideEditableHost(e){let t=e;for(;t;){if(t instanceof HTMLElement){if(t.matches(Ew))return false;if(this.isEditableHost(t))return true}t=ds.getComposedParent(t);}return false}isEditableHost(e){if(e.isContentEditable)return true;if("textbox"===e.getAttribute("role"))return true;if(Tw.some(t=>{try{return e.matches(t)}catch{return false}}))return true;const t=e.getAttribute("contenteditable");return !!t&&"false"!==t.toLowerCase()}tableToMarkdown(e){const t=e.querySelectorAll("tr");if(0===t.length)return "";const n=[];let r=false;const o=e=>{if(this.settings.formulaCopy){const t=e.cloneNode(true);return t.querySelectorAll(".math-block, .math-inline").forEach(e=>{const t=e,n=t.getAttribute("data-math");if(n){const e=t.classList.contains("math-block");let r;r=this.settings.formulaDelimiter?e?`$$${n}$$`:`$${n}$`:n,t.replaceWith(document.createTextNode(r));}}),t.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""}return e.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""};return t.forEach((e,t)=>{const i=e.querySelectorAll("th, td"),a=Array.from(i).map(e=>o(e));if(n.push("| "+a.join(" | ")+" |"),!r&&(e.querySelector("th")||0===t)){const e=Array.from(i).map(e=>e.classList.contains("align-center")?":---:":e.classList.contains("align-right")?"---:":"---");n.push("| "+e.join(" | ")+" |"),r=true;}}),n.join("\n")}destroyTableCopy(){this.tableCopyInitialized=false,this.stopTableWatch&&(this.stopTableWatch(),this.stopTableWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);const e=document.getElementById("gh-table-copy-style");e&&e.remove(),ds.query(".gh-table-copy-btn",{all:true,shadow:true})?.forEach(e=>e.remove()),ds.query("[data-gh-table-copy]",{all:true,shadow:true})?.forEach(e=>{e instanceof HTMLElement&&e.removeAttribute("data-gh-table-copy");}),ds.query(".gh-table-container",{all:true,shadow:true})?.forEach(e=>{e.classList.remove("gh-table-container");});}stop(){this.destroyFormulaCopy(),this.destroyTableCopy();}}const Mw="gh-page-width-styles",Iw="gh-page-width-shadow",Lw="gh-user-query-width-styles",Nw="gh-user-query-width-shadow",Rw="gh-zen-mode-styles",Dw="gh-zen-mode-shadow",Pw="gh-clean-mode-styles",qw="gh-clean-mode-shadow",Bw="gh-zen-mode-exit-host",$w={enabled:false,showExitButton:true};class _w{siteAdapter;pageWidthConfig;userQueryWidthConfig=null;pageWidthStyle=null;userQueryWidthStyle=null;zenModeStyle=null;zenModeConfig=$w;zenModeEnabled=false;zenModeExitHost=null;zenModeRootClassState=null;cleanModeStyle=null;cleanModeEnabled=false;processedShadowRoots=new WeakSet;shadowCheckInterval=null;constructor(e,t){this.siteAdapter=e,this.pageWidthConfig=t;}updateConfig(e){this.pageWidthConfig=e,this.apply();}apply(){if(this.removeStyle(this.pageWidthStyle),this.pageWidthStyle=null,!this.pageWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generatePageWidthCSS();this.pageWidthStyle=this.injectStyle(Mw,e),this.refreshShadowInjection();}updateUserQueryConfig(e){this.userQueryWidthConfig=e,this.applyUserQueryWidth();}applyUserQueryWidth(){if(this.removeStyle(this.userQueryWidthStyle),this.userQueryWidthStyle=null,!this.userQueryWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generateUserQueryWidthCSS();this.userQueryWidthStyle=this.injectStyle(Lw,e),this.refreshShadowInjection();}updateZenMode(e){this.zenModeConfig="boolean"==typeof e?{...this.zenModeConfig,enabled:e}:{...$w,...e},this.zenModeEnabled=this.zenModeConfig.enabled,this.applyZenMode();}applyZenMode(){if(this.removeStyle(this.zenModeStyle),this.zenModeStyle=null,!this.zenModeEnabled)return this.cleanupZenModeRootClass(),this.unmountZenModeExitButton(),void this.refreshShadowInjection();this.syncZenModeRootClass();const e=this.generateZenModeCSS();e&&(this.zenModeStyle=this.injectStyle(Rw,e)),false===this.zenModeConfig.showExitButton?this.unmountZenModeExitButton():this.mountZenModeExitButton(),this.refreshShadowInjection();}updateCleanMode(e){this.cleanModeEnabled=e,this.applyCleanMode();}applyCleanMode(){if(this.removeStyle(this.cleanModeStyle),this.cleanModeStyle=null,!this.cleanModeEnabled)return void this.refreshShadowInjection();const e=this.generateCleanModeCSS();e&&(this.cleanModeStyle=this.injectStyle(Pw,e)),this.refreshShadowInjection();}generatePageWidthCSS(){const e=`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,t=this.siteAdapter.getWidthSelectors(),n=this.buildCSSFromSelectors(t,e,true);if("%"===this.pageWidthConfig.unit){return `${n}\n@media (max-width: 480px) {\n${this.buildCSSFromSelectors(t,"95%",true)}\n}`}return n}generateUserQueryWidthCSS(){if(!this.userQueryWidthConfig)return "";const e=`${this.userQueryWidthConfig.value||"81"}${this.userQueryWidthConfig.unit||"%"}`,t=this.siteAdapter.getUserQueryWidthSelectors();return this.buildCSSFromSelectors(t,e,false)}generateZenModeCSS(){const e=this.siteAdapter.getZenModeConfig(),t=this.siteAdapter.getCleanModeConfig();if(!e&&!t)return "";const n=[...e?.hide||[],...t?.hide||[]],r=[...e?.styles||[],...t?.styles||[]];return [n.map(e=>`${e} { display: none !important; }`).join("\n"),this.buildZenModeStyleCSS(r)].filter(Boolean).join("\n")}generateCleanModeCSS(){const e=this.siteAdapter.getCleanModeConfig();if(!e)return "";return [(e.hide||[]).map(e=>`${e} { display: none !important; }`).join("\n"),this.buildZenModeStyleCSS(e.styles||[])].filter(Boolean).join("\n")}buildCSSFromSelectors(e,t,n){return e.map(e=>{const{selector:r,globalSelector:o,property:i,value:a,transformValue:s,extraCss:l,noCenter:c}=e,d=a||t,u=s?s(d):d;return `${n&&o||r} { ${i}: ${u} !important; ${c?"":"margin-left: auto !important; margin-right: auto !important;"} ${l||""} }`}).join("\n")}injectStyle(e,t){const n=document.createElement("style");return n.id=e,n.textContent=t,document.head.appendChild(n),n}removeStyle(e){e&&e.remove();}buildZenModeStyleCSS(e){return e.map(e=>{const t=e.globalSelector||e.selector,n=e.extraCss||"";return `${t} { ${e.property}: ${e.value} !important; ${n} }`}).join("\n")}syncZenModeRootClass(){const e=this.siteAdapter.getZenModeConfig()?.rootClass;if(!e)return;const t=this.zenModeRootClassState;if(!t||t.selector!==e.selector||t.className!==e.className){const t=document.querySelector(e.selector);if(!(t instanceof HTMLElement))return;this.zenModeRootClassState={selector:e.selector,className:e.className,removeOnDisable:!t.classList.contains(e.className)};}document.querySelectorAll(e.selector).forEach(t=>{t instanceof HTMLElement&&!t.classList.contains(e.className)&&t.classList.add(e.className);});}cleanupZenModeRootClass(){if(!this.zenModeRootClassState?.removeOnDisable)return void(this.zenModeRootClassState=null);const{selector:e,className:t}=this.zenModeRootClassState;document.querySelectorAll(e).forEach(e=>{e instanceof HTMLElement&&e.classList.remove(t);}),this.zenModeRootClassState=null;}mountZenModeExitButton(){if(!document.body)return;if(this.zenModeExitHost?.isConnected)return;const e=document.getElementById(Bw);e instanceof HTMLElement&&e.remove();const t=document.createElement("div");t.id=Bw,t.style.cssText=["position: fixed","z-index: 2147483647","pointer-events: auto"].join(";");const n=this.siteAdapter.getThemeColors().primary||"#2563eb",r=le("zenModeExitButton"),o=t.attachShadow({mode:"open"});o.innerHTML=Ad(`\n \n \n `);const i=o.querySelector(".zen-exit-btn");i?.addEventListener("click",this.handleZenModeExit),document.body.appendChild(t),this.zenModeExitHost=t;}unmountZenModeExitButton(){if(this.zenModeExitHost?.shadowRoot){const e=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-btn");e?.removeEventListener("click",this.handleZenModeExit);}this.zenModeExitHost?.remove(),this.zenModeExitHost=null;}handleZenModeExit=()=>{const e=this.siteAdapter.getSiteId(),t={...this.zenModeConfig,enabled:false};this.updateZenMode(t),Mi.getState().updateDeepSetting("layout","zenMode",e,t);};refreshLocalizedTexts(){if(!this.zenModeEnabled||!this.zenModeExitHost?.shadowRoot)return;const e=le("zenModeExitButton"),t=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-text"),n=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-btn");t&&(t.textContent=e),n&&n.setAttribute("aria-label",e);}refreshShadowInjection(){if(!(this.pageWidthConfig?.enabled||this.userQueryWidthConfig?.enabled||this.zenModeEnabled||this.cleanModeEnabled))return this.stopShadowInjection(),void this.clearAllShadowStyles();this.startShadowInjection();}startShadowInjection(){this.injectToAllShadows(),this.shadowCheckInterval||(this.shadowCheckInterval=setInterval(()=>this.injectToAllShadows(),1e3));}stopShadowInjection(){this.shadowCheckInterval&&(clearInterval(this.shadowCheckInterval),this.shadowCheckInterval=null);}injectToAllShadows(){if(!document.body)return;this.zenModeEnabled&&this.syncZenModeRootClass();const e=this.siteAdapter;ds.walkShadowRoots((t,n)=>{if(!n||e.shouldInjectIntoShadow(n)){if(this.pageWidthConfig?.enabled){const n=`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,r=e.getWidthSelectors();let o=this.buildCSSFromSelectors(r,n,false);if("%"===this.pageWidthConfig.unit){o=`${o}\n@media (max-width: 480px) {\n${this.buildCSSFromSelectors(r,"95%",false)}\n}`;}ds.cssToShadow(t,o,Iw);}else this.removeStyleFromShadow(t,Iw);if(this.userQueryWidthConfig?.enabled){const n=this.userQueryWidthConfig.value||"81",r=this.userQueryWidthConfig.unit||"%",o=this.buildCSSFromSelectors(e.getUserQueryWidthSelectors(),`${n}${r}`,false);ds.cssToShadow(t,o,Nw);}else this.removeStyleFromShadow(t,Nw);if(this.zenModeEnabled){const e=this.generateZenModeCSS();e?ds.cssToShadow(t,e,Dw):this.removeStyleFromShadow(t,Dw);}else this.removeStyleFromShadow(t,Dw);if(this.cleanModeEnabled){const e=this.generateCleanModeCSS();e?ds.cssToShadow(t,e,qw):this.removeStyleFromShadow(t,qw);}else this.removeStyleFromShadow(t,qw);this.processedShadowRoots.add(t);}});}removeStyleFromShadow(e,t){const n=e.getElementById(t);n&&n.remove();}clearAllShadowStyles(){document.body&&ds.walkShadowRoots(e=>{this.removeStyleFromShadow(e,Iw),this.removeStyleFromShadow(e,Nw),this.removeStyleFromShadow(e,Dw),this.removeStyleFromShadow(e,qw),this.processedShadowRoots.delete(e);});}}const Ow=/]*>[\s\S]*?<\/code>/gi,zw=/]*>([\s\S]*?)<\/b>/gi,Fw=/]*>([\s\S]*?)<\/strong>/gi,Uw=/\*\*([^*]+(?:\*(?!\*)[^*]*)*)\*\*/g,Hw=/###OPHEL_CODE_(\d+)###/g;class Ww{stopObserver=null;enabled=false;config;constructor(e){this.config=e;}start(){this.enabled||(this.enabled=true,this.fixAllParagraphs(),this.stopObserver=ds.each(this.config.selector,(e,t)=>{t&&setTimeout(()=>this.fixParagraph(e),100);}));}stop(){this.enabled&&(this.enabled=false,this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}fixAllParagraphs(){ds.query(this.config.selector,{all:true}).forEach(e=>this.fixParagraph(e));}fixParagraph(e){if(!e.isConnected)return;if(this.config.shouldIgnore?.(e))return void delete e.dataset.mdFixerHash;if(this.config.shouldSkip?.(e))return void setTimeout(()=>this.fixParagraph(e),500);const t=e.innerHTML;if(e.dataset.mdFixerHash===String(t.length))return;if(!t.includes("(n.push(e),`###OPHEL_CODE_${n.length-1}###`)).replace(Fw,"**$1**");r=r.replace(zw,"**$1**");let o=false;if(r=r.replace(Uw,(e,t)=>(o=true,`${t}`)),o){const o=r.replace(Hw,(e,t)=>n[parseInt(t,10)]);t!==o&&Md(e,o);}e.dataset.mdFixerHash=String(e.innerHTML.length);}}class jw{adapter;config;isLocked=false;verifyTimer=null;configDebounceTimer=null;constructor(e,t){this.adapter=e,this.config=t;}updateConfig(e){const t=this.config.enabled,n=this.config.keyword;this.config=e;(!t&&e.enabled||e.enabled&&e.keyword!==n)&&(this.configDebounceTimer&&clearTimeout(this.configDebounceTimer),this.configDebounceTimer=setTimeout(()=>{this.configDebounceTimer=null,this.isLocked=false,this.start(50);},500));}start(e=1500){this.config.enabled&&this.config.keyword&&(this.isLocked||setTimeout(()=>{this.isLocked||this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();});},e));}relock(e=300){this.config.enabled&&this.config.keyword&&(this.stop(),this.isLocked=false,this.start(e));}startVerification(){this.verifyTimer&&clearInterval(this.verifyTimer);let e=0,t=0;this.verifyTimer=setInterval(()=>{e++;const n=this.adapter.getModelSwitcherConfig(this.config.keyword);if(!n)return void this.finishVerification();const r=this.adapter.findElementBySelectors(n.selectorButtonSelectors);if(!r)return void this.finishVerification();const o=this.adapter.getModelLockCheckText(r).toLowerCase().trim(),i=n.targetModelKeyword.toLowerCase().trim();o?o.includes(i)?(t++,(t>=2||e>=3)&&this.finishVerification()):(t=0,e<=2?(this.finishVerification(),this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();})):this.finishVerification()):e>=3&&this.finishVerification();},1500);}finishVerification(){this.isLocked=true,this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null);}stop(){this.configDebounceTimer&&(clearTimeout(this.configDebounceTimer),this.configDebounceTimer=null),this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null),this.isLocked=true;}}class Gw{adapter;settings;retryCounts=new Map;lastPromptValues=new WeakMap;monitorInitialized=false;constructor(e,t){this.adapter=e,this.settings=t,window.addEventListener("message",this.handleMessage.bind(this)),this.settings.enabled&&this.initNetworkMonitor();}updateSettings(e){const t=this.settings.enabled;this.settings=e,!t&&e.enabled&&this.initNetworkMonitor();}initNetworkMonitor(){if(this.monitorInitialized)return;const e=this.adapter.getNetworkMonitorConfig?.();e&&(window.postMessage({type:fd,payload:{urlPatterns:e.urlPatterns,urlPathEndsWith:e.urlPathEndsWith,silenceThreshold:e.silenceThreshold}},"*"),this.monitorInitialized=true);}handleMessage(e){if(this.adapter.getSiteId()!==mo)return;const t=e.data;if(t&&t.type===yd){if(!this.settings.enabled)return;this.checkAndRetry();}}async checkAndRetry(){await new Promise(e=>setTimeout(e,500));const e=ds.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return;const t=e.shadowRoot,n=t.querySelector(".turn.last")||t.querySelector(".turn:last-child");if(!n)return;const r=n.querySelector("ucs-summary");if(!r)return;if(!this.findBannedAnswer(r))return;const o=n.querySelector(".question-block");if(!o)return void console.warn("[PolicyRetry] User question block not found");const i=this.adapter.extractUserQueryText(o);if(!i)return void console.warn("[PolicyRetry] Empty user question");const a=await this.sha256(i),s=this.retryCounts.get(a)||0;if(ssetTimeout(e,100));if(!this.adapter.insertPrompt(e))return void console.error("[PolicyRetry] Failed to insert prompt");await new Promise(e=>setTimeout(e,300));const t=this.adapter.getSubmitButtonSelectors(),n=ds.query(t,{shadow:true});if(n)n.click();else {const e=this.adapter.findTextarea();e?(e.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keypress",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter",code:"Enter",keyCode:13,bubbles:true}))):console.error("[PolicyRetry] Submit button and editor not found");}}async sha256(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}}class Vw{static HYDRATION_TIMEOUT_MS=5e3;static SESSION_READY_TIMEOUT_MS=3e3;static SESSION_READY_POLL_MS=100;adapter;settings;isRecording=false;isRestoring=false;currentSessionId=null;listeningContainer=null;scrollHandler=null;userInteractionHandler=null;lastSaveTime=0;ignoreScrollUntil=0;positionKeeperRaF=0;restoredTop;constructor(e,t){this.adapter=e,this.settings=t;}async waitForHydration(e=Vw.HYDRATION_TIMEOUT_MS){return !!Uy.getState()._hasHydrated||new Promise(t=>{let n=false,r=0;const o=e=>{n||(n=true,window.clearTimeout(r),i(),t(e));},i=Uy.subscribe(e=>{e._hasHydrated&&o(true);});r=window.setTimeout(()=>{Uy.setState({_hasHydrated:true}),o(false);},e);})}updateSettings(e){this.settings=e,!this.settings.persistence&&this.isRecording?this.stopRecording():this.settings.persistence&&!this.isRecording&&this.startRecording();}startRecording(){if(this.isRecording)return;this.isRecording=true,this.currentSessionId=null,this.scrollHandler=e=>this.handleScroll(e);const e=this.adapter.getScrollContainer();e&&(e.addEventListener("scroll",this.scrollHandler,{passive:true}),this.listeningContainer=e),this.ignoreScrollUntil=Date.now()+2e3,this.userInteractionHandler=e=>{if("keydown"===e.type){const t=e.key;if(!["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(t))return}if("wheel"===e.type||"touchmove"===e.type){const t=e.composedPath?.()?.[0];if(t){const e=t.getRootNode?.();if(e&&e!==document)return}}this.ignoreScrollUntil>0&&(this.ignoreScrollUntil=0),this.positionKeeperRaF&&this.stopPositionKeeper();},window.addEventListener("wheel",this.userInteractionHandler,{passive:true}),window.addEventListener("touchmove",this.userInteractionHandler,{passive:true}),window.addEventListener("keydown",this.userInteractionHandler,{passive:true}),window.addEventListener("scroll",this.scrollHandler,{capture:true,passive:true}),window.addEventListener("visibilitychange",this.scrollHandler),window.addEventListener("beforeunload",this.scrollHandler);}stopRecording(){this.isRecording&&(this.isRecording=false,this.currentSessionId=null,this.scrollHandler&&(this.listeningContainer&&(this.listeningContainer.removeEventListener("scroll",this.scrollHandler),this.listeningContainer=null),window.removeEventListener("scroll",this.scrollHandler,{capture:true}),window.removeEventListener("visibilitychange",this.scrollHandler),window.removeEventListener("beforeunload",this.scrollHandler),this.scrollHandler=null),this.userInteractionHandler&&(window.removeEventListener("wheel",this.userInteractionHandler),window.removeEventListener("touchmove",this.userInteractionHandler),window.removeEventListener("keydown",this.userInteractionHandler),this.userInteractionHandler=null),this.stopPositionKeeper());}restartRecording(){this.stopRecording(),this.startRecording();}handleScroll(e){if(!this.settings.persistence)return;if("scroll"===e.type){const t=this.adapter.getScrollContainer(),n=e.target;if(t&&n&&n!==document&&n!==window&&n!==t)return}const t=Date.now();("beforeunload"===e.type||"visibilitychange"===e.type||t-this.lastSaveTime>1e3)&&(this.saveProgress(),this.lastSaveTime=t);}getKey(e=this.getSessionId()){const t=e||"unknown";return `${this.adapter.getSiteId()}:${t}`}getSessionId(){return this.adapter.getSessionId()?.trim()||""}canUseCurrentSession(e=this.getSessionId()){return !!e&&this.adapter.isUserConversationPage()}lockCurrentSessionId(e){e&&(this.currentSessionId||(this.currentSessionId=e));}async waitForReadySessionId(e=Vw.SESSION_READY_TIMEOUT_MS){const t=Date.now()+e;for(;Date.now()<=t;){const e=this.getSessionId();if(this.canUseCurrentSession(e))return e;await new Promise(e=>window.setTimeout(e,Vw.SESSION_READY_POLL_MS));}const n=this.getSessionId();return this.canUseCurrentSession(n)?n:""}saveProgress(){if(!this.isRecording)return;if(this.isRestoring)return;const e=this.getSessionId();if(this.currentSessionId&&e&&e!==this.currentSessionId)return;if(Date.now(){e?.(`${le("exportLoading")} ${t}`);}})).success)return !1;const t=r.top;document.documentElement.dataset.ophelPositionLock=String(t),await bf(this.adapter,t),this.restoredTop=t,o=!0;}catch{return delete document.documentElement.dataset.ophelPositionLock,!1}}return o}finally{o&&void 0!==this.restoredTop&&this.startPositionKeeper(this.restoredTop),setTimeout(()=>{this.isRestoring=false;},1e3);}}cleanup(){const e=this.settings.cleanupDays||7;Hy().cleanup(e);}startPositionKeeper(e){this.stopPositionKeeper();const t=Date.now();document.documentElement.dataset.ophelPositionLock=String(e),document.documentElement.dataset.ophelPositionLockLastBlock=String(t);const n=()=>{const r=Date.now(),o=r-t;if(o>15e3)return void this.stopPositionKeeper();if(o>2e3){const e=Number(document.documentElement.dataset.ophelPositionLockLastBlock||"0");if(e>0&&r-e>2e3)return void this.stopPositionKeeper()}const i=this.adapter.getScrollContainer();if(i){const t=document.documentElement.dataset.ophelPositionLock;if(void 0!==t){const n=Number(t);!isNaN(n)&&Math.abs(n-e)>5&&(e=n);}Math.abs(i.scrollTop-e)>5&&(i.scrollTop=e);}this.positionKeeperRaF=requestAnimationFrame(n);};this.positionKeeperRaF=requestAnimationFrame(n);}stopPositionKeeper(){this.positionKeeperRaF&&(cancelAnimationFrame(this.positionKeeperRaF),this.positionKeeperRaF=0,delete document.documentElement.dataset.ophelPositionLock,delete document.documentElement.dataset.ophelPositionLockLastBlock);}}class Qw{adapter;settings;enabled=false;constructor(e,t){this.adapter=e,this.settings=t,this.init();}updateSettings(e){const t=this.settings.panel?.preventAutoScroll;this.settings=e,!t&&e.panel?.preventAutoScroll?this.enable():t&&!e.panel?.preventAutoScroll&&this.disable();}init(){this.settings.panel?.preventAutoScroll&&this.enable();}enable(){this.enabled||(this.enabled=true,this.toggleMainWorldHijack(true));}disable(){this.enabled&&(this.enabled=false,this.toggleMainWorldHijack(false));}stop(){this.disable();}toggleMainWorldHijack(e){window.postMessage({type:"OPHEL_SCROLL_LOCK_TOGGLE",enabled:e},"*");}}class Kw{adapter;settings;isRunning=false;intervalId=null;titleObserver=null;expectedTitle=null;isApplyingManagedTitle=false;titleSyncTimer=null;aiState="idle";lastAiState="idle";currentNetworkGenerationPending=false;currentNetworkGenerationConfirmed=false;generationConfirmationIntervalId=null;currentGenerationUsesDomCompletion=false;currentDomCompletionObservedStart=false;domCompletionIntervalId=null;domCompletionTrackingStartedAt=0;userSawCompletion=false;completionViewed=false;lastConversationTitle=null;staleManagedTitleAfterRouteChange=null;staleConversationTitleAfterRouteChange=null;notificationAudio=null;notificationRepeatTimer=null;notificationPlaybackId=0;boundHandleMessage;boundVisibilityHandler;boundFocusHandler;boundBlurHandler;constructor(e,t){this.adapter=e,this.settings=t,this.boundHandleMessage=this.handleMessage.bind(this),this.boundVisibilityHandler=this.onVisibilityChange.bind(this),this.boundFocusHandler=this.onWindowFocus.bind(this),this.boundBlurHandler=this.onWindowBlur.bind(this),window.addEventListener("message",this.boundHandleMessage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),window.addEventListener("focus",this.boundFocusHandler),window.addEventListener("blur",this.boundBlurHandler);}updateSettings(e){const t=this.settings.renameInterval,n=this.settings.showNotification,r=this.settings.notificationSound,o=this.settings.notificationSoundPreset,i=this.settings.notificationVolume,a=this.settings.notificationRepeatCount,s=this.settings.notificationRepeatInterval;this.settings=e,n===this.settings.showNotification&&r===this.settings.notificationSound&&o===this.settings.notificationSoundPreset&&i===this.settings.notificationVolume&&a===this.settings.notificationRepeatCount&&s===this.settings.notificationRepeatInterval||this.stopNotificationPlayback(),this.settings.autoRename&&!this.isRunning?this.start():!this.settings.autoRename&&this.isRunning&&this.stop(),this.isRunning&&t!==this.settings.renameInterval&&this.setInterval(this.settings.renameInterval||5),this.isRunning&&this.updateTabName(true);}start(){if(!this.settings.autoRename)return;if(this.isRunning)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;this.isRunning=true,this.startTitleObserver(),this.updateTabName();const e=1e3*(this.settings.renameInterval||5);this.intervalId=setInterval(()=>this.updateTabName(),e);const t=this.adapter.getNetworkMonitorConfig?this.adapter.getNetworkMonitorConfig():null;t&&window.postMessage({type:fd,payload:{urlPatterns:t.urlPatterns,urlPathEndsWith:t.urlPathEndsWith,silenceThreshold:t.silenceThreshold,requestBodyRules:t.requestBodyRules}},"*");}stop(){this.isRunning&&(this.isRunning=false,this.resetGenerationConfirmationState(),this.stopTitleObserver(),this.expectedTitle=null,this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null,Ua(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null));}destroy(){this.stop(),this.stopNotificationPlayback(),this.resetGenerationConfirmationState(),this.stopTitleObserver(),window.removeEventListener("message",this.boundHandleMessage),document.removeEventListener("visibilitychange",this.boundVisibilityHandler),window.removeEventListener("focus",this.boundFocusHandler),window.removeEventListener("blur",this.boundBlurHandler);}setInterval(e){if(!this.isRunning)return;const t=1e3*e;this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval(()=>this.updateTabName(),t);}togglePrivacyMode(){return this.settings.privacyMode=!this.settings.privacyMode,this.updateTabName(true),this.settings.privacyMode}resetConversationTitleCache(){const e=Fa(document.title),t=Fa(this.expectedTitle)||Fa(Ha()),n=Fa(this.lastConversationTitle),r=e&&e===t?Wa(e,{expectedManagedTitle:t,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat}):null;this.lastConversationTitle=null,this.expectedTitle=null,Ua(),e&&e===t?(this.staleManagedTitleAfterRouteChange=e,this.staleConversationTitleAfterRouteChange=n||r):(this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null);}updateTabName(e=false){if(!this.isRunning&&!e)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;if(this.settings.privacyMode){const t=this.settings.privacyTitle||"Google";return void this.applyManagedTitle(t,e)}const t=this.getCleanConversationTitle(),n=this.isCurrentlyGenerating();"generating"===this.lastAiState&&!n&&this.isUserAway()&&"completed"!==this.aiState&&this.sendCompletionNotification(),this.lastAiState=n?"generating":"idle";const r=this.computeStatusPrefix(n),o=this.adapter.getName(),i=this.settings.titleFormat??"{status}{title}",a=i.includes("{model}")&&this.adapter.getModelName?.()||"",s=function(e,t){const n=Fa(t.modelName)?`[${Fa(t.modelName)}]`:"";return (n?e:Ga(e)).replace(/\{status\}/g,t.statusPrefix).replace(/\{title\}/g,t.conversationTitle).replace(/\{model\}/g,n).replace(/\{site\}/g,t.siteName).replace(/\s+/g," ").trim()}(i,{statusPrefix:r,conversationTitle:t||o,modelName:a,siteName:o});s&&this.applyManagedTitle(s,e);}computeStatusPrefix(e){return false===this.settings.showStatus?"":e?"⏳ ":this.settings.hideStatusWhenRead&&("completed"!==this.aiState||this.completionViewed)?"":"✅ "}applyManagedTitle(e,t=false){this.expectedTitle=e,function(e){"undefined"!=typeof document&&document.documentElement?.setAttribute(qa,e);}(e),(t||document.title!==e)&&(this.isApplyingManagedTitle=true,document.title=e,queueMicrotask(()=>{this.isApplyingManagedTitle=false;}));}startTitleObserver(){if(this.titleObserver||"undefined"==typeof MutationObserver)return;this.titleObserver=new MutationObserver(()=>{this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&(null!==this.titleSyncTimer&&window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=window.setTimeout(()=>{this.titleSyncTimer=null,this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&this.updateTabName(true));},0)));}),(()=>{document.head&&(this.titleObserver?.disconnect(),this.titleObserver?.observe(document.head,{childList:true,subtree:true,characterData:true}));})();}stopTitleObserver(){null!==this.titleSyncTimer&&(window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=null),this.titleObserver?.disconnect(),this.titleObserver=null,this.isApplyingManagedTitle=false;}getCleanConversationTitle(){if(this.adapter.isNewConversation?.())return this.lastConversationTitle=null,null;const e=this.sanitizeAdapterTitleCandidate(this.adapter.getConversationTitle?.());if(e)return this.clearStaleManagedTitleAfterRouteChange(),this.lastConversationTitle=e,e;if(this.expectedTitle&&document.title===this.expectedTitle&&this.lastConversationTitle)return this.lastConversationTitle;const t=this.sanitizeAdapterTitleCandidate(this.adapter.getSessionName?.());return t?(this.clearStaleManagedTitleAfterRouteChange(),this.lastConversationTitle=t,t):this.lastConversationTitle}sanitizeAdapterTitleCandidate(e){return this.shouldIgnoreStaleManagedTitle(e)||this.shouldIgnoreCurrentManagedDocumentTitle(e)?null:Wa(e,{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})}shouldIgnoreStaleManagedTitle(e){return !!this.staleManagedTitleAfterRouteChange&&(Fa(document.title)!==this.staleManagedTitleAfterRouteChange?(this.clearStaleManagedTitleAfterRouteChange(),false):this.isManagedDocumentTitleFallback(e,this.staleManagedTitleAfterRouteChange,this.staleConversationTitleAfterRouteChange))}shouldIgnoreCurrentManagedDocumentTitle(e){return !!this.expectedTitle&&(Fa(document.title)===Fa(this.expectedTitle)&&this.isManagedDocumentTitleFallback(e,this.expectedTitle,this.lastConversationTitle))}isManagedDocumentTitleFallback(e,t,n){const r=Fa(e),o=Fa(t);if(!r||!o)return false;if(r===o)return true;const i=Fa(o.replace(/^(?:[⏳✅]\s*)+/u,""));if(i&&r===i)return true;const a=Wa(o,{expectedManagedTitle:o,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat});return !(!a||r!==a)||Boolean(n&&r===Fa(n))}clearStaleManagedTitleAfterRouteChange(){this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null;}isCurrentlyGenerating(){return "completed"!==this.aiState&&("generating"===this.aiState||(this.adapter.isGenerating?.()??false))}requiresDomConfirmationForNetworkGeneration(){return this.adapter.requiresDomConfirmationForNetworkGeneration?.()??false}beginNetworkGeneration(e){this.stopNotificationPlayback(),e?.domCompletionRequired?this.beginDomCompletionDrivenGeneration():(this.resetDomCompletionState(),this.requiresDomConfirmationForNetworkGeneration()?(this.currentNetworkGenerationPending=true,this.currentNetworkGenerationConfirmed=false,this.startGenerationConfirmationPolling()):this.confirmCurrentNetworkGeneration());}confirmCurrentNetworkGeneration(){this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=true,this.clearGenerationConfirmationPolling(),"generating"!==this.aiState&&(this.lastAiState=this.aiState,this.aiState="generating",this.settings.hideStatusWhenRead&&(this.completionViewed=false)),this.updateTabName();}startGenerationConfirmationPolling(){this.clearGenerationConfirmationPolling();const e=()=>{this.currentNetworkGenerationPending&&this.adapter.isGenerating?.()&&this.confirmCurrentNetworkGeneration();};e(),this.currentNetworkGenerationConfirmed||(this.generationConfirmationIntervalId=window.setInterval(e,200));}beginDomCompletionDrivenGeneration(){this.resetGenerationConfirmationState(),this.currentGenerationUsesDomCompletion=true,this.currentDomCompletionObservedStart=false,this.domCompletionTrackingStartedAt=Date.now(),this.completionViewed=false,this.startDomCompletionPolling(),this.updateTabName();}startDomCompletionPolling(){this.clearDomCompletionPolling();const e=()=>{if(!this.currentGenerationUsesDomCompletion)return;const e=this.adapter.isGenerating?.()??false;if(!this.currentDomCompletionObservedStart)return e?(this.currentDomCompletionObservedStart=true,"generating"!==this.aiState&&(this.lastAiState=this.aiState,this.aiState="generating",this.completionViewed=false),void this.updateTabName()):void(Date.now()-this.domCompletionTrackingStartedAt>3e4&&(this.lastAiState=this.aiState,this.aiState="idle",this.userSawCompletion=false,this.completionViewed=false,this.resetDomCompletionState(),this.updateTabName(true)));e||this.finalizeAiCompletion();};e(),this.currentGenerationUsesDomCompletion&&(this.domCompletionIntervalId=window.setInterval(e,150));}clearGenerationConfirmationPolling(){null!==this.generationConfirmationIntervalId&&(window.clearInterval(this.generationConfirmationIntervalId),this.generationConfirmationIntervalId=null);}clearDomCompletionPolling(){null!==this.domCompletionIntervalId&&(window.clearInterval(this.domCompletionIntervalId),this.domCompletionIntervalId=null);}resetDomCompletionState(){this.clearDomCompletionPolling(),this.currentGenerationUsesDomCompletion=false,this.currentDomCompletionObservedStart=false,this.domCompletionTrackingStartedAt=0;}resetGenerationConfirmationState(){this.clearGenerationConfirmationPolling(),this.resetDomCompletionState(),this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=false;}handleMessage(e){if(e.origin!==window.location.origin)return;const{type:t,payload:n}=e.data||{};t===bd?this.beginNetworkGeneration(n):t===yd&&this.onAiComplete();}isUserAway(){const e=document.hidden,t=document.hasFocus(),n="visible"!==document.visibilityState;return e||!t||n}onVisibilityChange(){const e=this.isUserAway();if(e||this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"!==this.aiState||e||this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true),"completed"===this.aiState&&!e){if(this.completionViewed)return;this.completionViewed=true,this.updateTabName(true);}}onWindowFocus(){this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"===this.aiState&&this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true),"completed"===this.aiState&&(this.completionViewed||(this.completionViewed=true,this.updateTabName(true)));}onWindowBlur(){}onAiComplete(){if(this.currentGenerationUsesDomCompletion)return;const e=this.requiresDomConfirmationForNetworkGeneration(),t=this.currentNetworkGenerationConfirmed;if(e&&!t)return this.resetGenerationConfirmationState(),this.lastAiState=this.aiState,this.aiState="idle",this.userSawCompletion=false,this.completionViewed=false,void this.updateTabName(true);this.finalizeAiCompletion();}finalizeAiCompletion(){const e="generating"===this.aiState;this.lastAiState=this.aiState,this.aiState="completed";const t=this.settings.notifyWhenFocused,n=this.isUserAway();e&&!this.userSawCompletion&&(n||t)&&this.sendCompletionNotification(),n||(this.completionViewed=true),this.userSawCompletion=false,this.resetGenerationConfirmationState(),this.updateTabName(true);}sendCompletionNotification(){if(this.stopNotificationPlayback(),this.settings.showNotification)try{const e=this.adapter.getName(),t=le("notificationTitle").replace("{site}",e),n=this.lastConversationTitle||Wa(this.adapter.getConversationTitle?.(),{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})||le("notificationBody");$i.notify({title:t,message:n});}catch(e){console.error("[TabManager] 通知发送失败:",e);}this.settings.showNotification&&this.settings.notificationSound&&this.playNotificationSound(),this.settings.autoFocus&&$i.focusWindow();}playNotificationSound(){const e=this.settings.notificationSoundPreset||no[0].id,t=no.find(t=>t.id===e)||no[0],n=$i.getNotificationSoundUrl(t.id);if(!n)return void console.warn("[TabManager] Notification sound URL not found for preset:",t.id);const r=this.normalizeNotificationRepeatCount(this.settings.notificationRepeatCount),o=1e3*this.normalizeNotificationRepeatInterval(this.settings.notificationRepeatInterval);this.startNotificationPlayback(n,r,o);}startNotificationPlayback(e,t,n){this.stopNotificationPlayback();const r=++this.notificationPlaybackId,o=t=>{if(r===this.notificationPlaybackId)try{this.notificationAudio||(this.notificationAudio=new Audio);const i=this.settings.notificationVolume??.5;this.notificationAudio.volume=Math.max(.1,Math.min(1,i)),this.notificationAudio.src=e,this.notificationAudio.currentTime=0,this.notificationAudio.onended=()=>{if(r===this.notificationPlaybackId)return t<=1?(this.clearNotificationPlaybackHandlers(),void(this.notificationRepeatTimer=null)):void(this.isUserAway()?this.notificationRepeatTimer=window.setTimeout(()=>{this.notificationRepeatTimer=null,o(t-1);},n):this.stopNotificationPlayback())},this.notificationAudio.onerror=()=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio element error:",{url:e,mediaError:this.notificationAudio?.error}),this.stopNotificationPlayback());},this.notificationAudio.play().catch(t=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio play rejected:",{url:e,error:t}),this.stopNotificationPlayback());});}catch(i){console.error("[TabManager] 音频初始化失败:",i);}};o(t);}stopNotificationPlayback(e){const t=e?.stopCurrentAudio??true;this.notificationPlaybackId+=1,null!==this.notificationRepeatTimer&&(window.clearTimeout(this.notificationRepeatTimer),this.notificationRepeatTimer=null);try{t&&this.notificationAudio&&(this.clearNotificationPlaybackHandlers(),this.notificationAudio.pause(),this.notificationAudio.currentTime=0);}catch(n){console.error("[TabManager] 音频停止失败:",n);}}clearNotificationPlaybackHandlers(){this.notificationAudio&&(this.notificationAudio.onended=null,this.notificationAudio.onerror=null);}normalizeNotificationRepeatCount(e){return Number.isFinite(e)?Math.max(1,Math.min(10,Math.round(e))):1}normalizeNotificationRepeatInterval(e){return Number.isFinite(e)?Math.max(1,Math.min(60,e)):3}isActive(){return this.isRunning}}const Zw="gh-usage-monitor-style",Yw="gh-usage-monitor-host",Xw={count:0,updatedAt:Date.now(),resetAt:Date.now()},Jw=e=>e.replace(/[\u200B\u200C\u200D\uFEFF\u00A0]/g,"").replace(/\s+/g," ").trim(),eS=/[\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g,tS=/[A-Za-z0-9]/g,nS=/[^\sA-Za-z0-9\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g;class rS{adapter;siteId;settings;root=null;slot=null;activeAnchor=null;mounted=false;mountTimer=null;renderTimer=null;renderInFlight=false;rerenderRequested=false;midnightTimer=null;pendingTimer=null;pendingSend=null;unwatchStorage=null;activeRecordKey="";currentRecord={...Xw};injectedStyleRoots=new Set;handleViewportChange=()=>{this.settings.enabled&&this.scheduleRender(0);};handleDocumentClick=e=>{if(!this.settings.enabled)return;const t=this.resolveEditor();t&&this.isSubmitButtonClick(e,t)&&this.schedulePendingSend(t);};handleDocumentKeydown=e=>{if(!this.settings.enabled)return;if(!this.isSubmitShortcut(e))return;const t=this.resolveEditorFromTarget(e.target);t&&this.schedulePendingSend(t);};handleDocumentInput=e=>{if(!this.settings.enabled)return;this.resolveEditorFromTarget(e.target)&&(this.ensureMounted(),this.scheduleRender(60));};handleDocumentFocus=()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));};constructor(e,t,n){this.adapter=e,this.settings=this.normalizeSettings(t),this.siteId=n;}start(){if(this.settings.enabled){if(this.mounted)return this.ensureMounted(),void this.scheduleRender(0);this.mounted=true,this.ensureStyles(),document.addEventListener("click",this.handleDocumentClick,true),document.addEventListener("keydown",this.handleDocumentKeydown,true),document.addEventListener("input",this.handleDocumentInput,true),document.addEventListener("focusin",this.handleDocumentFocus,true),window.addEventListener("resize",this.handleViewportChange,true),window.addEventListener("scroll",this.handleViewportChange,true),this.unwatchStorage=uv(e=>{const t=e.records[this.getRecordKey()];this.currentRecord=t?{count:Math.max(0,Math.floor(t.count||0)),updatedAt:t.updatedAt||Date.now(),resetAt:t.resetAt||Date.now()}:{count:0,updatedAt:Date.now(),resetAt:Date.now()},this.scheduleRender(0);}),this.startMountLoop(),this.scheduleMidnightReset(),this.syncCounterRecord(true),this.ensureMounted(),this.scheduleRender(0);}}stop(){if(!this.mounted)return this.removeRoot(),void this.removeStyles();this.mounted=false,document.removeEventListener("click",this.handleDocumentClick,true),document.removeEventListener("keydown",this.handleDocumentKeydown,true),document.removeEventListener("input",this.handleDocumentInput,true),document.removeEventListener("focusin",this.handleDocumentFocus,true),window.removeEventListener("resize",this.handleViewportChange,true),window.removeEventListener("scroll",this.handleViewportChange,true),null!==this.mountTimer&&(window.clearInterval(this.mountTimer),this.mountTimer=null),null!==this.renderTimer&&(window.clearTimeout(this.renderTimer),this.renderTimer=null),null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.pendingSend=null,this.unwatchStorage?.(),this.unwatchStorage=null,this.removeRoot(),this.removeStyles();}destroy(){this.stop();}updateSettings(e){this.settings=this.normalizeSettings(e),this.settings.enabled?this.mounted?(this.activeRecordKey="",this.scheduleMidnightReset(),this.ensureMounted(),this.syncCounterRecord(true),this.scheduleRender(0)):this.start():this.stop();}handleUrlChange(){this.settings.enabled&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.activeRecordKey="",this.adapter.findTextarea(),this.ensureMounted(true),this.syncCounterRecord(true),[80,220,500,1e3].forEach(e=>window.setTimeout(()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));},e)));}normalizeSettings(e){return {enabled:e?.enabled??false,dailyLimit:Math.max(1,Math.floor(e?.dailyLimit??100)),autoResetEnabled:e?.autoResetEnabled??false}}startMountLoop(){null===this.mountTimer&&(this.mountTimer=window.setInterval(()=>{(this.ensureMounted()||this.root)&&this.scheduleRender(0);},1e3));}ensureMounted(e=false){if(!this.settings.enabled)return false;const t=this.resolveEditor();if(!t)return (e||this.activeAnchor&&!this.activeAnchor.isConnected)&&this.removeRoot(),false;const n=this.resolveMountAnchor(t);if(!n?.parentElement)return false;this.ensureStylesForTarget(n),this.root||(this.root=document.createElement("div"),this.root.className=Yw),this.slot||(this.slot=document.createElement("div"),this.slot.className=`${Yw}-slot`);const r=e||this.activeAnchor!==n||!this.root.isConnected||!this.slot.isConnected||this.slot.parentElement!==n.parentElement||this.slot.nextSibling!==n;return r&&((n.parentElement&&this.slot.parentElement!==n.parentElement||n.parentElement&&this.slot.nextSibling!==n)&&n.parentElement.insertBefore(this.slot,n),this.root.parentElement!==this.slot&&this.slot.appendChild(this.root),this.activeAnchor=n),this.root.dataset.theme=this.detectThemeMode(),this.applySlotLayout(n),r}removeRoot(){this.activeAnchor=null,this.root?.remove(),this.root=null,this.slot?.remove(),this.slot=null;}bindPanelControls(){if(!this.root)return;const e=this.root.querySelector('[data-action="reset-counter"]');e&&(e.onclick=async e=>{e.preventDefault(),e.stopPropagation(),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t={count:0,updatedAt:Date.now(),resetAt:Date.now()},n=await nv();return n.records[e]=t,await rv(n),t}(this.getRecordKey()),this.scheduleRender(0);});}ensureStyles(){if(document.getElementById(Zw))return;const e=document.createElement("style");e.id=Zw,e.textContent=this.getUsageMonitorStyles(),document.head.appendChild(e);}ensureStylesForTarget(e){const t=e.getRootNode();t instanceof ShadowRoot&&(ds.cssToShadow(t,this.getUsageMonitorStyles(),Zw),this.injectedStyleRoots.add(t));}getUsageMonitorStyles(){return `\n .${Yw} {\n box-sizing: border-box;\n width: 100%;\n max-width: 100%;\n margin: 0;\n pointer-events: auto;\n }\n\n .${Yw}-slot {\n width: 100%;\n display: flex;\n align-items: flex-start;\n overflow: visible;\n pointer-events: none;\n margin: 0 0 8px 0;\n }\n\n .${Yw} * {\n box-sizing: border-box;\n }\n\n .${Yw} .gh-usage-monitor-panel {\n pointer-events: auto;\n border: 1px solid var(--gh-card-border, var(--gh-border, #e5e7eb));\n border-radius: 14px;\n padding: 10px 12px;\n background: var(--gh-card-bg, var(--gh-bg, #ffffff));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.1));\n color: var(--gh-text, #1f2937);\n font-size: 12px;\n line-height: 1.45;\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-panel {\n border-color: var(--gh-card-border, var(--gh-border, #333333));\n background: var(--gh-card-bg, var(--gh-bg, #1e1e1e));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.3));\n color: var(--gh-text, #e3e3e3);\n }\n\n .${Yw} .gh-usage-monitor-top {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n margin-bottom: 8px;\n }\n\n .${Yw} .gh-usage-monitor-title {\n font-weight: 600;\n letter-spacing: 0.01em;\n }\n\n .${Yw} .gh-usage-monitor-meta {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .${Yw} .gh-usage-monitor-count {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${Yw} .gh-usage-monitor-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 2px 8px;\n border-radius: 999px;\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #f9fafb));\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.2;\n white-space: nowrap;\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-badge {\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #0b0b0b));\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${Yw} .gh-usage-monitor-reset {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease, opacity 160ms ease;\n }\n\n .${Yw} .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${Yw} .gh-usage-monitor-control {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease;\n }\n\n .${Yw} .gh-usage-monitor-control:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-reset {\n border-color: var(--gh-input-border, var(--gh-border, #333333));\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #262626);\n }\n\n .${Yw} .gh-usage-monitor-progress {\n position: relative;\n height: 6px;\n border-radius: 999px;\n overflow: hidden;\n background: var(--gh-border, #e5e7eb);\n margin-bottom: 8px;\n }\n\n .${Yw} .gh-usage-monitor-progress-bar {\n height: 100%;\n width: 0;\n border-radius: inherit;\n background: var(--gh-primary, #4285f4);\n transition: width 160ms ease, background-color 160ms ease;\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-progress {\n background: var(--gh-border, #333333);\n }\n\n .${Yw}[data-level="warning"] .gh-usage-monitor-progress-bar {\n background: var(--gh-secondary, #34a853);\n }\n\n .${Yw}[data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${Yw}[data-level="danger"] .gh-usage-monitor-progress-bar {\n background: var(--gh-danger, #ef4444);\n }\n\n .${Yw}[data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${Yw}[data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${Yw}[data-theme="dark"][data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${Yw}[data-theme="dark"][data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${Yw}[data-theme="dark"][data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${Yw} .gh-usage-monitor-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 6px 12px;\n }\n\n .${Yw} .gh-usage-monitor-item {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 10px;\n }\n\n .${Yw} .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${Yw} .gh-usage-monitor-value {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${Yw} .gh-usage-monitor-footnote {\n margin-top: 8px;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.45;\n }\n\n .${Yw}[data-theme="dark"] .gh-usage-monitor-footnote {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n @media (max-width: 640px) {\n .${Yw} .gh-usage-monitor-grid {\n grid-template-columns: 1fr;\n }\n }\n `}removeStyles(){document.getElementById(Zw)?.remove();for(const e of this.injectedStyleRoots)e.getElementById(Zw)?.remove();this.injectedStyleRoots.clear();}applySlotLayout(e){if(!this.root||!this.slot||!e?.isConnected)return;const t=e.getBoundingClientRect(),n=this.slot.parentElement?.getBoundingClientRect(),r=Math.max(280,Math.min(t.width,window.innerWidth-16)),o=n?Math.max(0,t.left-n.left):0;this.slot.style.justifyContent="flex-start",this.slot.style.minHeight="0",this.slot.style.marginBottom="8px",this.root.style.width=`${r}px`,this.root.style.maxWidth="100%",this.root.style.marginLeft=`${o}px`,this.root.style.alignSelf="flex-start";const i=this.root.offsetHeight;this.slot.style.height=`${i+8}px`;}scheduleMidnightReset(){if(null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),!this.settings.autoResetEnabled)return;const e=new Date,t=new Date(e);t.setHours(24,0,0,50);const n=Math.max(1e3,t.getTime()-e.getTime());this.midnightTimer=window.setTimeout(()=>{this.syncCounterRecord(true),this.scheduleRender(0),this.scheduleMidnightReset();},n);}scheduleRender(e=0){this.settings.enabled&&(null!==this.renderTimer&&window.clearTimeout(this.renderTimer),this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.render();},e));}async render(){if(this.settings.enabled&&(this.root||(this.ensureMounted(),this.root)))if(this.renderInFlight)this.rerenderRequested=true;else {this.renderInFlight=true;try{await this.syncCounterRecord();const e=this.getEstimateSnapshot(),t=this.currentRecord.count,n=Math.max(1,this.settings.dailyLimit),r=t/n,o=Math.min(100,Math.max(0,100*r)),i=r>=1?"danger":r>=.8?"warning":"normal";this.root.dataset.level=i,this.root.dataset.theme=this.detectThemeMode();const a=le("usageMonitorSettingsTitle"),s=this.settings.autoResetEnabled?le("usageMonitorTodayUsed"):le("usageMonitorLocallyUsed"),l=le("usageMonitorInputChars"),c=le("usageMonitorLoadedConversationTokens"),d=le("usageMonitorLoadedOutputTokens"),u=le("usageMonitorRequestTokens"),h=le("usageMonitorRoundTripTokens"),g=le("usageMonitorRoundTripDesc"),p=le("usageMonitorResetButton"),m=this.settings.autoResetEnabled?null:le("usageMonitorManualMode"),f=le("usageMonitorContextChars");this.root.replaceChildren(this.buildUsageMonitorPanel({title:a,usageLabel:s,resetButtonLabel:p,roundTripDesc:g,inputCharsLabel:l,loadedConversationLabel:c,loadedOutputLabel:d,requestTokensLabel:u,roundTripLabel:h,contextCharsLabel:f,manualModeLabel:m,count:t,limit:n,percent:o,estimate:e})),this.bindPanelControls(),this.activeAnchor&&this.applySlotLayout(this.activeAnchor);}finally{this.renderInFlight=false,this.rerenderRequested&&(this.rerenderRequested=false,this.scheduleRender(0));}}}async syncCounterRecord(e=false){const t=this.getRecordKey();(e||this.activeRecordKey!==t)&&(this.activeRecordKey=t,this.currentRecord=await async function(e){const t=await nv(),n=Xy(t.records[e]);return t.records[e]||(t.records[e]=n,await rv(t)),n}(t));}getRecordKey(){const e=this.adapter.getCurrentCid?.()||"default";return this.settings.autoResetEnabled?`${this.siteId}::${e}::day::${((e=new Date)=>`${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`)()}`:`${this.siteId}::${e}::manual`}resolveEditor(){const e=this.collectEditorCandidates();return e.length>0?e.sort((e,t)=>this.scoreEditorCandidate(t)-this.scoreEditorCandidate(e))[0]:this.adapter.findTextarea()||this.adapter.getTextareaElement()}collectEditorCandidates(){const e=new Set,t=[];for(const n of this.adapter.getTextareaSelectors()){let r=[];try{r=ds.query(n,{all:!0,shadow:!0})||[];}catch{continue}for(const n of r)n instanceof HTMLElement&&(e.has(n)||(e.add(n),this.adapter.isValidTextarea(n)&&t.push(n)));}return t}scoreEditorCandidate(e){if(!e.isConnected)return Number.NEGATIVE_INFINITY;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return Number.NEGATIVE_INFINITY;let n=0;(e===document.activeElement||e.contains(document.activeElement))&&(n+=1e3);const r=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e);r&&r.isConnected&&(n+=400),n+=t.top/Math.max(window.innerHeight,1)*120;const o=(e.getAttribute("aria-label")||"").toLowerCase(),i=(e.getAttribute("placeholder")||e.placeholder||"").toLowerCase();return /prompt|message|chat|发送|输入|ask|query/.test(`${o} ${i}`)&&(n+=120),n}resolveEditorFromTarget(e){if(!(e instanceof Element))return this.resolveEditor();for(const n of this.adapter.getTextareaSelectors())try{if(e.matches(n))return e;const t=ds.closestComposed(e,n);if(t instanceof HTMLElement)return t}catch{continue}const t=this.resolveEditor();return t&&this.containsInComposedTree(t,e)?t:null}resolveMountAnchor(e){const t=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e),n=[ds.closestComposed(e,"form"),t?ds.closestComposed(t,"form"):null,this.findClosestCommonAncestor(e,t),ds.closestComposed(e,'[role="form"]')].filter(Boolean),r=this.pickBestMountCandidate(n,e,t);if(r)return r;const o=[ds.closestComposed(e,".chat-input-editor-container"),ds.closestComposed(e,".chat-editor"),ds.closestComposed(e,".input-area-container"),ds.closestComposed(e,".input-area"),ds.closestComposed(e,".composer"),ds.closestComposed(e,".footer-input-wrap"),ds.closestComposed(e,".input-container"),ds.closestComposed(e,".editor-container"),ds.getComposedParentElement(e),e.parentElement].filter(Boolean);return this.pickBestMountCandidate(o,e,t)}pickBestMountCandidate(e,t,n){const r=Array.from(new Set(e)).filter(e=>{if(!e?.parentElement)return false;if(e===document.body||e===document.documentElement)return false;if(e.isContentEditable)return false;const t=e.getBoundingClientRect();return t.width>0&&t.height>0}).map(e=>({candidate:e,score:this.scoreMountCandidate(e,t,n)})).sort((e,t)=>t.score-e.score);return r[0]?.candidate||null}scoreMountCandidate(e,t,n){const r=e.getBoundingClientRect(),o=t.getBoundingClientRect(),i=Math.max(1,r.width*r.height);let a=0;const s=this.containsInComposedTree(e,t),l=!!n&&this.containsInComposedTree(e,n);"form"===e.tagName.toLowerCase()&&(a+=520),"form"===e.getAttribute("role")&&(a+=320),s&&(a+=160),l&&(a+=180),s&&l&&(a+=260),e===t.parentElement&&(a-=260);a-=.2*(Math.abs(r.top-o.top)+Math.abs(r.left-o.left)+Math.abs(r.bottom-o.bottom)),a-=i/5e3,r.height<1.4*o.height&&(a-=140);const c=e.parentElement;if(c){const e=window.getComputedStyle(c);if(e.display.includes("flex")&&!e.flexDirection.startsWith("column")&&this.containsInComposedTree(c,t)&&(!n||this.containsInComposedTree(c,n))){const e=c.getBoundingClientRect(),t=Math.max(1,e.width*e.height);t<2.2*i&&t{this.confirmPendingSend();},120)));}async confirmPendingSend(){if(!this.pendingSend)return void(null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));const e=this.pendingSend,t=this.resolveEditor(),n=this.getEditorText(t),r=this.getUserMessageCount(),o=this.adapter.isGenerating?.()??false,i=Date.now()-e.startedAt,a=r>e.preUserCount,s=o&&!e.preGenerating,l=e.normalizedText.length>0&&0===n.length,c=e.normalizedText.length>0&&n.length>0&&n!==e.normalizedText;if(a||s||l&&o||c&&o){this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null);const e=this.getEstimateSnapshot();return await async function(e){const t=Jy(e);if(!t)return;const n=await nv();n.events=ev([...n.events,t]),await rv(n);}({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),siteId:this.siteId,cid:this.adapter.getCurrentCid?.()||"default",sessionId:this.adapter.getSessionId?.()||"",countDelta:1,requestTokens:e.requestTokens,roundTripTokens:e.roundTripMid,loadedConversationTokens:e.loadedConversationTokens,loadedOutputTokens:e.loadedOutputTokens}),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t=await nv(),n=Xy(t.records[e]),r={count:n.count+1,updatedAt:Date.now(),resetAt:n.resetAt};return t.records[e]=r,await rv(t),r}(this.getRecordKey()),void this.scheduleRender(0)}i>4e3&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));}getUserMessageCount(){const e=this.adapter.getUserQuerySelector();if(!e)return 0;try{return (ds.query(e,{all:!0,shadow:!0})||[]).filter(e=>e instanceof HTMLElement&&e.isConnected).length}catch{return 0}}getEditorText(e){return e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?Jw(e.value||""):Jw(e.textContent||""):""}getEstimateSnapshot(){const e=this.resolveEditor(),t=this.getEditorText(e),n=this.getLoadedConversationStats(),r=t.length,o=this.estimateTokens(t),i=this.estimateTokens([n.conversationText,t].filter(Boolean).join("\n")),a=i>0?i+Math.max(32,Math.ceil(.5*i)):0,s=i>0?i+Math.max(128,Math.ceil(2*i)):0,l=a>0||s>0?Math.round((a+s)/2):0;return {inputChars:r,loadedConversationChars:n.conversationChars,loadedConversationTokens:n.conversationTokens,loadedOutputChars:n.outputChars,loadedOutputTokens:n.outputTokens,requestTokens:Math.max(i,o),roundTripMin:a,roundTripMax:s,roundTripMid:l}}getLoadedConversationStats(){const e=this.adapter.getChatContentSelectors();if(!e.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};let t=[];try{t=ds.query(e,{all:!0,shadow:!0})||[];}catch{t=[];}if(0===t.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};const n=this.adapter.getUserQuerySelector(),r=Array.from(new Set(t)),o=[],i=[];r.forEach(e=>{const t=!!n&&this.matchesSelector(e,n),r=t?this.adapter.extractUserQueryMarkdown(e):this.adapter.extractAssistantResponseText(e),a=Jw(r||e.textContent||"");a&&(o.push(a),t||i.push(a));});const a=o.join("\n"),s=i.join("\n");return {conversationText:a,conversationChars:a.length,conversationTokens:this.estimateTokens(a),outputChars:s.length,outputTokens:this.estimateTokens(s)}}matchesSelector(e,t){try{return e.matches(t)}catch{return false}}estimateTokens(e){if(!e)return 0;const t=(e.match(eS)||[]).length,n=(e.match(tS)||[]).length,r=(e.match(nS)||[]).length;return Math.max(0,Math.ceil(1.2*t+n/4+r/2))}detectThemeMode(){const e=document.documentElement.className;if(/\bdark\b/i.test(e))return "dark";if(/\blight\b/i.test(e))return "light";const t=document.body.className;if(/\bdark-theme\b/i.test(t))return "dark";if(/\blight-theme\b/i.test(t))return "light";const n=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===n?"dark":"light"===n?"light":window.matchMedia?.("(prefers-color-scheme: dark)")?.matches?"dark":"light"}buildUsageMonitorPanel({title:e,usageLabel:t,resetButtonLabel:n,roundTripDesc:r,inputCharsLabel:o,loadedConversationLabel:i,loadedOutputLabel:a,requestTokensLabel:s,roundTripLabel:l,contextCharsLabel:c,manualModeLabel:d,count:u,limit:h,percent:g,estimate:p}){const m=document.createElement("div");m.className="gh-usage-monitor-panel";const f=document.createElement("div");f.className="gh-usage-monitor-top";const b=document.createElement("div");b.className="gh-usage-monitor-title",b.textContent=e;const y=document.createElement("div");if(y.className="gh-usage-monitor-meta",d){const e=document.createElement("span");e.className="gh-usage-monitor-badge",e.textContent=d,y.appendChild(e);}const v=document.createElement("div");v.className="gh-usage-monitor-count",v.textContent=`${t}: ${u} / ${h}`;const x=document.createElement("button");x.type="button",x.className="gh-usage-monitor-reset",x.dataset.action="reset-counter",x.textContent=n,y.append(v,x),f.append(b,y);const w=document.createElement("div");w.className="gh-usage-monitor-progress";const S=document.createElement("div");S.className="gh-usage-monitor-progress-bar",S.style.width=`${g.toFixed(1)}%`,w.appendChild(S);const C=document.createElement("div");C.className="gh-usage-monitor-grid",C.append(this.createUsageMonitorItem(o,`${p.inputChars} chars`),this.createUsageMonitorItem(i,`${p.loadedConversationTokens} tokens`),this.createUsageMonitorItem(a,`${p.loadedOutputTokens} tokens`),this.createUsageMonitorItem(s,`${p.requestTokens} tokens`),this.createUsageMonitorItem(l,`${p.roundTripMin}-${p.roundTripMax}`),this.createUsageMonitorItem(c,`${p.loadedConversationChars} chars`));const k=document.createElement("div");return k.className="gh-usage-monitor-footnote",k.textContent=r,m.append(f,w,C,k),m}createUsageMonitorItem(e,t){const n=document.createElement("div");n.className="gh-usage-monitor-item";const r=document.createElement("span");r.className="gh-usage-monitor-label",r.textContent=e;const o=document.createElement("span");return o.className="gh-usage-monitor-value",o.textContent=t,n.append(r,o),n}}const oS=[/^\s*#{1,6}\s+\S/m,/^\s*```/m,/^\s*(?:>|>)\s+\S/m,/^\s*[-*]\s+\S/m,/^\s*\d+\.\s+\S/m],iS=[/\*\*[^*]+\*\*/,/`[^`]+`/,/\[.+\]\(.+\)/],aS=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],sS=[/(^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$)/,/\\\([^\n]+?\\\)/],lS="gh-user-query-markdown-style";function cS(){return "undefined"==typeof window?"":window.__OPHEL_USER_QUERY_MARKDOWN_STYLES__||""}function dS(e){const t=e.trim();return !!t&&(oS.some(e=>e.test(t))||iS.some(e=>e.test(t))||function(e){const t=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(e);return aS.some(e=>e.test(t))||sS.some(e=>e.test(t))}(t))}class uS{adapter;enabled;processedElements=new WeakMap;stopWatch=null;rescanTimer=null;injectedShadowRoots=new WeakSet;codeCopyHandler=null;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}init(){const e=this.adapter.getUserQuerySelector();if(!e)return void console.warn("[UserQueryMarkdownRenderer] No user query selector found for this site");if(this.adapter.usesShadowDOM())this.startRescanTimer();else {this.injectGlobalStyles(),this.initCodeCopyHandler(),this.stopWatch=ds.each(e,e=>{this.processQueryElement(e);},{shadow:true});const t=this.adapter.getSiteId();t!==yo&&t!==Co&&t!==So||this.startRescanTimer();}}injectGlobalStyles(){const e=this.getStyleText();let t=document.getElementById(lS);t||(t=document.createElement("style"),t.id=lS,document.head.appendChild(t)),t.textContent!==e&&(t.textContent=e);}injectStyleToShadowRoot(e){const t=this.getStyleText(),n=e.querySelector(`#${lS}`);if(n)return n.textContent!==t&&(n.textContent=t),void this.injectedShadowRoots.add(e);const r=document.createElement("style");r.id=lS,r.textContent=t,e.prepend(r),this.injectedShadowRoots.has(e)||(e.addEventListener("click",e=>this.handleCodeCopy(e)),this.injectedShadowRoots.add(e));}getStyleText(){return [_l(),ql(),cS()].filter(Boolean).join("\n")}normalizeRenderedContainer(e){e instanceof HTMLElement&&e.style.setProperty("white-space","normal","important");}handleCodeCopy(e){const t=e.target.closest(".gh-code-copy-btn");if(t&&t.closest(".gh-user-query-markdown")){e.preventDefault(),e.stopPropagation();const n=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(n).then(()=>{ld(t,{size:14});}).catch(e=>{console.error("[UserQueryMarkdownRenderer] Copy failed:",e);});}}initCodeCopyHandler(){this.codeCopyHandler||(this.codeCopyHandler=e=>this.handleCodeCopy(e),document.addEventListener("click",this.codeCopyHandler,true));}startRescanTimer(){this.rescanTimer||(setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.adapter.getUserQuerySelector();if(!e)return;const t=ds.query(e,{all:true,shadow:true});for(const n of t)this.processQueryElement(n);}processQueryElement(e){const t=this.adapter.extractUserQueryMarkdown(e);if(!t)return;if(!dS(t))return;if(this.processedElements.get(e)===t)return;const n=$l(t,false,{enableMath:true});if(this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&this.injectStyleToShadowRoot(t.shadowRoot);}const r=this.adapter.replaceUserQueryContent(e,n);let o=e.querySelector(".gh-user-query-markdown");if(!o&&this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&(o=t.shadowRoot.querySelector(".gh-user-query-markdown"));}if(o)return this.normalizeRenderedContainer(o),cd(o,{size:14,color:"#6b7280"}),void this.processedElements.set(e,t);r&&this.processedElements.set(e,t);}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);}destroy(){this.stop(),this.processedElements=new WeakMap,this.injectedShadowRoots=new WeakSet;const e=document.getElementById(lS);e&&e.remove(),this.codeCopyHandler&&(document.removeEventListener("click",this.codeCopyHandler,true),this.codeCopyHandler=null);}}let hS={assistantMermaidRenderer:null,themeManager:null,copyManager:null,layoutManager:null,markdownFixer:null,tabManager:null,watermarkRemover:null,readingHistoryManager:null,modelLocker:null,scrollLockManager:null,userQueryMarkdownRenderer:null,policyRetryManager:null,usageCounterManager:null},gS=null,pS=null;function mS(e){return e.content?.assistantMermaid??true}async function fS(e){const{adapter:t,settings:n}=e;if("fallback"!==t.getAssistantMermaidSupportMode())return hS.assistantMermaidRenderer?.stop(),void(hS.assistantMermaidRenderer=null);mS(n)?hS.assistantMermaidRenderer?hS.assistantMermaidRenderer.updateSettings(true):(pS||(pS=(async()=>{"fallback"===t.getAssistantMermaidSupportMode()&&mS(Li())&&(hS.assistantMermaidRenderer?hS.assistantMermaidRenderer.updateSettings(true):hS.assistantMermaidRenderer=new Cw(t,true));})().finally(()=>{pS=null;})),await pS):hS.assistantMermaidRenderer?.updateSettings(false);}function bS(e){const{adapter:t,settings:n,siteId:r}=e,o=ni(n,r),i=Ym({mode:o.mode,adapter:t,lightPresetId:o.lightStyleId||"google-gradient",darkPresetId:o.darkStyleId||"classic-dark",syncNativePageTheme:n.theme?.syncNativePageTheme??true,apply:true});return hS.themeManager=i,i}async function yS(e){const{adapter:t,settings:n,siteId:r}=e,o=ni(n,r);if("system"===o.mode&&hS.themeManager)return void(await hS.themeManager.setMode("system"));const i="system"===o.mode?window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":"dark"===o.mode?"dark":"light";if(!t.supportsHostThemeSync())return void hS.themeManager?.applyTheme(i);const a=document.documentElement.className,s=/\bdark\b/i.test(a),l=/\blight\b/i.test(a),c=document.body.className,d=/\bdark-theme\b/i.test(c),u=document.body.style.colorScheme;let h="light";s||d||"dark"===u?h="dark":l&&(h="light"),h!==i&&(hS.themeManager&&hS.themeManager.applyTheme(i),t&&"function"==typeof t.toggleTheme&&await t.toggleTheme(i));}function vS(e,t){switch(t){case ho:return e.content?.markdownFix??false;case bo:return e.aistudio?.markdownFix??false;case go:return e.chatgpt?.markdownFix??false;default:return false}}function xS(e){const{adapter:t,settings:n,siteId:r}=e,o=t.getMarkdownFixerConfig(),i=vS(n,r);o&&i&&(hS.markdownFixer=new Ww(o),hS.markdownFixer.start(),console.warn(`[Ophel] MarkdownFixer started for ${t.getName()}`));}function wS(e){const{adapter:t,settings:n,siteId:r}=e,o=ri(n,r),i=ii(n,r),a=ai(n,r),s=a.enabled,l=si(n,r),c=!!t.getCleanModeConfig()&&l.enabled;(o?.enabled||i?.enabled||s||c)&&(hS.layoutManager=new _w(t,o),o?.enabled&&hS.layoutManager.apply(),i?.enabled&&hS.layoutManager.updateUserQueryConfig(i),s&&hS.layoutManager.updateZenMode(a),c&&hS.layoutManager.updateCleanMode(true));}function SS(e){const{adapter:t,settings:n}=e;n.content&&(hS.copyManager=new Aw(n.content,t),n.content.formulaCopy&&hS.copyManager.initFormulaCopy(),n.content.tableCopy&&hS.copyManager.initTableCopy());}function CS(e){const{adapter:t,settings:n}=e;n.tab&&(hS.tabManager=new Kw(t,n.tab),hS.tabManager.start());}function kS(e){const{adapter:t,settings:n,siteId:r}=e;hS.usageCounterManager=new rS(t,n.usageMonitor,r),hS.usageCounterManager.start();}function TS(e){const{settings:t,siteId:n}=e;n!==ho&&n!==mo||!t.content?.watermarkRemoval||(hS.watermarkRemover=new Hd,hS.watermarkRemover.start());}async function ES(e){const{adapter:t,settings:n}=e;if(n.readingHistory?.persistence){gS&&(clearTimeout(gS),gS=null);const e=e=>{hS.readingHistoryManager||(hS.readingHistoryManager=new Vw(t,e.readingHistory),hS.readingHistoryManager.startRecording(),hS.readingHistoryManager.cleanup());};if(await(li||(li=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(Go,t=>{const n=t?.[Go];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=5e3?e(true):chrome.storage.local.remove(Go,()=>e(false)):e(true);}):e(false);}),li))||ui())return void(gS=setTimeout(()=>{gS=null;const t=Li();t.readingHistory?.persistence&&!hS.readingHistoryManager&&e(t);},5e3));if(e(n),n.readingHistory.autoRestore){const{showToast:e}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Bi);return {showToast:e}},void 0);hS.readingHistoryManager.restoreProgress(t=>e(t,3e3)).then(t=>{t&&e(le("restoredPosition"),2e3);});}hS.readingHistoryManager.cleanup();}}function AS(e){const{adapter:t,settings:n,siteId:r}=e,o=oi(n,r);hS.modelLocker=new jw(t,o),o.enabled&&o.keyword&&hS.modelLocker.start();}function MS(e){const{adapter:t,settings:n}=e;hS.scrollLockManager=new Qw(t,n);}function IS(e){const{adapter:t,settings:n}=e;hS.userQueryMarkdownRenderer=new uS(t,n.content?.userQueryMarkdown??true);}function LS(e){const{adapter:t,settings:n,siteId:r}=e;r===mo&&(hS.policyRetryManager=new Gw(t,n.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3}));}const NS=Object.freeze(Object.defineProperty({__proto__:null,initAssistantMermaidRenderer:fS,initCopyManager:SS,initCoreModules:async function(e){return bS(e),setTimeout(()=>yS(e),1e3),xS(e),wS(e),SS(e),CS(e),TS(e),kS(e),await ES(e),AS(e),MS(e),IS(e),await fS(e),LS(e),hS},initLayoutManager:wS,initMarkdownFixer:xS,initModelLocker:AS,initPolicyRetryManager:LS,initReadingHistoryManager:ES,initScrollLockManager:MS,initTabManager:CS,initThemeManager:bS,initUrlChangeObserver:function(e){const{adapter:t}=e;let n=window.location.pathname,r=null;const i=async()=>{const e=window.location.pathname;e!==n&&(n=e,console.warn("[Ophel] URL changed, reinitializing modules..."),r&&(clearTimeout(r),r=null),hS.readingHistoryManager&&(hS.readingHistoryManager.stopRecording(),r=setTimeout(async()=>{r=null;const{showToast:e}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Bi);return {showToast:e}},void 0);if(!ui()){await(hS.readingHistoryManager?.restoreProgress(t=>e(t,3e3)))&&e(le("restoredPosition"),2e3);}hS.readingHistoryManager?.startRecording();},1500)),window.dispatchEvent(new Event("gh-url-change")),hS.tabManager&&(hS.tabManager.resetConversationTitleCache(),[300,800,1500].forEach(e=>setTimeout(()=>hS.tabManager?.updateTabName(true),e))),t.findTextarea(),hS.usageCounterManager?.handleUrlChange(),hS.modelLocker?.relock(300));};window.addEventListener("popstate",i);const a=history.pushState,s=history.replaceState;history.pushState=function(...e){a.apply(this,e),i();},history.replaceState=function(...e){s.apply(this,e),i();},setInterval(i,1e3);},initUsageCounterManager:kS,initUserQueryMarkdownRenderer:IS,initWatermarkRemover:TS,subscribeModuleUpdates:function(e){const{adapter:t,siteId:n}=e;let r=Li().language;Ni(e=>{e.language&&e.language!==r&&(r=e.language,ae(e.language),hS.assistantMermaidRenderer?.refreshLocalizedTexts(),hS.layoutManager?.refreshLocalizedTexts());const o=ni(e,n);o&&hS.themeManager&&(hS.themeManager.setNativeThemeOverrideEnabled(e.theme?.syncNativePageTheme??true),hS.themeManager.setPresets(o.lightStyleId||"google-gradient",o.darkStyleId||"classic-dark"));const i=oi(e,n);i&&hS.modelLocker&&hS.modelLocker.updateConfig(i),e&&hS.scrollLockManager&&hS.scrollLockManager.updateSettings(e);const a=t.getMarkdownFixerConfig(),s=vS(e,n);a&&s?(hS.markdownFixer||(hS.markdownFixer=new Ww(a)),hS.markdownFixer.start()):hS.markdownFixer?.stop();const l=ri(e,n),c=ii(e,n),d=ai(e,n),u=d.enabled,h=si(e,n),g=!!t.getCleanModeConfig()&&h.enabled;hS.layoutManager?(hS.layoutManager.updateConfig(l),hS.layoutManager.updateUserQueryConfig(c),hS.layoutManager.updateZenMode(d),hS.layoutManager.updateCleanMode(g)):(l?.enabled||c?.enabled||u||g)&&(hS.layoutManager=new _w(t,l),l?.enabled&&hS.layoutManager.apply(),c?.enabled&&hS.layoutManager.updateUserQueryConfig(c),u&&hS.layoutManager.updateZenMode(d),g&&hS.layoutManager.updateCleanMode(true)),!e||n!==ho&&n!==mo||(e.content?.watermarkRemoval?(hS.watermarkRemover||(hS.watermarkRemover=new Hd),hS.watermarkRemover.start()):hS.watermarkRemover?.stop()),e?.tab&&(hS.tabManager?hS.tabManager.updateSettings(e.tab):(hS.tabManager=new Kw(t,e.tab),hS.tabManager.start())),e?.usageMonitor&&(hS.usageCounterManager?hS.usageCounterManager.updateSettings(e.usageMonitor):(hS.usageCounterManager=new rS(t,e.usageMonitor,n),hS.usageCounterManager.start())),e?.readingHistory&&(hS.readingHistoryManager?hS.readingHistoryManager.updateSettings(e.readingHistory):e.readingHistory.persistence&&(hS.readingHistoryManager=new Vw(t,e.readingHistory),hS.readingHistoryManager.startRecording())),e?.content&&(hS.copyManager?hS.copyManager.updateSettings(e.content):(hS.copyManager=new Aw(e.content),e.content.formulaCopy&&hS.copyManager.initFormulaCopy(),e.content.tableCopy&&hS.copyManager.initTableCopy()),e.content.userQueryMarkdown?hS.userQueryMarkdownRenderer?hS.userQueryMarkdownRenderer.updateSettings(true):hS.userQueryMarkdownRenderer=new uS(t,true):hS.userQueryMarkdownRenderer?.updateSettings(false)),fS({adapter:t,settings:e}).catch(e=>{console.error("[Ophel] Assistant Mermaid renderer update failed:",e);}),e?.geminiEnterprise&&n===mo&&hS.policyRetryManager&&hS.policyRetryManager.updateSettings(e.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3});});},syncHostThemeWithSettings:yS},Symbol.toStringTag,{value:"Module"})); })(__OphelGeminiWatermarkRemover);