// ==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.1.2 // @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@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-markdown-vendor-ophel-1.1.2.js // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-gemini-watermark-remover-1.0.17-ophel-1.1.2.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@d7ae686a5f3e50957a415a92051287b578d1a255/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@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.de.beca49185baa.json // @resource ophelLocaleEn https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.en.11f767c6a79d.json // @resource ophelLocaleEs https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.es.048e6833b34b.json // @resource ophelLocaleFr https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.fr.daacdbf55cf5.json // @resource ophelLocaleJa https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.ja.17f5eba32451.json // @resource ophelLocaleKo https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.ko.6f72bd80a062.json // @resource ophelLocalePt https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.pt.ca16af131f5c.json // @resource ophelLocaleRu https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.ru.7601c0985a4c.json // @resource ophelLocaleZhCN https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.zh-CN.5794ae290bc9.json // @resource ophelLocaleZhTW https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.locale.zh-TW.031a3fd30cf9.json // @resource ophelMarkdownPreviewStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.markdown-preview.a99d491d0b81.css // @resource ophelNotificationBrightAlert https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-sound-bright-alert.568967a3d9f8.ogg // @resource ophelNotificationDefault https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-sound-default.15d3cda1ee80.mp3 // @resource ophelNotificationGlassPing https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-sound-glass-ping.2379b58f953e.ogg // @resource ophelNotificationSoftChime https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-sound-soft-chime.063564703b60.ogg // @resource ophelSiteIcons https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.site-icons.2c0540f606ea.json // @resource ophelStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.user.dc5699225ba3.css // @resource ophelUserQueryMarkdownStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel.user-query-markdown.bf5242eedc63.css // @resource ophelWatermarkBg48 https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/userscript-assets/ophel-watermark-bg-48.4afc99afe0ef.png // @resource ophelWatermarkBg96 https://cdn.jsdelivr.net/gh/urzeye/ophel@d7ae686a5f3e50957a415a92051287b578d1a255/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,q=i.useImperativeHandle,R=i.useInsertionEffect,P=i.useLayoutEffect,D=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:q,useInsertionEffect:R,useLayoutEffect:P,useMemo:D,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 Q="OPHEL_GEMINI_CANVAS_CODE_REQUEST",V="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!==Q)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:V,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","promptChains","folders","tags","readingHistory","claudeSessionKeys","conversations","ophel:releaseNotesState","ophel:clearAllFlag","ophel:restoreFlag"];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(()=>Jm),void 0),o(()=>Promise.resolve().then(()=>hC),void 0),o(()=>Promise.resolve().then(()=>FC),void 0),o(()=>Promise.resolve().then(()=>KC),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(vT){throw c(),vT}})();const{useSettingsStore:d,getSettingsState:u}=await o(async()=>{const{useSettingsStore:e,getSettingsState:t}=await Promise.resolve().then(()=>Wi);return {useSettingsStore:e,getSettingsState:t}},void 0),{useConversationsStore:h}=await o(async()=>{const{useConversationsStore:e}=await Promise.resolve().then(()=>rf);return {useConversationsStore:e}},void 0),{useFoldersStore:g}=await o(async()=>{const{useFoldersStore:e}=await Promise.resolve().then(()=>df);return {useFoldersStore:e}},void 0),{useTagsStore:p}=await o(async()=>{const{useTagsStore:e}=await Promise.resolve().then(()=>pf);return {useTagsStore:e}},void 0),{usePromptsStore:m}=await o(async()=>{const{usePromptsStore:e}=await Promise.resolve().then(()=>sb);return {usePromptsStore:e}},void 0),{useClaudeSessionKeysStore:f}=await o(async()=>{const{useClaudeSessionKeysStore:e}=await Promise.resolve().then(()=>sS);return {useClaudeSessionKeysStore:e}},void 0),{useReadingHistoryStore:b}=await o(async()=>{const{useReadingHistoryStore:e}=await Promise.resolve().then(()=>Cw);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(()=>yT);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,qe=(e,t,n)=>i.createElement(e,function(e,t){return void 0===t?e??{}:{...e??{},key:t}}(t,n)),Re=qe,Pe=({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:[ qe("circle",{cx:"12",cy:"12",r:"4"}), qe("line",{x1:"12",y1:"2",x2:"12",y2:"4"}), qe("line",{x1:"12",y1:"20",x2:"12",y2:"22"}), qe("line",{x1:"4.93",y1:"4.93",x2:"6.34",y2:"6.34"}), qe("line",{x1:"17.66",y1:"17.66",x2:"19.07",y2:"19.07"}), qe("line",{x1:"2",y1:"12",x2:"4",y2:"12"}), qe("line",{x1:"20",y1:"12",x2:"22",y2:"12"}), qe("line",{x1:"4.93",y1:"19.07",x2:"6.34",y2:"17.66"}), qe("line",{x1:"17.66",y1:"6.34",x2:"19.07",y2:"4.93"})]}),De=({size:e=18,color:t="currentColor",className:n=""})=>qe("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:qe("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=""})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:qe("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=""})=>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:[ qe("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), qe("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),_e=({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:[ qe("circle",{cx:"12",cy:"5",r:"2.5"}), qe("line",{x1:"12",y1:"7.5",x2:"12",y2:"22"}), qe("line",{x1:"7",y1:"10",x2:"17",y2:"10"}), qe("path",{d:"M4 14C4 19 8 22 12 22C16 22 20 19 20 14"}), qe("path",{d:"M1.5 16.5L4 14L6.5 16.5"}), qe("path",{d:"M17.5 16.5L20 14L22.5 16.5"})]}),Oe=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 1024 1024",fill:"none",className:n,children:[ qe("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}), qe("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=""})=>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:[ qe("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), qe("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),Fe=({size:e=18,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",width:e,height:e,...r},children:[ qe("path",{d:"M15 3h6v6"}), qe("path",{d:"M10 14 21 3"}), qe("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),Ue=({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:[ qe("circle",{cx:"12",cy:"12",r:"3"}), qe("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"})]}),He=({size:e=18,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:[ qe("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"}), qe("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"})]}),We=({size:e=18,color:t="currentColor",className:n=""})=>qe("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:qe("line",{x1:"5",y1:"12",x2:"19",y2:"12"})}),je=({size:e=18,color:t="currentColor",className:n="",style:r})=>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:[ qe("path",{d:"M192 192m32 0l0 0q32 0 32 32l0 640q0 32-32 32l0 0q-32 0-32-32l0-640q0-32 32-32Z",fill:t}), qe("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}), qe("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}), qe("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}), qe("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}), qe("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}), qe("path",{d:"M224 224m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0Z",fill:t})]}),Ge=({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:[ qe("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}), qe("polyline",{points:"14 2 14 8 20 8"}), qe("line",{x1:"16",y1:"13",x2:"8",y2:"13"}), qe("line",{x1:"16",y1:"17",x2:"8",y2:"17"}), qe("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),Qe=({size:e=18,color:t="currentColor",className:n=""})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:qe("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=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ qe("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"}), qe("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"}), qe("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"}), qe("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"})]}),Ke=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("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"}), qe("circle",{cx:"8",cy:"10.5",r:"1",fill:t,stroke:"none"}), qe("circle",{cx:"12",cy:"10.5",r:"1",fill:t,stroke:"none"}), qe("circle",{cx:"16",cy:"10.5",r:"1",fill:t,stroke:"none"})]}),Ze=({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:[ qe("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), qe("polyline",{points:"17 8 12 3 7 8"}), qe("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),Ye=({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:[ qe("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), qe("polyline",{points:"7 10 12 15 17 10"}), qe("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),Xe=({size:e=18,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block"},children:[ qe("path",{d:"M198.4 922.496H512a44.8 44.8 0 1 1 0 89.6H198.4a89.6 89.6 0 0 1-89.6-89.6v-806.4a89.6 89.6 0 0 1 89.6-89.6h627.2a89.6 89.6 0 0 1 89.6 89.6v403.2a44.8 44.8 0 0 1-89.6 0v-403.2H198.4v806.4z",fill:t}), qe("path",{d:"M769.6 986.496a41.6 41.6 0 0 0 41.6-41.6v-291.2a41.6 41.6 0 0 0-83.2 0v291.2c0 22.976 18.624 41.6 41.6 41.6z",fill:t}), qe("path",{d:"M742.4 994.432a38.4 38.4 0 0 0 54.4 0l100.736-100.8a38.4 38.4 0 0 0-54.272-54.336l-73.664 73.6-73.6-73.6a38.4 38.4 0 0 0-49.024-4.48l-5.312 4.48a38.4 38.4 0 0 0 0 54.336l100.8 100.8zM691.2 295.296a44.8 44.8 0 1 1 0 89.6H332.8a44.8 44.8 0 0 1 0-89.6h358.4zM512 474.496a44.8 44.8 0 0 1 0 89.6H332.8a44.8 44.8 0 0 1 0-89.6H512z",fill:t})]}),Je="M12 3v12",et="m7 10 5 5 5-5",tt="M5 21h14",nt=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("path",{d:"M4 6h6"}), qe("path",{d:"M4 10h9"}), qe("path",{d:"M4 14h9"}), qe("path",{d:"M4 18h6"}), qe("path",{d:"M18 5v14"}), qe("path",{d:"m15.5 7.5 2.5-2.5 2.5 2.5"}), qe("path",{d:"m15.5 16.5 2.5 2.5 2.5-2.5"})]}),rt=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("path",{d:"M4 6h9"}), qe("path",{d:"M4 12h9"}), qe("path",{d:"M4 18h9"}), qe("path",{d:"M18 3v6"}), qe("path",{d:"m15.5 6.5 2.5 2.5 2.5-2.5"}), qe("path",{d:"M18 21v-6"}), qe("path",{d:"m15.5 17.5 2.5-2.5 2.5 2.5"})]}),ot=({size:e=18,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),it=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), qe("polyline",{points:"5 12 12 5 19 12"})]}),at=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), qe("polyline",{points:"19 12 12 19 5 12"})]}),st=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),lt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),ct=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:qe("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})}),dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),ut=({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:[ qe("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}), qe("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}), qe("path",{d:"M486.3 383.8h50v384h-50z",fill:t}), qe("path",{d:"M513 599h94.5v50H513zM513 717h94.5v50H513z",fill:t})]}),ht=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),gt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),pt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),mt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("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"})}),ft=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z M9 12l2 2 4-4"})}),bt=({size:e=20,color:t="currentColor",className:n="",style:r,filled:o=false})=>qe("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:qe("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"})}),yt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}),vt=({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},fill:t,children:[ qe("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"}), qe("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"})]}),xt=({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:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ qe("circle",{cx:12,cy:12,r:10}), qe("line",{x1:12,y1:16,x2:12,y2:12}), qe("line",{x1:12,y1:8,x2:12.01,y2:8})]}),wt=({size:e=16,color:t="currentColor",className:n="",style:r})=>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:[ qe("rect",{x:"100",y:"282",width:"824",height:"80",rx:"40",fill:t}), qe("rect",{x:"100",y:"472",width:"824",height:"80",rx:"40",fill:t}), qe("rect",{x:"100",y:"662",width:"824",height:"80",rx:"40",fill:t})]}),St=({size:e=18,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),Ct=({size:e=18,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),kt=({size:e=18,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),Tt=({size:e=18,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),Et=({size:e=20,className:t=""})=>Re("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ qe("path",{d:"M15 3h6v6"}), qe("path",{d:"M9 21H3v-6"}), qe("path",{d:"M21 3l-7 7"}), qe("path",{d:"M3 21l7-7"})]}),At=({size:e=20,className:t=""})=>Re("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ qe("path",{d:"M4 14h6v6"}), qe("path",{d:"M20 10h-6V4"}), qe("path",{d:"M14 10l7-7"}), qe("path",{d:"M3 21l7-7"})]}),Mt=({size:e=20,className:t=""})=>qe("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:qe("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"})}),It=({size:e=20,className:t="",style:n})=>qe("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:qe("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"})}),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:[ qe("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",ry:"2"}), qe("line",{x1:"6",y1:"8",x2:"6",y2:"8"}), qe("line",{x1:"10",y1:"8",x2:"10",y2:"8"}), qe("line",{x1:"14",y1:"8",x2:"14",y2:"8"}), qe("line",{x1:"18",y1:"8",x2:"18",y2:"8"}), qe("line",{x1:"6",y1:"12",x2:"6",y2:"12"}), qe("line",{x1:"10",y1:"12",x2:"10",y2:"12"}), qe("line",{x1:"14",y1:"12",x2:"14",y2:"12"}), qe("line",{x1:"18",y1:"12",x2:"18",y2:"12"}), qe("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]}),Nt=({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:[ qe("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}), qe("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),qt=({size:e=18,color:t="currentColor",className:n="",style:r})=>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:[ qe("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}), qe("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}), qe("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})]}),Rt=({size:e=16,className:t="",...n})=>Re("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:[ qe("circle",{cx:"12",cy:"12",r:"1.5",className:"dot dot-2"}), qe("circle",{cx:"19",cy:"12",r:"1.5",className:"dot dot-3"}), qe("circle",{cx:"5",cy:"12",r:"1.5",className:"dot dot-1"}), qe("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 "})]}),Pt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("path",{d:"M18 15l-6-6-6 6"})}),Dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("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:qe("path",{d:"M6 9l6 6 6-6"})}),Bt=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}), qe("path",{d:"m14.5 9-5 5"}), qe("path",{d:"m9.5 9 5 5"})]}),$t=({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("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"}), qe("path",{d:"M7 7h.01"})]}),_t=({size:e=24,className:t,color:n="currentColor"})=>Re("svg",{width:e,height:e,viewBox:"0 0 1024 1024",className:t,style:{color:n},children:[ qe("path",{d:"M123.648 178.346667C361.642667-98.602667 802.986667-43.946667 967.936 279.68h-396.501333c-71.424 0-117.546667-1.621333-167.509334 24.661333-58.709333 30.933333-102.997333 88.234667-118.485333 155.52L123.648 178.389333z",fill:"#EA4335"}), qe("path",{d:"M341.674667 512c0 93.866667 76.330667 170.24 170.154666 170.24 93.866667 0 170.154667-76.373333 170.154667-170.24s-76.330667-170.24-170.154667-170.24c-93.866667 0-170.154667 76.373333-170.154666 170.24z",fill:"#4285F4"}), qe("path",{d:"M577.877333 734.848c-95.530667 28.373333-207.274667-3.114667-268.501333-108.8-46.762667-80.64-170.24-295.765333-226.346667-393.557333-196.565333 301.226667-27.136 711.808 329.685334 781.866666l165.12-279.509333z",fill:"#34A853"}), qe("path",{d:"M669.866667 341.76a233.130667 233.130667 0 0 1 43.008 286.634667c-40.576 69.973333-170.154667 288.682667-232.96 394.581333 367.658667 22.656 635.733333-337.664 514.645333-681.258667H669.866667z",fill:"#FBBC05"})]}),Ot=({size:e=24,className:t,color:n="currentColor"})=>qe("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:qe("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"})}),zt=({size:e=24,className:t,color:n="currentColor"})=>Re("svg",{width:e,height:e,viewBox:"0 0 1024 1024",className:t,style:{color:n},children:[ qe("path",{d:"M28.16 514.56c0 268.8 217.6 486.4 486.4 486.4s486.4-217.6 486.4-486.4-217.6-486.4-486.4-486.4-486.4 217.6-486.4 486.4z",fill:n}), qe("path",{d:"M440.32 258.048c139.264 140.288 142.336 144.384 135.68 193.024-2.048 16.384 0 28.672 0 29.696 0 40.96 138.752 164.352 218.624 253.952 39.424 44.032 64 78.848 53.248 109.056-5.12 14.336-17.92 27.648-34.304 31.744-32.768 8.192-67.072-26.112-117.76-78.336-145.408-150.016-197.632-204.8-251.392-194.56-13.824 2.56-11.264 7.68-25.6 8.704-35.84 2.56-80.896-34.304-193.024-146.432C121.856 360.448 91.648 322.56 98.304 304.128c7.68-19.456 26.112-5.12 113.152 79.872l105.472 103.424 29.184-28.672 29.184-28.672-103.424-103.424c-68.608-69.632-97.28-106.496-87.04-112.64 10.752-6.656 52.736 27.648 117.248 90.624L401.92 404.48l30.208-28.672 29.184-30.208-99.84-100.352C274.432 157.184 250.88 115.2 287.744 115.2c5.12 0 73.728 64.512 152.576 142.848z",fill:"#FFFFFF"})]}),Ft=({size:e=24,className:t})=>qe("img",{src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAXrSURBVFhH1Vfrb1N1GD6nXXd6XXtOrxvIzS8YIwgYEyEigWAwEUOQgCGQQBTjB4iRRGRIDCLXcJP13q0D+eAtMUQT7wl4jdwcksnWXbt1RdAg6l/w+PxOT0e3tcM6/OCbvDtt19/vfd73fd5LpTEiy5JkMhlv7pbwTlncyWdVYjLzT7WHSkU4U+Udsq8B8rylkBR78RNeUlN4/mMZdcbqkEyzl8Hkm4zCB5WE4Te/mkZduhvqrq+hPLp+JBCZ3ogUVRLxP/GdouFau2RfuA6exs/gO/ErlB3vocL54gGb5Dt8DoFEP3zRPLyJG3C98S2UReshK47Cd4aBMKcj9LZhWXFKymMbePYr+JO98Cb7oKXzUA6dG+nQGOElwW1foj6agz8yAF8sB028jmWh7TkL6+J1EOGsJLLVKdkWboT2+vcIJIcQpFEtkaEjnfC15ODY9jEjIMg4jgQ2nSaAPI32MBK9CIb7EGzKIkBAoWgfPDtPw75kI2pmPQHLQythnrcCMvNbu+QFuHZ/B396CFpqAJ5IP9xNXQTSjVC8Aw3JAajPvj0eBwohUZ+J6wBCkQzq4zxMo8Ewo9E0gEBTL2YkOzHzVA7B+HUE0n/Ay9yqb11H6NRNepmHI9ENZ7KHYc/R+KAOIBDvJIAc3KuPGQDKhV8vF0myP7UdIYa+gcYaIln4o73kg+AENcbXkQ74wp1QI70FL+N9hvZCjTFCzLdQLcG0UZ3RDOqi3fClBqE8+bIOQDZsjRQjN4JwgQTDHc4yCoO6YZUXFFUjiBGaEMbKqyeZhZUO2PhabcnCvIgcElK20RkALHOWwU8AHobPkxiEGp8YACXWDxuf7tYuyHPYX4SUJaJRn+Z75zJ/JEyKOYvzOVEAkT5ygveke2CaMWccDhRrWG2A69jPOvF08k0gBYIDqnAiNgD3kXaYeLdupDyAgoiGox5pg+/NXrgPdsJLsk0EQIDkU5v64D3QVtLMyoqBigy1NX6kp8CfGqLRUQZHa1nDQgtV4KLxYCoP944P2YSK7K8UgRqFWis5N59EHcnjDAuvyxgt1XGMayRxHfuHN5GHc3MzJLNFkoWNEWKQz+S7B+7GL+DfdwGBgz8iyNCLJjTcAwz1xrMj9Lax0ToILT4ET5RRjOXhOXgRnn0/oG775zD7ppRwYbj8lmPSyT9peAD19L6ejUVokM3lXwMQyrtEpPzkj5fddfo7t6DMXT62HOVah+RY0Qj31vfhO9rGxpGBp5kkZEjFMCrqnQCI0iuqJlpy/ArbdhtCh85AfamZ7XgrZI7p8mIgsq3ZCVdrBq5UBy+tLgJjAEQvMZLn4Vn1YsHryuse88F9QIhl6XNwtPbDnuzSG1EpgEJIS3Q8AAJ8hIModhWuxWsLAGqt/FOpCgxCylPuhz3FPpBiDycRRS8oajUABHg/B1UwfBWWyTONvFcyTpGnPQh52SaYN+yFO9rO/IsQUqsAUKoqR7M31Q4tfAnOtfthW/I8zNMeMCpgWAo5MU+ajVouH7UncrC29rAJZUieLo5eEQG246LSK2G4MKbZYhPX4Epe06PlSfWUAOCITnbA03KZZG6HO/YLt6vf4TjejZqZD5dWQQGAZco8lhz7/4kbsB26iND+s9Be+YBLCMnWlOPsF8MpBxf3RVFWDWxSwXAOSuovmLiY2Dls3C1XdcMqtyk31zBH8xVYd72LuqNnuBsOcS+4BWv4N8j3LSifDsvUubDMehxm/1RIFkEWSXI8/RoNcqBE2FS4HzjiPeyS3Zh0vAuh45x2yVswtdyEjSVbl/qJEcpQmSoS2LZ6R8GQRZFMgekwzeJqPmP+6BTcWWoWrIRvzwX4w2Ll4nglQUUK6sOiLLk3kHDu5i495FqK29KBb2B9ZFX1hhgTIy/F0BTf8+H0Stb566FsSUPZ+wnch8/De/gy/JycXq7ynt2fwrklyd8SayA7Nf3MmLtEDxivCirK8BQzpMbC3Y3djONVrOL6U3xWKqPP3BW54+884eV/YbisCCCl+r8USfobNcUmGxboH7gAAAAASUVORK5CYII=",width:e,height:e,className:t,alt:"","aria-hidden":"true",style:{display:"block",width:e,height:e}}),Ut=({size:e=24,className:t})=>Re("svg",{width:e,height:e,viewBox:"0 0 48 48",className:t,children:[ qe("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"}), qe("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"}), qe("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"}), qe("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"}), qe("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"})]}),Ht=({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:[ qe("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), qe("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),Wt=({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:[ qe("polyline",{points:"3 6 5 6 21 6"}), qe("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"}), qe("line",{x1:"10",y1:"11",x2:"10",y2:"17"}), qe("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]}),jt=({size:e=18,color:t="currentColor",className:n="",filled:r=false,style:o})=>qe("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...o},children: qe("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})}),Gt=({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:[ qe("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}), qe("circle",{cx:"12",cy:"12",r:"3"})]}),Qt=({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:[ qe("path",{d:"M2 8a10.645 10.645 0 0 0 20 0"}), qe("path",{d:"m4 15 1.726-2.05"}), qe("path",{d:"m9 18 .722-3.25"}), qe("path",{d:"m15 18-.722-3.25"}), qe("path",{d:"m20 15-1.726-2.05"})]}),Vt=({size:e=16,className:t="",...n})=>qe("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:qe("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"})}),Kt=({size:e=16,className:t="",...n})=>Re("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:[ qe("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"}), qe("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"})]}),Zt=({size:e=16,className:t="",...n})=>Re("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:[ qe("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"}), qe("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"})]}),Yt=({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:[ qe("circle",{cx:"11",cy:"11",r:"8"}), qe("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),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:[ qe("circle",{cx:"12",cy:"12",r:"10"}), qe("polyline",{points:"12 6 12 12 16 14"})]}),Jt=({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 Re("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:[ qe("defs",{children:a&&Re("linearGradient",{id:o,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[ qe("stop",{offset:"0%",stopColor:"#22d3ee"}), qe("stop",{offset:"100%",stopColor:"#6366f1"})]})}), Re("g",{style:{fill:s,stroke:s,strokeWidth:12,strokeLinejoin:"round",strokeLinecap:"round"},children:[ qe("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"}), qe("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"}), qe("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"}), qe("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"})]})]})},en=({size:e=15,color:t="currentColor",className:n=""})=>qe("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:qe("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})}),tn=({size:e=18,color:t="currentColor",className:n=""})=>qe("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:qe("polyline",{points:"20 6 9 17 4 12"})}),nn=({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:[ qe("line",{x1:"2",y1:"2",x2:"2",y2:"22"}), qe("rect",{x:"6",y:"4",width:"16",height:"16",rx:"2"}), qe("polyline",{points:"15 9 11 12 15 15"})]}),rn=({size:e=18,color:t="currentColor",className:n=""})=>qe("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",width:e,height:e},children:qe("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})}),on=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),an=({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:qe("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"})}),sn=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("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:[ qe("path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"}), qe("polyline",{points:"17 21 17 13 7 13 7 21"}), qe("polyline",{points:"7 3 7 8 15 8"})]}),ln=({size:e=20,color:t="currentColor",className:n="",style:r})=>Re("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:[ qe("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}), qe("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),cn=({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},fill:t,children:[ qe("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"}), qe("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"})]}),dn=({size:e=16,color:t="currentColor",accentColor:n="#ff8910",className:r=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:r,style:{display:"block"},children:[ qe("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}), qe("path",{d:"M3.364571 558.592h227.584v146.285714l189.622858-182.857143-189.622858-182.857142v146.285714H3.364571z",fill:n})]}),un=({size:e=16,color:t="currentColor",className:n=""})=>Re("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ qe("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}), qe("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})]}),hn=({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:[ qe("path",{d:"M3 21c3-3 4-6 4-9 0-3.31-2.69-6-6-6v2c2.21 0 4 1.79 4 4h-2a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h2z",fill:t,stroke:"none"}), qe("path",{d:"M15 21c3-3 4-6 4-9 0-3.31-2.69-6-6-6v2c2.21 0 4 1.79 4 4h-2a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h2z",fill:t,stroke:"none"})]}),gn="scrollTop",pn="scrollBottom",mn="goToAnchor",fn="togglePanel",bn="togglePanelMode",yn="toggleTheme",vn="openSettings",xn="switchTab1",wn="switchTab2",Sn="switchTab3",Cn="toggleUserQueries",kn="onlyUserQueries",Tn="toggleBookmarks",En="locateOutline",An="searchOutline",Mn="refreshOutline",In="prevHeading",Ln="nextHeading",Nn="toggleOutlineExpand",qn="expandLevel1",Rn="expandLevel2",Pn="expandLevel3",Dn="expandLevel4",Bn="expandLevel5",$n="expandLevel6",_n="newConversation",On="refreshConversations",zn="locateConversation",Fn="prevConversation",Un="nextConversation",Hn="exportConversation",Wn="copyLatestReply",jn="copyLastCodeBlock",Gn="toggleScrollLock",Qn="toggleZenMode",Vn="focusInput",Kn="openGlobalSearch",Zn="stopGeneration",Yn="togglePromptQueue",Xn="showShortcuts",Jn="showModelSelector",er="openClaudeSettings",tr="switchClaudeKey",nr="openGeminiSettings",rr="openThemeSettings",or="openModelLockSettings",ir={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"}},ar={navigation:{labelKey:"shortcutCategoryNavigation",label:"导航"},panel:{labelKey:"shortcutCategoryPanel",label:"面板"},outline:{labelKey:"shortcutCategoryOutline",label:"大纲"},conversation:{labelKey:"shortcutCategoryConversation",label:"会话"},edit:{labelKey:"shortcutCategoryEdit",label:"交互控制"},settings:{labelKey:"shortcutCategorySettings",label:"设置"}},sr={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}},lr={enabled:true,globalUrl:"https://gemini.google.com",keybindings:sr},cr={Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/"},dr={"å":"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 ur(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(cr[t])return cr[t]}return dr[e]?dr[e]:e}function hr(e){if(!e)return e;return {key:ur(e.key),alt:!!e.alt,ctrl:!!e.ctrl||!!e.meta,shift:!!e.shift}}function gr(e){return e?{enabled:e.enabled??true,globalUrl:e.globalUrl||lr.globalUrl,keybindings:(t=e.keybindings,(t?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,null===t?null:hr(t)])):t)||lr.keybindings)}:e;var t;}function pr(e,t=false){const n=hr(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=ur(n.key),i={ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",",":","}[o]||o.toUpperCase();return r.push(i),r.join(t?"":"+")}function mr(){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 fr="prompts",br="outline",yr="conversations",vr="settings",xr="general",wr="appearance",Sr="features",Cr="siteSettings",kr="globalSearch",Tr="shortcuts",Er="backup",Ar="permissions",Mr="about",Ir="outline",Lr="conversations",Nr="prompts",qr="tab",Rr="reminder",Pr="content",Dr="readingHistory",Br="toolbox",$r="presets",_r="custom",Or="layout",zr="modelLock",Fr={"appearance-sync-native-page-theme":{page:wr},"appearance-preset-light":{page:wr,subTab:$r},"appearance-preset-dark":{page:wr,subTab:$r},"appearance-custom-styles":{page:wr,subTab:_r},"tab-show-notification":{page:Sr,subTab:Rr},"tab-notification-sound":{page:Sr,subTab:Rr},"tab-notification-sound-preset":{page:Sr,subTab:Rr},"tab-notification-volume":{page:Sr,subTab:Rr},"tab-notification-repeat-count":{page:Sr,subTab:Rr},"tab-notification-repeat-interval":{page:Sr,subTab:Rr},"tab-notify-when-focused":{page:Sr,subTab:Rr},"tab-auto-focus":{page:Sr,subTab:Rr},"usage-monitor-enabled":{page:Sr,subTab:Rr},"usage-monitor-daily-limit":{page:Sr,subTab:Rr},"usage-monitor-auto-reset":{page:Sr,subTab:Rr}},Ur=[{prefix:"panel-",route:{page:xr,subTab:"panel"}},{prefix:"quick-buttons-",route:{page:xr,subTab:"shortcuts"}},{prefix:"tools-menu-",route:{page:xr,subTab:"toolsMenu"}},{prefix:"shortcuts-",route:{page:Tr}},{prefix:"shortcut-binding-",route:{page:Tr}},{prefix:"layout-",route:{page:Cr,subTab:Or}},{prefix:"model-lock-",route:{page:Cr,subTab:zr}},{prefix:"gemini-",route:{page:Cr,subTab:"gemini"}},{prefix:"aistudio-",route:{page:Cr,subTab:"aistudio"}},{prefix:"chatgpt-",route:{page:Cr,subTab:"chatgpt"}},{prefix:"claude-",route:{page:Cr,subTab:"claude"}},{prefix:"global-search-",route:{page:kr}},{prefix:"tab-",route:{page:Sr,subTab:qr}},{prefix:"outline-",route:{page:Sr,subTab:Ir}},{prefix:"conversation-",route:{page:Sr,subTab:Lr}},{prefix:"export-",route:{page:Sr,subTab:Lr}},{prefix:"prompt-",route:{page:Sr,subTab:Nr}},{prefix:"reading-history-",route:{page:Sr,subTab:Dr}},{prefix:"content-",route:{page:Sr,subTab:Pr}},{prefix:"appearance-preset-",route:{page:wr,subTab:$r}},{prefix:"appearance-custom-",route:{page:wr,subTab:_r}}],Hr={"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.prompts.quickQuoteEnabled":"prompt-quick-quote-enabled","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"},Wr=e=>{const t=e?.trim();if(t)return Hr[t]??t},jr=e=>{const t=Wr(e);if(t)return Fr[t]?Fr[t]:Ur.find(e=>t.startsWith(e.prefix))?.route},Gr=[{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:"prompt-quick-quote-enabled",title:"Ophel 选区引用",keywords:["prompt","quote","quick quote","selection","引用","选区引用","悬浮条"]},{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(ir).map(([e,t])=>({settingId:`shortcut-binding-${e}`,title:`快捷键:${t.label}`,keywords:["shortcut","shortcuts","keybinding","hotkey","keyboard","快捷键","键位","按键",t.label,t.labelKey,e,t.category]}))],Qr=Object.entries(Hr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),Vr=e=>e.trim().toLowerCase(),Kr=(e,t)=>{const n=Vr(e),r=(e=>Vr(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0))(n);return Gr.map((e,t)=>{const o=Vr(e.title),i=Vr((e.keywords||[]).join(" ")),a=Vr(e.settingId),s=Vr((Qr[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)},Zr={[fr]:{label:"tabPrompts",icon:"✏️",IconComponent:Qe},[yr]:{label:"tabConversations",icon:"💬",IconComponent:Ke},[br]:{label:"tabOutline",icon:"📑",IconComponent:je},[vr]:{label:"tabSettings",icon:"⚙️"}},Yr={scrollTop:{icon:"⬆",labelKey:"scrollTop",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:it},panel:{icon:"✨",labelKey:"panelTitle",canToggle:false,isPanelOnly:true,IconComponent:Jt},floatingToolbar:{icon:"🧰",labelKey:"tools",canToggle:true,isPanelOnly:false,IconComponent:({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:[ qe("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(0 12 12)"}), qe("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(60 12 12)"}), qe("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(120 12 12)"}), qe("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})},globalSearch:{icon:"🔎",labelKey:"navGlobalSearch",canToggle:true,isPanelOnly:false,IconComponent:Yt},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=""})=>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:[ qe("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"}), qe("line",{x1:"12",y1:"7",x2:"12",y2:"13"}), qe("line",{x1:"9",y1:"10",x2:"15",y2:"10"})]})},scrollBottom:{icon:"⬇",labelKey:"scrollBottom",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:at},zenMode:{icon:"🧘",labelKey:"zenModeTitle",canToggle:true,isPanelOnly:false,IconComponent:Gt},settings:{icon:"⚙️",labelKey:"tabSettings",canToggle:true,isPanelOnly:false,IconComponent:Ue}},Xr=["📁","📂","📥","🗂️","📊","📈","📉","📋","💼","📅","📌","📎","📝","✒️","🔍","💡","💻","⌨️","🖥️","🖱️","🐛","🔧","🔨","⚙️","🤖","👾","🧠","⚡","🔥","✨","🎓","📚","🎨","🎭","🎬","🎹","🎵","📷","🖌️","🖍️","🏠","🛒","✈️","🎮","⚽","🍔","☕","❤️","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","⭐","🌟","🎉","🔒","🔑","🚫","✅","❓"],Jr=["#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"],eo=1500,to=2e3,no=3e3,ro="#10b981",oo="#ef4444",io="var(--gh-text-secondary)",ao=[{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"}],so=["settings","prompts","promptChains","folders","tags","conversations","readingHistory"],lo=["conversations","readingHistory"],co=()=>[{id:"default_1",title:le("defaultPromptCodeOptTitle"),content:le("defaultPromptCodeOptContent"),category:le("defaultPromptCodeOptCategory")},{id:"default_2",title:le("defaultPromptTranslateTitle"),content:le("defaultPromptTranslateContent"),category:le("defaultPromptTranslateCategory")}],uo="default_quick_quote_reply",ho=()=>[{id:uo,title:le("quickQuoteReply"),description:"",iconSvg:'',showInSelectionPopover:true,steps:[{id:"default_quick_quote_reply_step",mode:"inline",promptId:"",inlineContent:le("quickQuoteReplyTemplate"),runMode:"insert",splitMode:"none"}],createdAt:1,updatedAt:1}],go=[{id:"inbox",name:"收件箱",icon:"📥",isDefault:true}],po={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}},mo={CLAUDE_KEY:/^sk-ant-sid\d{2}-/},fo=500,bo="claude",yo="gemini",vo="chatgpt",xo="chatglm",wo="gemini-enterprise",So="grok",Co="aistudio",ko="doubao",To="ima",Eo="deepseek",Ao="kimi",Mo="qianwen",Io="qwenai",Lo="yuanbao",No="zai",qo=[{id:vo,name:"ChatGPT",pattern:/chatgpt\.com/,url:"https://chatgpt.com",icon:"💬"},{id:yo,name:"Gemini",pattern:/gemini\.google\.com/,url:"https://gemini.google.com",icon:"🌟"},{id:bo,name:"Claude",pattern:/claude\.(ai|com)/,url:"https://claude.ai",icon:"🎭"},{id:Co,name:"AI Studio",pattern:/aistudio\.google\.com/,url:"https://aistudio.google.com",icon:"🧪"},{id:So,name:"Grok",pattern:/grok\.com/,url:"https://grok.com",icon:"🤖"},{id:wo,name:"Gemini Enterprise",pattern:/business\.gemini\.google/,url:"https://business.gemini.google",icon:"🏢"},{id:ko,name:"Doubao",pattern:/www\.doubao\.com/,url:"https://www.doubao.com",icon:"🌱"},{id:Eo,name:"DeepSeek",pattern:/chat\.deepseek\.com/,url:"https://chat.deepseek.com",icon:"🌀"},{id:Ao,name:"Kimi",pattern:/www\.kimi\.com/,url:"https://www.kimi.com",icon:"🌙"},{id:No,name:"Z.ai",pattern:/chat\.z\.ai/,url:"https://chat.z.ai",icon:"⚡"},{id:xo,name:"ChatGLM",pattern:/chatglm\.cn/,url:"https://chatglm.cn/main/alltoolsdetail?lang=zh",icon:"🧠"},{id:Lo,name:"Yuanbao",pattern:/yuanbao\.tencent\.com/,url:"https://yuanbao.tencent.com",icon:"💎"},{id:Mo,name:"Qianwen",pattern:/www\.qianwen\.com/,url:"https://www.qianwen.com",icon:"🔮"},{id:Io,name:"Qwen Studio",pattern:/chat\.qwen\.ai/,url:"https://chat.qwen.ai",icon:"🪄"},{id:To,name:"ima",pattern:/ima\.qq\.com/,url:"https://ima.qq.com",icon:"🐼"}],Ro="__all__",Po="__recent__",Do="export",Bo="segmentedExport",$o="copyMarkdown",_o="move",Oo="setTag",zo="scrollLock",Fo="modelLock",Uo="cleanup",Ho="settings",Wo=[{id:Do,labelKey:"export",defaultLabel:"Export",IconComponent:Ye,defaultVisible:true},{id:Bo,labelKey:"segmentedExportMenuItem",defaultLabel:"Export segments",IconComponent:Xe,defaultVisible:true},{id:$o,labelKey:"exportToClipboard",defaultLabel:"Copy Markdown",IconComponent:Nt,defaultVisible:true},{id:_o,labelKey:"conversationsMoveTo",defaultLabel:"Move",IconComponent:Oe,defaultVisible:true},{id:Oo,labelKey:"conversationsSetTag",defaultLabel:"Set Tag",IconComponent:$t,defaultVisible:true},{id:zo,labelKey:"shortcutToggleScrollLock",defaultLabel:"Scroll Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("path",{d:"M12 3v12"}), qe("path",{d:"m8 11 4 4 4-4"}), qe("path",{d:"M19 19H5"}), qe("circle",{cx:"12",cy:"11",r:"9",strokeOpacity:"0.3"}), qe("path",{d:"m4.9 4.9 14.2 14.2"})]}),isToggle:true,defaultVisible:true},{id:Fo,labelKey:"modelLockTitle",defaultLabel:"Model Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Re("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:[ qe("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}), qe("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}), qe("circle",{cx:"9",cy:"15",r:"1.5",fill:t,stroke:"none"}), qe("circle",{cx:"15",cy:"15",r:"1.5",fill:t,stroke:"none"}), qe("path",{d:"M9 19h6"})]}),isToggle:true,defaultVisible:true},{id:Uo,labelKey:"cleanup",defaultLabel:"Cleanup",IconComponent:Bt,isDanger:true,defaultVisible:true},{id:Ho,labelKey:"tabSettings",defaultLabel:"Settings",IconComponent:Ue,isSystem:true,defaultVisible:true}],jo=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},Go=e=>e;const Qo=e=>{const t=(e=>e?jo(e):jo)(e),n=e=>function(e,t=Go){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},Vo=e=>Qo;function Ko(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 Zo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then:e=>Zo(e)(n),catch(e){return this}}}catch(n){return {then(e){return this},catch:e=>Zo(e)(n)}}},Yo=(e,t)=>(n,r,o)=>{let i={storage:Ko(()=>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 Zo(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};function Xo(){return "userscript"}function Jo(){try{return !0}catch{return console.warn("[Ophel] Failed to get platform type, falling back to runtime detection"),"undefined"!=typeof GM_info}}function ei(){return function(){if(!Jo())return null;try{return "undefined"==typeof GM_info?null:"string"==typeof GM_info.scriptHandler?GM_info.scriptHandler:null}catch{return null}}()?.toLowerCase().replace(/\s+/g,"").includes("scriptcat")??false}let ti;ti={type:"userscript",storage:{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);},watch(e,t){const n=GM_addValueChangeListener(e,(e,n,r,o)=>{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 ni=Object.freeze(Object.defineProperty({__proto__:null,getPlatformType:Xo,isUserscriptPlatform:Jo,get platform(){return ti}},Symbol.toStringTag,{value:"Module"})),ri=Jo(),oi="ophel:clearAllFlag",ii="ophel_skip_restore",ai={mode:"light",lightStyleId:"google-gradient",darkStyleId:"classic-dark"},si={enabled:false,value:"81",unit:"%"},li={enabled:false,value:"81",unit:"%"},ci={enabled:false,showExitButton:true},di={enabled:true},ui=[{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}],hi={collapsed:ui.map(e=>({...e})),opacity:1,floatingToolbar:{open:true},hideWhenPanelOpen:false,proximityRadius:150},gi={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:ri,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:{...ai},"gemini-enterprise":{...ai},doubao:{...ai},ima:{...ai},deepseek:{...ai},yuanbao:{...ai},zai:{...ai},_default:{...ai}},customStyles:[]},layout:{pageWidth:{gemini:{...si},"gemini-enterprise":{...si},aistudio:{...si},doubao:{...si},ima:{...si},deepseek:{...si},yuanbao:{...si},zai:{...si},_default:{...si}},userQueryWidth:{gemini:{...li},"gemini-enterprise":{...li},aistudio:{...li},doubao:{...li},ima:{...li},deepseek:{...li},yuanbao:{...li},zai:{...li},_default:{...li}},zenMode:{gemini:{...ci},"gemini-enterprise":{...ci},aistudio:{...ci},doubao:{...ci},ima:{...ci},deepseek:{...ci},yuanbao:{...ci},zai:{...ci},_default:{...ci}},cleanMode:{gemini:{...di},"gemini-enterprise":{...di},aistudio:{...di},doubao:{...di},ima:{...di},deepseek:{...di},yuanbao:{...di},zai:{...di},_default:{...di}}},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,quickQuoteEnabled:true},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:ri,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:ui.map(e=>({...e})),opacity:hi.opacity,floatingToolbar:{...hi.floatingToolbar},hideWhenPanelOpen:hi.hideWhenPanelOpen,proximityRadius:hi.proximityRadius},claude:{currentKeyId:""},webdav:{enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:"ophel",dataSources:["settings","conversations","prompts","claudeSessionKeys"]},shortcuts:lr,aistudio:{collapseNavbar:false,collapseTools:false,collapseAdvanced:false,enableSearch:true,defaultModel:"",markdownFix:ri,removeWatermark:ri},chatgpt:{markdownFix:false}};function pi(e,t){const n=e.theme?.sites;return n&&t in n?n[t]:n?._default??ai}function mi(e,t){const n=e.layout?.pageWidth;return n&&t in n?n[t]:n?._default??si}function fi(e,t){return e.modelLock?.[t]??{enabled:false,keyword:""}}function bi(e,t){const n=e.layout?.userQueryWidth;return n&&t in n?n[t]:n?._default??li}function yi(e,t){const n=e.layout?.zenMode;return n&&t in n?n[t]:n?._default??ci}function vi(e,t){const n=e.layout?.cleanMode;return n&&t in n?n[t]:n?._default??di}let xi=null;const wi="ophel:restoreFlag";let Si=null;function Ci(){if("undefined"==typeof window)return false;const e=new URL(window.location.href);if("1"!==e.searchParams.get(ii))return false;e.searchParams.delete(ii);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 ki=(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)},Ti={getItem:e=>{try{const t=GM_getValue(e);return ki(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 Ei=0;const Ai=e=>{Ei+=1;try{return e()}finally{(()=>{const e=()=>{Ei=Math.max(0,Ei-1);};"function"!=typeof queueMicrotask?Promise.resolve().then(e):queueMicrotask(e);})();}},Mi=(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},Ii=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},Li=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})):hi.collapsed.map(e=>({...e}));return o=Mi(o,{id:"floatingToolbar",enabled:true},"panel"),o=Mi(o,{id:"globalSearch",enabled:true},"floatingToolbar"),o=Mi(o,{id:"zenMode",enabled:true},"theme"),o=Mi(o,{id:"settings",enabled:true},"zenMode"),{collapsed:o,opacity:n.opacity??e.quickButtonsOpacity??hi.opacity,hideWhenPanelOpen:n.hideWhenPanelOpen??hi.hideWhenPanelOpen,toolsMenu:n.toolsMenu??e.toolsMenu,floatingToolbar:{...hi.floatingToolbar,...e.floatingToolbar||{},...n.floatingToolbar||{}},position:Ii(n.position),proximityRadius:(()=>{const e=Number(n.proximityRadius);return Number.isFinite(e)?Math.min(300,Math.max(0,e)):hi.proximityRadius})()}},Ni=(e,t,n)=>{const r={...n}; return new Set([...Object.keys(n),...Object.keys(e??{})]).forEach(o=>{r[o]=((e,t)=>{const n=po[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},qi=e=>{const t={...gi.theme.sites}; return new Set([...Object.keys(gi.theme.sites),...Object.keys(e??{})]).forEach(n=>{t[n]={...gi.theme.sites[n]??gi.theme.sites._default,...e?.[n]??{}};}),t},Ri=(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},Pi=e=>{const t=gi.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}},Di=e=>{const t=gi.export,n="zip"===e?.packaging||"markdown"===e?.packaging?e.packaging:t.packaging;return {...t,...e,packaging:n}},Bi=e=>{const{collapsedButtons:t,quickButtonsOpacity:n,toolsMenu:r,floatingToolbar:o,quickButtons:i,...a}=e;return {...gi,...a,panel:Pi(e.panel),content:{...gi.content,...e.content},theme:{...gi.theme,...e.theme,sites:qi(e.theme?.sites),customStyles:e.theme?.customStyles??gi.theme.customStyles},layout:{...gi.layout,...e.layout,pageWidth:Ni(e.layout?.pageWidth,"PAGE_WIDTH",gi.layout.pageWidth),userQueryWidth:Ni(e.layout?.userQueryWidth,"USER_QUERY_WIDTH",gi.layout.userQueryWidth),zenMode:Ri(e.layout?.zenMode,gi.layout.zenMode),cleanMode:Ri(e.layout?.cleanMode,gi.layout.cleanMode)},modelLock:Ri(e.modelLock,gi.modelLock),globalSearch:{...gi.globalSearch,...e.globalSearch},usageMonitor:{...gi.usageMonitor,...e.usageMonitor},features:{...gi.features,...e.features,outline:{...gi.features.outline,...e.features?.outline},prompts:{...gi.features.prompts,...e.features?.prompts},conversations:{...gi.features.conversations,...e.features?.conversations}},tab:{...gi.tab,...e.tab},readingHistory:{...gi.readingHistory,...e.readingHistory},export:Di(e.export),geminiEnterprise:{...gi.geminiEnterprise,...e.geminiEnterprise,policyRetry:{...gi.geminiEnterprise?.policyRetry,...e.geminiEnterprise?.policyRetry}},webdav:{...gi.webdav,...e.webdav},aistudio:{...gi.aistudio,...e.aistudio},chatgpt:{...gi.chatgpt,...e.chatgpt},shortcuts:gr(e.shortcuts)||gi.shortcuts,quickButtons:Li(e)}},$i={...Ti,setItem:async(e,t)=>{if(!(Ei>0))return Ti.setItem(e,t)}},_i=(e,t)=>t?Bi({...e,...t}):e;let Oi=null;const zi=Vo()(Yo((e,t)=>(Oi=e,{settings:gi,persistedSettings:gi,previewSettings:null,_hasHydrated:false,_syncVersion:0,setSettings:t=>e(e=>{const n=Bi({...e.persistedSettings,...t});return {persistedSettings:n,previewSettings:null,settings:n}}),setPreviewSettings:t=>Ai(()=>e(e=>({previewSettings:t,settings:_i(e.persistedSettings,t)}))),clearPreviewSettings:()=>Ai(()=>e(e=>({previewSettings:null,settings:e.persistedSettings}))),updateNestedSetting:(t,n,r)=>e(e=>{const o=Bi({...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=Bi({...e.persistedSettings,[t]:{...i,[n]:{...a,[r]:o}}});return {persistedSettings:s,previewSettings:null,settings:s}}),replaceSettings:t=>e(()=>{const e=Bi({...gi,...t});return {persistedSettings:e,previewSettings:null,settings:e}}),resetSettings:()=>e(()=>{const e=Bi(gi);return {persistedSettings:e,previewSettings:null,settings:e}}),setHasHydrated:t=>Ai(()=>e({_hasHydrated:t}))}),{name:"settings",storage:Ko(()=>$i),partialize:e=>({settings:e.persistedSettings}),merge:(e,t)=>{try{const n=e?.settings,r=Bi(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)=>{Ai(()=>{if(e){const t=Bi(e.settings);return void Oi?.({persistedSettings:t,previewSettings:null,settings:t,_hasHydrated:!0})}Oi?.({_hasHydrated:!0});});}})),Fi=()=>zi(e=>e._hasHydrated),Ui=()=>zi.getState().settings,Hi=e=>zi.subscribe(t=>e(t.settings)),Wi=Object.freeze(Object.defineProperty({__proto__:null,getSettingsState:Ui,subscribeSettings:Hi,useSettingsHydrated:Fi,useSettingsStore:zi},Symbol.toStringTag,{value:"Module"})),ji=new Map;function Gi(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-(ji.get(o)||0)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(Xi)||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 ea(e){return e?e.startsWith("\ufeff")?e:`\ufeff${e}`:"\ufeff"}function ta(e,t){const n=[];return n.push(`# ${e.title}`),n.push(""),n.push("---"),n.push(""),n.push(`## ${Ki} ${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(`## ${Yi} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}}),n.join("\n")}const na=new TextEncoder;let ra=null;function oa(e){const t=function(){if(ra)return ra;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 ra=e,e}();let n=4294967295;for(const r of e)n=t[255&(n^r)]^n>>>8;return (4294967295^n)>>>0}function ia(e,t,n){return e[t]=255&n,e[t+1]=n>>>8&255,t+2}function aa(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 sa(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 la(e){return "string"==typeof e?na.encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(await e.arrayBuffer())}function ca(e,t){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim()||t}function da(e,t){const n=e.replace(/\\/g,"/").replace(/^[a-zA-Z]:\//,"").replace(/^\/+/,"").split("/").map(e=>ca(e,"asset")).filter(e=>"."!==e&&".."!==e);return n.length>0?n.join("/"):t}function ua(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 ha(e,t,n="assets/asset"){return ua(function(e,t="assets/asset"){return da(e,t)}(e,n),t)}function ga(e){return `assets/${ca(e.name,e.id||"asset")}`}async function pa(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 ti.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: ${ma(t)}; proxy fetch failed: ${ma(n)}`)}}}function ma(e){return e instanceof Error?e.message:String(e)}async function fa(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=da(d.path,"file"),a=na.encode(e),s=await la(d.data),l=oa(s),c=new Uint8Array(30+a.length);let u=0;u=aa(c,u,67324752),u=ia(c,u,20),u=ia(c,u,2048),u=ia(c,u,0),u=ia(c,u,o),u=ia(c,u,r),u=aa(c,u,l),u=aa(c,u,s.length),u=aa(c,u,s.length),u=ia(c,u,a.length),u=ia(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=na.encode(e.path),r=new Uint8Array(46+t.length);let o=0;o=aa(r,o,33639248),o=ia(r,o,20),o=ia(r,o,20),o=ia(r,o,2048),o=ia(r,o,0),o=ia(r,o,e.dosTime),o=ia(r,o,e.dosDate),o=aa(r,o,e.crc32),o=aa(r,o,e.data.length),o=aa(r,o,e.data.length),o=ia(r,o,t.length),o=ia(r,o,0),o=ia(r,o,0),o=ia(r,o,0),o=ia(r,o,0),o=aa(r,o,0),o=aa(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=aa(l,c,101010256),c=ia(l,c,0),c=ia(l,c,0),c=ia(l,c,t.length),c=ia(l,c,t.length),c=aa(l,c,s),c=aa(l,c,a),ia(l,c,0),n.push(l),new Blob([sa(n)],{type:"application/zip"})}async function ba(e,t,n="text/plain;charset=utf-8"){try{const r=new Blob([e],{type:n});return await ya(r,t)}catch(r){return console.error("[Exporter] Download failed:",r),Gi(le("exportFailed")),false}}async function ya(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),Gi(le("exportFailed")),false}}async function va(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){return console.error("[Exporter] Failed to copy:",t),false}}function xa(e,t,n,r){return {title:e||le("exportUntitled"),id:n,url:window.location.href,exportTime:(new Date).toLocaleString(),source:t,customUserName:r?.customUserName,customModelName:r?.customModelName}}function wa(){return {assets:[],usedPaths:new Set,imagePathsBySource:new Map,filePathsBySource:new Map}}function Sa(e,t="file",n=120){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim().substring(0,n)||t}function Ca(e){return e.replace(/[[\]]/g,"\\$&")}function ka(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 Ta(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 Ea(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 Aa(e){return e.match(/\.([A-Za-z0-9]{1,10})(?:$|[?#\s])/)?.[1]?.toLowerCase()||""}function Ma(e){return Aa(Ea(e))}function Ia(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:Aa(i)||(r?r.slice(1):""),sizeLabel:o}}function La(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 Na(e,t="document"){return `${Sa(e,t,80)}.md`}function qa(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 Ra(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 Pa(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;aHa(e,t,n)).filter(Boolean)}function ja(e,t,n){return e.filter(e=>"image"===e.kind&&Boolean(e.source)).map(e=>Ha({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 Ga(e,t,n){const r=n.prefix||ka([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=Ca(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?Ua(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 Qa(e,t,n={}){const r=function(e,t,n={}){const r=n.fallbackTitle||"document",o=Na(n.title||La(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=ha(`${(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 `[${Ca(n.title||r.name)}](${r.path})`}const Va="data-ophel-managed-tab-title",Ka="data-ophel-gemini-native-tab-title",Za="data-ophel-gemini-native-tab-title-path",Ya=/\{(?:status|title|model|site)\}/g,Xa="{model}",Ja={"(":")","[":"]","{":"}","<":">","(":")","【":"】","《":"》","「":"」","『":"』"};function es(e){const t=e?.replace(/\s+/g," ").trim();return t||null}function ts(){"undefined"!=typeof document&&document.documentElement?.removeAttribute(Va);}function ns(){return "undefined"==typeof document?null:document.documentElement?.getAttribute(Va)||null}function rs(e,t={}){const n=es(e);if(!n)return null;const r=ns(),o=es(t.expectedManagedTitle),i=es(t.privacyTitle),a=es(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=is(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+=cs(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=es(t);r+=e?`(?${cs(e)})`:`(?[\\s\\S]*?)`,a+=1;}o=s.index+s[0].length;}if(r+=cs(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=ls(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?es(o):null}(n,{hasManagedSignal:r,siteName:t.siteName,titleFormat:t.titleFormat});o&&o!==n&&(n=o,r=true);return es(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 os(e,t={}){const n=rs(e,t);if(!n)return null;const r=es(t.siteName);if(r&&n===r)return null;return es(r?n.replace(new RegExp(`\\s*[-|]\\s*${ds(r)}$`,"i"),"").replace(new RegExp(`^${ds(r)}\\s*[-|]\\s*`,"i"),"").trim():n)}function is(e){let t=e;for(;t.includes(Xa);){const e=as(t);if(e===t)return t.replace(/\{model\}/g,"");t=e;}return t}function as(e){const t=Array.from(e.matchAll(Ya)),n=t.findIndex(e=>e[0]===Xa&&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 Ja[o]!==i?null:`${n[1]}${r[2]}`}(e,t);if(null!==n)return n;const r=ss(e),o=ss(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 ss(e){return /[\p{L}\p{N}]/u.test(e)}function ls(e,t){for(const n of t){const t=n.exec(e),r=es(t?.groups?.ophelTitle);if(t&&r)return {title:r,hasManagedSignal:false}}return null}function cs(e){return ds(e).replace(/\s+/g,"\\s+")}function ds(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const us={MAX_DEPTH:15,DEFAULT_TIMEOUT:5e3,POLL_INTERVAL:50,CACHE_TTL:3e5},hs={ELEMENT:1,DOCUMENT:9,FRAGMENT:11},gs=["keydown","keypress","keyup"],ps="data-ophel-interaction-layer",ms={[ps]:"true"},fs=[`[${ps}="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(", "),bs=e=>(e??("undefined"!=typeof document&&document.body?[document.body]:[])).some(e=>Boolean(e.querySelector(fs))),ys=e=>e instanceof HTMLElement&&("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||e.isContentEditable||"true"===e.getAttribute("contenteditable")||e.classList.contains("ProseMirror")),vs=(e,t={})=>{const{events:n=gs,capture:r=true}=t,o=e=>{(e=>{const t=("function"==typeof e.composedPath?e.composedPath():[]).find(e=>e instanceof HTMLElement)||null;return ys(t)?t:ys(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);});}},xs={isValidContext:e=>null!==e&&Object.values(hs).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(vT){console.error("[DOMToolkit] Cleanup error:",vT);}}),e.clear();},get size(){return e.size}}}};class ws{enabled=true;ttl;store=new WeakMap;timestamps=new WeakMap;constructor(e=us.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):xs.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 Ss{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===hs.ELEMENT&&t.forEach(t=>{try{t(e,n);}catch(vT){console.error("[DOMToolkit] Observer callback error:",vT);}});});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 Cs=new class{cache;observerManager;doc;constructor(){this.doc=document,this.cache=new ws,this.observerManager=new Ss;}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=us.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=us.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=xs.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,us.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(vT){console.error("[DOMToolkit] each callback error:",vT),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(!xs.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(vT){console.error("[DOMToolkit] watch callback error:",vT);}},r);else try{t(e,n);}catch(vT){console.error("[DOMToolkit] watch callback error:",vT);}});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(!xs.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(vT){console.error("[DOMToolkit] watchMultiple callback error:",vT);}}),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(vT){console.error("[DOMToolkit] walkShadowRoots callback error:",vT);}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>us.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();}},ks=[/^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],Ts=[{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 Es(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 As(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&&ks.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 Ts){const e=i.match(s);if(e)return n[r]=`${a}${l}${i.slice(e[0].length)}`,n.join("\n")}return t}function Is(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 Ls(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 Ns(e){const t=Cs.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=Ls(o);if(!e||n.has(e))continue;const t=Is(e);t&&((Es(e)||As(t))&&(n.add(e),r.push({element:e,source:t})));}return r}class qs{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"}getNewTabUrl(){return window.location.origin}supportsTabRename(){return true}getSessionName(){return this.getDocumentConversationTitle()}getDocumentConversationTitle(e=this.getName()){return os(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!==qs.prototype.toggleTheme}getNativeThemeCss(){return null}getWidthSelectors(){return []}getUserQueryWidthSelectors(){return []}getZenModeConfig(){return null}getCleanModeConfig(){return null}getMarkdownFixerConfig(){return null}getAssistantMermaidSupportMode(){return "native"}getAssistantMermaidBlocks(e){return Ns(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()===yo){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}getQuickQuoteSupportMode(){return "enabled"}getNativeQuotePopoverSelectors(){return []}getQuickQuoteChipHost(e){return Array.from(e.querySelectorAll(".gh-user-query-markdown")).find(e=>{const t=window.getComputedStyle(e);return "none"!==t.display&&"hidden"!==t.visibility})||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)}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}usesPeriodicOutlineRefreshFallback(){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.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}findActiveOutlineItemId(){return null}findUserQueryElement(e,t){const n=this.getUserQuerySelector();if(!n)return null;const r=Cs.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);}getExportConfig(){return null}async extractExportMessages(e){return null}async extractExportBundle(e){return null}async createExportBundleFromMessages(e){const t=wa(),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)}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 Cs.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=Cs.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(()=>Vi);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 Cs.query(e,{shadow:true})}findAllElementsBySelector(e){return Cs.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=Cs.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=Cs.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&&Cs.query(e.assistantResponseSelector,{parent:this.getPrimaryCodeSearchRoot(),all:true,shadow:true,filter:e=>this.shouldIncludeAssistantResponseElement(e)})||[]}getPrimaryCodeSearchRoot(){const e=this.getResponseContainerSelector();if(e){const t=Cs.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)}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 Rs="delete_ui_failed",Ps="delete_batch_aborted_after_ui_failure",Ds="delete_api_disabled_unstable",Bs="delete_api_auth_missing",$s="delete_api_key_missing",_s="delete_api_request_failed",Os="delete_api_not_found_but_visible",zs=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","löschen","excluir","hapus","удалить"],Fs=["cancel","取消","キャンセル","취소","annuler","abbrechen","annulla","batal","cancelar","отмена"],Us="/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService",Hs="ms-chat-turn",Ws=".chat-turn-container.model, .model-prompt-container",js=".chat-turn-container.model",Gs="ms-thought-chunk",Qs="data-gh-aistudio-export-root",Vs="data-gh-aistudio-export-turn",Ks="data-gh-aistudio-export-role",Zs="user",Ys="assistant",Xs=`[${Qs}="1"] [${Vs}="1"]`,Js=`[${Qs}="1"] [${Ks}="${Zs}"]`,el=`[${Qs}="1"] [${Ks}="${Ys}"]`,tl="ms-library-table",nl=['ms-library-table table a[href*="/prompts/"]:not([href*="new_chat"])','ms-library-table .prompt-card a[href*="/prompts/"]:not([href*="new_chat"])'].join(", "),rl=["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 ol=new Set(["chatglm.cn"]),il="share_conversation_id",al="SKIN_MODE",sl={light:"1",dark:"2",system:"3"},ll=[".userInfoBar-header .me-icon",".userInfoBar-header .me",".userInfoBar-header img.avatar"],cl=".selecttheme-list",dl=".conversation-list",ul=".conversation.question",hl=".question-txt",gl=".answer-content-wrap",pl=".answer-content-wrap .markdown-body",ml=[".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(", "),fl=[".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(", "),bl=["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"],yl=["#search-input-box textarea",".main-chat-search #search-input-box textarea",".main-chat-search textarea"],vl=".enter-icon-container";function xl(e){let t=5381;for(let n=0;n>>0;return `${e.length}:${t.toString(36)}`}const wl="ChatGPT",Sl=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удалить","excluir"],Cl="delete_ui_failed",kl="delete_batch_aborted_after_ui_failure",Tl="delete_api_token_missing",El="delete_api_request_failed",Al="delete_api_not_found_but_visible",Ml=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"]),Il=['button[class*="__composer-pill"][aria-haspopup="menu"]'],Ll='[data-radix-popper-content-wrapper] [role="menu"][data-radix-menu-content]',Nl=`${Ll} [data-testid^="model-switcher-"]`,ql='a[data-sidebar-item="true"][href^="/c/"]',Rl=/^\/c\/([a-z0-9-]+)(?:[/?#]|$)/i,Pl="data-gh-chatgpt-export-root",Dl="data-gh-chatgpt-export-turn",Bl="data-gh-chatgpt-export-role",$l="user",_l="assistant",Ol=`[${Pl}="1"] [${Dl}="1"]`,zl=`[${Pl}="1"] [${Bl}="${$l}"]`,Fl=`[${Pl}="1"] [${Bl}="${_l}"]`,Ul=/^chatgpt-native-user-query::(\d+)::/,Hl=/^Prompt\s+\d+$/i,Wl=".markdown.markdown-new-styling",jl=".self-end.bg-token-bg-tertiary .whitespace-pre-wrap";function Gl(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 Ql(e,t={}){const{maxLevel:n=6,showWordCount:r=false,idPrefix:o,maxTextLength:i,shouldSkipHeading:a,calculateWordCount:s}=t,l=Gl(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 Kl(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 Zl(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 Yl="https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/fonts",Xl=e=>e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Jl=()=>{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/")?`${Yl}/${r.slice(6)}`:`${Yl}/${r}`}${t})`}))(e):""}catch(vT){return console.warn("[Ophel] Failed to load KaTeX CSS resource:",vT),""}},ec=(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="${Xl(n)}">${Xl(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="${Xl(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="${Xl(n)}">${Xl(e)}`}};const tc=(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),nc=()=>"undefined"==typeof window?"":window.__OPHEL_MARKDOWN_PREVIEW_STYLES__||"",rc="delete_ui_failed",oc="delete_batch_aborted_after_ui_failure",ic="delete_api_org_missing",ac="delete_api_request_failed",sc="delete_api_not_found_but_visible",lc=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","elimina","löschen","excluir","hapus","हट","मिट"],cc=["cancel","取消","annuler","abbrechen","annulla","キャンセル","취소","batal","cancelar"],dc=/^[a-f0-9-]{36}$/i,uc=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],hc=[/((^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$))/,/\\\([^\n]+?\\\)/],gc="document",pc="#wiggle-file-content",mc=".standard-markdown, .progressive-markdown",fc=".artifact-block-cell",bc='[data-testid="file-thumbnail"]',yc="button[aria-expanded]",vc='span[role="status"][aria-live="polite"]';function xc(){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 wc(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))||hc.some(e=>e.test(n))}const Sc=/\/a\/chat\/s\/([a-z0-9-]+)/i,Cc=/\/share\/([a-z0-9-]+)/i,kc="__appKit_@deepseek/chat_themePreference",Tc='a[href*="/a/chat/s/"]',Ec=".ds-message",Ac=`${Ec}:has(.ds-markdown)`,Mc=".ds-message:not(:has(.ds-markdown))",Ic=".ds-think-content",Lc=[`${Mc} > .gh-inline-bookmark + div`,`${Mc} > div:not(.gh-user-query-raw):not(.gh-user-query-markdown):not(.ds-focus-ring)`,`${Mc} > div.gh-user-query-markdown`].join(", "),Nc="https://chat.deepseek.com/",qc="gh.deepseek.delete.refresh",Rc="data-gh-deepseek-export-root",Pc="data-gh-deepseek-export-role",Dc="user",Bc="assistant",$c=`[${Rc}="1"] [${Pc}="${Dc}"]`,_c=`[${Rc}="1"] [${Pc}="${Bc}"]`,Oc="M2 4.88",zc="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",Fc="delete_api_missing_auth_token",Uc="delete_api_request_failed",Hc="delete_api_invalid_response",Wc="delete_api_business_failed";const jc=/^(?:(?:\/code)?\/chat|\/thread)\/([^/?#]+)/,Gc="#flow_chat_sidebar",Qc=`${Gc} [data-history-container="true"]`,Vc=`${Gc} a[id^="conversation_"][href*="/chat/"]`,Kc='[class*="overallTitle-"], [class*="title-"]',Zc=`${Gc} > div:nth-child(2)`,Yc='[class*="v_list_scroller"]',Xc=".v_list_row",Jc='[data-target-id="message-box-target-id"]',ed="[data-message-id].justify-end",td=".whitespace-pre-wrap.wrap-anywhere:not(.gh-user-query-markdown)",nd=`${ed} ${td}`,rd="[data-message-id]:not(.justify-end)",od=[".flow-markdown-body",".md-box-root"],id=od.join(", "),ad=od.map(e=>`${rd} ${e}`).join(", "),sd='[data-plugin-identifier="block_type:2074"]',ld='[class*="image-wrapper"], [class*="image-box-grid-item"], [class*="image-box-grid"]',cd=["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"],dd="delete_ui_failed",ud="delete_batch_aborted_after_ui_failure";const hd=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createPortal)throw new Error("[Ophel] ReactDOM CDN runtime is missing");return e}(),gd=hd.createPortal;hd.flushSync,hd.unstable_batchedUpdates,hd.version;const pd="ophel-global-tooltip-styles",md=8,fd=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 bd(e){if(!e||"undefined"==typeof document)return null;const t=e.getRootNode?.();return t instanceof ShadowRoot?t:document.body}function yd(e){if("undefined"==typeof document||!e||e instanceof ShadowRoot)return;if(document.getElementById(pd))return;const t=document.createElement("style");t.id=pd,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 vd(e,t,n={}){const{preferredPlacement:r="bottom",gap:o=md,viewportPadding:i=fd}=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 xd=new class{tooltipEl=null;activeTrigger=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=bd(e);if(!o)return;yd(o),this.activeTrigger&&this.activeTrigger!==e&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=e,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}=vd(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 wd(e,t){let n=null;const r=()=>{n&&(clearTimeout(n),n=null);},o=()=>{r(),xd.hide(e);},i=()=>{var o;(r(),"function"==typeof(o=t.disabled)?o():Boolean(o))||(n=setTimeout(()=>{if(!e.isConnected)return;const n=t.getContent();xd.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 Sd=({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(vd(e,t,{preferredPlacement:"bottom"}));},[]);return L(()=>{if(y.current){const e=bd(y.current);b(e),yd(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]),Re("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&&gd( qe("div",{ref:v,className:"ophel-tooltip",style:{position:"fixed",top:d.top,left:d.left,maxWidth:n,opacity:h?0:1},children:e}),f)]})},Cd="http://www.w3.org/2000/svg";function kd(e,t={}){const n=document.createElementNS(Cd,e);for(const[r,o]of Object.entries(t))n.setAttribute(r,o);return n}function Td(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=kd("svg",{xmlns:Cd,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=kd("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),a=kd("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 Ed(e,t={}){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=kd("svg",{xmlns:Cd,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=kd("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(Td(t));},1500);}function Ad(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(Td(t));}});}const Md="CHECK_PERMISSION",Id="CHECK_PERMISSIONS",Ld="REQUEST_PERMISSIONS",Nd="CLEAR_ALL_DATA",qd="RESTORE_DATA";function Rd(e){return chrome.runtime.sendMessage(e)}const Pd="GH_MONITOR_INIT",Dd="GH_MONITOR_START",Bd="GH_MONITOR_COMPLETE",$d="OPHEL_GEMINI_MYSTUFF_SYNC_REQUEST",_d="OPHEL_GEMINI_MYSTUFF_CACHE_SYNC",Od="OPHEL_EXTENSION_UPDATE_AVAILABLE",zd="OPHEL_PAGE_URL_CHANGE";function Fd(e,t){return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(t).flexDirection}function Ud(e,t){return t?Math.min(0,e.clientHeight-e.scrollHeight):0}function Hd(e,t){return t?0:e.scrollHeight}function Wd(){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 jd(e,t){{const n=Wd();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 Gd(e){const t=await jd("getScrollInfo");if(t.success){const e=t.scrollTop||0,n=t.scrollHeight||0;return await jd("scrollToTop"),{container:Yd(),previousScrollTop:e,scrollHeight:n}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=n.scrollHeight,o=Fd(e,n);return n.scrollTo({top:Ud(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 Qd(e){const t=await jd("getScrollInfo");if(t.success){const e=t.scrollTop||0;return await jd("scrollToBottom"),{container:Yd(),previousScrollTop:e}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=Fd(e,n);return n.scrollTo({top:Hd(n,r),behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop}}async function Vd(e,t){const n=await jd("scrollTo",t);if(n.success)return Kd(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}),Kd(r.scrollTop),{success:true,currentScrollTop:r.scrollTop}):(document.documentElement.scrollTo({top:t,behavior:"instant",__bypassLock:true}),Kd(document.documentElement.scrollTop),{success:true,currentScrollTop:document.documentElement.scrollTop})}function Kd(e){ void 0!==document.documentElement.dataset.ophelPositionLock&&(document.documentElement.dataset.ophelPositionLock=String(e));}async function Zd(e){const t=await jd("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 Yd(){const e=document.createElement("div");return Object.defineProperty(e,"__isFlutterProxy",{value:true}),e}function Xd(e){return true===e.__isFlutterProxy}const Jd=1200,eu=2,tu=10,nu=50;function ru(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 ou(e){const{adapter:t,targetHeight:n,loadAll:r=false,onProgress:o,signal:i,allowShortCircuit:a=false}=e;let{previousScrollTop:s,container:l}=await Gd(t);if(Xd(l)){return {success:true,finalHeight:(await Zd(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>=nu)return {success:true,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(l.scrollTop=ru(t,l),l.dispatchEvent(new WheelEvent("wheel",{deltaY:-100,bubbles:true})),await su(Jd),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=ru(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?eu:tu))return {success:true,finalHeight:e,heightAdded:e-c,previousScrollTop:s,isFlutterMode:false,silent:false}}}}async function iu(e){const{adapter:t,getSignature:n,waitMs:r=800,maxRounds:o=60,stableRounds:i=4,wheelDeltaY:a=-800}=e;let s=t?.getScrollContainer()||null;if(!s)return {success:false,rounds:0,stableRounds:0,finalHeight:0,finalSignature:""};if(s.scrollHeight<=s.clientHeight+5)return {success:true,rounds:0,stableRounds:0,finalHeight:s.scrollHeight,finalSignature:n(s)};let l="",c=0,d="";for(let u=0;u=i)return {success:true,rounds:u+1,stableRounds:c,finalHeight:s.scrollHeight,finalSignature:d}}return {success:false,rounds:o,stableRounds:c,finalHeight:s.scrollHeight,finalSignature:d}}function au(e,t){e===document.documentElement||e===document.body?window.scrollTo({top:0,behavior:"auto"}):(e.scrollTop=0,e.scrollTo?.({top:0,behavior:"auto",__bypassLock:true})),e.dispatchEvent(new Event("scroll",{bubbles:true,composed:true})),e.dispatchEvent(new WheelEvent("wheel",{bubbles:true,cancelable:true,deltaY:t})),window.dispatchEvent(new Event("scroll"));}function su(e){return new Promise(t=>setTimeout(t,e))}let lu=null,cu=null,du=false;function uu(){if("undefined"==typeof window)return null;const e=window.trustedTypes;return e?.createPolicy?e:null}function hu(e){return `ophel-userscript-${e}-${Math.random().toString(36).slice(2,8)}`}function gu(e){if(lu||function(){if(lu)return true;const e=uu();if(!e)return false;try{return lu=e.createPolicy(hu("html"),{createHTML:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types policy:",t),false}}(),lu)try{return lu.createHTML(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe HTML:",t);}return e}function pu(e,t){try{const n=gu(t);return e.innerHTML=n,!0}catch(n){return console.warn("[TrustedTypes] Failed to set innerHTML:",n),false}}function mu(e){if(cu||function(){if(cu)return true;const e=uu();if(!e)return false;try{return cu=e.createPolicy(hu("script-url"),{createScriptURL:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types script URL policy:",t),false}}(),cu)try{return cu.createScriptURL(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe script URL:",t);}return e}function fu(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(mu(t)),!0}catch(o){n=o;}if(function(){if(du)return true;const e=uu();if(!e)return false;try{return e.createPolicy("default",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}),du=!0,!0}catch(o){const t=o instanceof Error?o.message:String(o);return /default/i.test(t)&&/already exists/i.test(t)?(du=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 bu(e){return e instanceof Error?e.message||"Unknown watermark processing error":"string"==typeof e&&e.trim()?e.trim():"Unknown watermark processing error"}function yu(e){return "undefined"!=typeof ImageData&&e instanceof ImageData?e:new ImageData(new Uint8ClampedArray(e.data),e.width,e.height)}function vu(e){return "googleusercontent.com"===e||e.endsWith(".googleusercontent.com")}function xu(e){return /=(?:d|d-I)$/i.test(e||"")}function wu(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 Su(e){if(!e)return null;try{const t=new URL(e);return vu(t.hostname)?wu(t.pathname):null}catch{return null}}function Cu(e){return null!==Su(e)}function ku(e){if(!e)return false;try{const t=new URL(e);if(!vu(t.hostname))return !1;const n=wu(t.pathname);return !(!n||"gg"!==n.family)&&(n.isPreview?!xu(t.pathname):!xu(t.pathname)&&(n.isDownload&&/-rj$/i.test(t.pathname)))}catch{return false}}function Tu(e){if(!Cu(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(xu(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 Eu="ophel-watermark-loading-style",Au="watermark-not-detected",Mu=["[data-image-attachment-index]","single-image.generated-image","generated-image",".generated-image-container",".image-container.replace-fife-images-at-export"].join(", ");class Iu{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 Iu.activeInstance}start(){this.enabled||(this.enabled=true,Iu.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(),Iu.activeInstance===this&&(Iu.activeInstance=null),this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}isGeminiStandardSite(){return "gemini.google.com"===window.location.hostname}shouldInterceptGeminiImageUrl(e){return Cu(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(Eu))return;if(!document.head)return;const e=document.createElement("style");e.id=Eu,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(Eu)?.remove();}findProcessingIndicatorHost(e){const t=e.closest(Mu);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(vT){this.postMainWorldProcessResponse({requestId:e,success:false,error:vT instanceof Error?vT.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(vT){return vT instanceof Error&&vT.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(vT){const r=vT instanceof Error?vT.message:"";if("copy"===t&&"fullsize-source-unavailable"===r)return this.getProcessedDataUrl(e,{bypassCache:true,requireNonPreviewSource:false,scene:t});throw vT}}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=Tu(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=Su(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&&ku(o))throw new Error("fullsize-source-unavailable");return e}catch(vT){r=vT;}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:yu(r.imageData),decision:i}:{status:"skipped",reason:o.skipReason?"invalid-candidate":"not-banana",decision:i}}catch(vT){return {status:"failed",error:bu(vT)}}}(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(Au);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(vT){throw vT instanceof Error&&vT.message===Au&&this.rememberSkippedSource(r),vT}}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(vT){throw vT instanceof Error&&vT.message===Au&&this.rememberSkippedSource(r),vT}})();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(Au)}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(vT){if((vT instanceof Error?vT.message:"")===Au)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)?Tu(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 Lu="delete_ui_failed",Nu="delete_ui_exception",qu="delete_batch_aborted_after_ui_failure",Ru=["delete","remove","删除","删掉","supprimer","eliminar","löschen","삭제","削除","移除","excluir","hapus","удал"],Pu=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"],Du="data-ophel-export-image-src",Bu=/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/i,$u=/(google|account|账号|帳號|conta|compte|cuenta|konto|アカウント|계정|учет)/i,_u=/(unable|cannot|can't|can not|无法|無法|不可).*(view|preview|download|共享|分享|shared|查看|预览|預覽|下载|下載)|shared.*(file|download|preview)|共享对话中的文件|共享對話中的文件/i,Ou=[".attachment-container.generated-images","response-element","generated-image","single-image.generated-image",".image-container.replace-fife-images-at-export","[data-image-attachment-index]"].join(", "),zu=["user-query img[data-test-id='uploaded-img']","user-query .preview-image"].join(", "),Fu='[data-test-id="uploaded-file"]',Uu="share-landing-page .share-turn-viewer",Hu="message-content .markdown",Wu='share-landing-page immersive-share-landing-page structured-content-container[data-test-id="deep-research-block"]',ju='share-landing-page structured-content-container[data-test-id="immersive-artifact-content"]',Gu=Hu,Qu="deep-research-confirmation-widget",Vu="immersive-panel deep-research-immersive-panel",Ku=[`${Vu} #extended-response-markdown-content`,`${Vu} message-content .markdown`].join(", "),Zu=['mat-icon[data-mat-icon-name="travel_explore"]','mat-icon[fonticon="travel_explore"]'].join(", "),Yu=['mat-icon[fonticon="code_blocks"]','mat-icon[data-mat-icon-name="code_blocks"]'].join(", "),Xu=['mat-icon[fonticon="article"]','mat-icon[data-mat-icon-name="article"]'].join(", "),Ju="immersive-panel extended-response-panel:has(canvas-create-button)",eh=["immersive-panel code-immersive-panel",Ju].join(", "),th='xap-code-editor[data-test-id="code-editor"]',nh=["#extended-response-markdown-content .ProseMirror",'immersive-editor[data-test-id="immersive-editor"] .ProseMirror',"immersive-editor .ProseMirror","#extended-response-markdown-content"].join(", "),rh="gh-gemini-panel-markdown-actions",oh="gh-gemini-panel-markdown-action",ih="data-ophel-deep-research-panel-actions",ah="data-ophel-canvas-panel-actions",sh="document",lh=[".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(", "),ch=["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(", "),dh="ophel-gemini-mystuff-active",uh="ophel-gemini-mystuff-style",hh="ophel-mystuff-open-btn",gh="data-ophel-mystuff-open",ph="data-ophel-mystuff-open-suppress",mh=/^https:\/\/lh\d+\.googleusercontent\.com\//i,fh='expandable-section[data-test-id="chats-expandable-section"]',bh='expandable-section[storagekey="chats"]',yh='gem-nav-list-item[data-test-id="conversation"]',vh=["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 xh{constructor(e){this.options=e;}started=false;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(),Cs.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!==_d||t===_d&&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(`[${gh}="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(dh,t),t&&(this.enhanceExistingMediaCards(),this.requestSync(e,this.getKindsForCurrentPath()).catch(()=>{}));}injectStyles(){if(document.getElementById(uh))return;const e=document.createElement("style");e.id=uh,e.textContent=`\n .${dh} library-item-card .library-item-card,\n .${dh} .library-item-card-container {\n position: relative;\n }\n\n .${dh} .${hh} {\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 .${dh} library-item-card:hover .${hh},\n .${dh} library-item-card:focus-within .${hh},\n .${dh} .library-item-card:hover .${hh},\n .${dh} .library-item-card:focus-within .${hh},\n .${dh} .library-item-card-container:hover .${hh},\n .${dh} .library-item-card-container:focus-within .${hh} {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0);\n }\n\n .${dh} .${hh}:hover {\n background: rgba(15, 23, 42, 0.60);\n color: #ffffff;\n }\n\n .${dh} .${hh}[${ph}="1"] {\n opacity: 0 !important;\n pointer-events: none !important;\n transform: translateY(-2px) !important;\n }\n\n .${dh} .${hh} 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 .${hh},\n html[dark-theme] .${hh},\n html.dark .${hh} {\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 .${hh}:hover,\n html[dark-theme] .${hh}:hover,\n html.dark .${hh}: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(`[${gh}="1"]`))return;const r=document.createElement("button");r.type="button",r.className=`${hh} ophel-tooltip-trigger`,r.setAttribute(gh,"1"),r.setAttribute("aria-label",this.getOpenInNewTabLabel()),r.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=kd("svg",{xmlns:Cd,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=kd("path",{d:"M14 5h5v5"}),a=kd("path",{d:"M10 14 19 5"}),s=kd("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,wd(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:$d,payload:r},"*"),o}preparePendingTab(){return "userscript"!==ti.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 Gi(le("geminiMystuffLocateFailed"),2500);const o=this.buildRecordUrl(r);!n||n.closed?ti.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(vT){console.warn("[GeminiAdapter][MyStuff] sync failed before open",{kind:t,error:vT});}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 mh.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(ii,"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(ph,"1");const t=()=>{e.removeAttribute(ph),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 wh="delete_ui_failed",Sh="delete_batch_aborted_after_ui_failure",Ch=["delete","remove","删除","删掉","移除","supprimer","eliminar","löschen","삭제","削除","hapus","удал"],kh=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"];const Th=["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,"")),Eh="delete_ui_failed",Ah="delete_batch_aborted_after_ui_failure",Mh="delete_api_request_failed",Ih="delete_api_not_found_but_visible",Lh=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удал","excluir"],Nh=["confirm","ok","yes","确定","確認","确认","確定","check"];const qh="ima.qq.com",Rh=/^\/chat\/([a-z0-9]+)(?:\/|$)/i,Ph="#scrollContainer",Dh=`${Ph} [class*="scrollWrap"]`,Bh='div[class*="userBubbleContainer"]',$h='div[class*="userBubbleWrap"]',_h=[Bh,$h].join(", "),Oh=`${Bh} [class*="userBubble"]`,zh='[class*="chatMainBubble"]',Fh=[Oh,`${$h} ${zh}`].join(", "),Uh=[`${Oh} [class*="content"]`,zh].join(", "),Hh='div[class*="aiContainer"]',Wh=`${Hh} [class*="bubble"]`,jh='[class*="markdown"]',Gh=`${Wh} ${jh}`,Qh='[class*="thinking"]',Vh='.system-copy-exclude, [x-noteelement="excluded"], [x-copyelement="copy-exclude"]',Kh=[".gh-root",".gh-user-query-markdown",".gh-inline-bookmark",Vh,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Zh=':is([class*="attachmentContainer"], [class*="attachmentWrap"])',Yh=[`${Zh} img`,'[class*="imgWrap"] img'].join(", "),Xh=[`${Zh} [class*="itemWrap"]`,`${Zh} [class*="file"]`,`${Zh} [class*="doc"]`,`${Zh} a[href]`,`${Zh} [data-file-id]`,`${Zh} [data-doc-id]`,`${Zh} [data-resource-id]`].join(", "),Jh=[`${Wh} [class*="imagesWrapper"] img`,`${Wh} [id^="image-toolkit-"] img`,`${Wh} [class*="bigImg"] img`,`${Wh} ${jh} img`].join(", "),eg=['[class*="imagesWrapper"]','[id^="image-toolkit-"]',".t-image__wrapper","picture","img"].join(", "),tg=["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"],ng='[class*="sendBtnWrap"]',rg=['div[class*="stopButton"] > div','[class*="stopButton"][role="button"]','button[class*="stopButton"]','[class*="stopButton"]'].join(", "),og='[class*="currentChoiceWrap"], [class*="modelSelectionWrap"], [class*="modelSelectionText"]',ig='[class*="modelSelectionText"]';const ag=/^\/chat\/([a-z0-9-]+)(?:\/|$)/i,sg=/^\/(?:share|kimiplus)\/([a-z0-9-]+)(?:\/|$)/i,lg=["/docs/","/website/","/table/"],cg="__tea_cache_tokens_",dg="kimi-auth",ug=[dg,"kimi_auth","access_token","accessToken","token","auth","authorization"],hg=["value","token","access_token","accessToken","auth","authorization","id_token","idToken","jwt"],gg=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,pg=/(token|auth|jwt|tea)/i,mg="a.chat-info-item",fg=`${mg}, a.history-link`,bg=".history-part",yg="span.chat-name",vg=".history-chat .title-wrapper .title",xg=".chat-content-list",wg=`${xg}, .share-content-list`,Sg=[xg,`${xg}${xg}`,`${xg}${xg}${xg}`,`.chat-detail-content ${xg}`,`.chat-detail-content ${xg}${xg}`].join(", "),Cg=".chat-content-item",kg=".chat-content-item-user",Tg=".chat-content-item-assistant",Eg=".segment.segment-user",Ag=".segment.segment-assistant",Mg=[".segment-user .segment-content",`${kg} .segment-content`,".segment-container:has(.user-content) > .segment-content"].join(", "),Ig=[".segment-user .segment-content-box",`${kg} .segment-content-box`,".segment-content-box:has(> .user-content)"].join(", "),Lg=[".segment-user .user-content",`${kg} .user-content`,".segment-content-box > .user-content"].join(", "),Ng=[".segment-assistant .segment-content-box > .markdown-container > .markdown",`${Tg} .segment-content-box > .markdown-container > .markdown`].join(", "),qg=".toolcall-container, .container-block",Rg="button, [role='button'], svg, canvas, [aria-hidden='true'], .segment-avatar, .okc-cards-container",Pg="CUSTOM_THEME",Dg="delete_api_missing_auth_token",Bg="delete_api_request_failed",$g="delete_api_invalid_response",_g="delete_api_business_failed";const Og=/\/chat\/([a-f0-9]+)/i,zg=/\/group\/([a-f0-9]+)/i,Fg="tongyi-theme-preference",Ug="model-select-expanded",Hg='[class*="questionItem"], .chat-question-wrap, [class*="message-select-wrapper-question"]',Wg="[data-chat-question-wrap]",jg='[class*="answerItem"], [data-chat-answers-wrap], .chat-answers-card-wrap',Gg='[class*="bubble"]',Qg=[`${Wg} .message-card-wrap.question`,`${Wg} .question-text-card`].join(", "),Vg=".message-card-wrap.question",Kg=`${Vg}[data-mt*="image"]`,Zg=[`${Vg}[data-mt*="doc"]`,`${Vg}[data-mt*="file"]`,`${Vg}[data-mt*="office"]`,`${Vg}:has([class*="office-card"])`].join(", "),Yg=[".answer-common-card .qk-markdown",".markdown-pc-special-class .qk-markdown","#qk-markdown-react",".answer-common-card"].join(", "),Xg=['[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(", "),Jg=['[data-card-type="ai_generate_image_list"]',".card_card_ai_generate_image",'[data-tpl*="card_ai_generate_image"]'].join(", "),ep=[".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(", "),tp=["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"],np='[class*="chatInput"]',rp=".message-list-scroll-container, #message-list-scroller",op="#qwen-message-list-area",ip=['[class*="page-content-"]','[class*="pageContent"]','[class*="scrollOutWrapper"]'].join(", "),ap="aside#new-nav-tab-wrapper",sp='.qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], [class*="thinkingHeader"], [class*="thinkingTitle"]',lp='[class*="stop-"], [class*="stopBtn"], div[class*="stop"]',cp='[role="dialog"], [data-radix-popper-content-wrapper]',dp=['[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 up=/\/c\/([a-f0-9-]+)/i,hp="theme",gp="#sidebar",pp=".session-list-wrapper",mp=".chat-item-drag",fp=".chat-item-drag-link-content-tip-text",bp="#chat-messages-scroll-container",yp="#chat-message-container",vp=".qwen-chat-message-user, .chat-user-message-wrapper",xp=".qwen-chat-message-assistant",wp=".user-message-content",Sp=".response-message-content",Cp="button.send-button",kp=["button.stop-button",'button[class*="stop-button"]',".stop-button"],Tp="pre.qwen-markdown-code",Ep=".artifacts-body-header-switch",Ap=".artifacts-body-header-switch-active, .artifacts-body-header-switch-unactive, .header-switch-status-small",Mp="data-ophel-qwenai-mermaid-export-switched",Ip=".qwen-chat-thinking-tool-status-card-wraper, .qwen-chat-thinking-status-card",Lp=".qwen-chat-thinking-status-card-title-text",Np=[".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(", "),qp=".response-message-footer, .copy-response-button, .message-hoc-container",Rp=[".gh-root",".gh-user-query-markdown",Ip,qp,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Pp=[".user-image-item",".user-image-list .qwen-image","[class*='file-message-image'] .qwen-image",".qwen-markdown-image:has(img)"].join(", "),Dp=[".chat-response-media-render img",".qwen-chat-response-control-card img",".response-message-content img",".qwen-markdown-image img","img.qwen-image"].join(", "),Bp=[".chat-response-media-render",".qwen-chat-response-control-card",".qwen-markdown-image","picture","img"].join(", "),$p=["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"],_p='#qwen-chat-header-left .ant-dropdown-trigger:has([class*="model-selector-text"])',Op='#qwen-chat-header-left [class*="model-selector-text"]',zp='[class*="model-selector-popup"]',Fp=[`${zp} [class*="model-list"] > [class*="model-item___"]`,`${zp} [class*="model-list"] > [class*="model-item-selected___"]`].join(", "),Up=[`${zp} .ant-dropdown-trigger:has([class*="view-more-text"])`,`${zp} .ant-dropdown-trigger:has([class*="view-more-icon"])`].join(", "),Hp=[Fp,Up,'.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(", "),Wp=".qwen-markdown-latex";const jp="yuanbao.tencent.com",Gp=/^\/chat\/([^/?#]+)(?:\/([^/?#]+))?/,Qp="yb_web_theme_mode",Vp="#yuanbao-send-btn, a.style__send-btn___RwTm5",Kp="a.style__send-btn___RwTm5",Zp=".yb-recent-conv-list__item",Yp=".yb-recent-conv-list__item.active",Xp=".yb-recent-conv-list__item-name[data-item-name], .yb-recent-conv-list__item-name, [data-item-id][data-item-name]",Jp="#chat-content .agent-chat__list__content, .agent-chat__list__content",em=".agent-chat__list__item--human",tm=".agent-chat__list__item--ai",nm=".agent-chat__list__item--ai .hyc-common-markdown-style, .agent-chat__list__item--ai .hyc-content-md-done",rm=".agent-chat__toolbar, .agent-chat__toolbar_new, .agent-chat__question-toolbar, .hyc-common-markdown__code__hd__r",om=".hyc-card-box-process-list, .hyc-common-markdown__replace-appCard",im=[".hyc-component-multi-modal__image img",".agent-chat__bubble--human .hyc-content-img img"].join(", "),am=[".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(", "),sm=['[data-card-type="image"] img','[data-box-type="loadingImage"] img',".hyc-media-box--loadingImage img",".loading-image-box img"].join(", "),lm=['[data-card-type="image"]','[data-box-type="loadingImage"]',".hyc-media-box--loadingImage",".loading-image-box"].join(", "),cm=["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"],dm=".ybc-model-select-button .t-button__text",um=[".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(", "),hm=[".hyc-component-reasoner__think",".hyc-component-deepsearch-cot__think",".hyc-common-markdown-style-cot"].join(", "),gm=[".hyc-component-reasoner__text .hyc-common-markdown-style",".hyc-component-reasoner__text .hyc-content-md-done",".hyc-component-reasoner__text"],pm=[".t-dropdown__menu",".t-dropdown__submenu",".t-dropdown",".t-popup",".t-popup__content",".t-popup__content__inner",'[role="menu"]','[role="listbox"]'].join(", "),mm=[".t-dropdown__item",".yb-dropdown__item",'[role="menuitem"]','[role="option"]'].join(", "),fm=['[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(", "),bm='.t-dialog, [role="dialog"]',ym="--hunyuan-chat-list-max-width",vm=/删除|delete/i,xm=/删除|确认|确定|delete|confirm/i,wm=/取消|cancel/i,Sm="ui_failed",Cm="ui_exception",km="batch_aborted_after_ui_failure";const Tm="chat.z.ai",Em=/\/(?:c|s)\/([a-z0-9-]+)(?:\/|$)/i,Am=/\/s\/([a-z0-9-]+)(?:\/|$)/i,Mm=["#chat-input","textarea#chat-input"],Im="#send-message-button",Lm=["#sidebar-new-chat-button","#new-chat-button"],Nm=["button.modelSelectorButton",'button[id^="model-selector-"][id$="-button"]',"#model-selector-glm-5-button","button[data-melt-dropdown-menu-trigger][data-menu-trigger].modelSelectorButton"],qm="#chat-container",Rm=[`${qm} .flex.overflow-y-scroll.flex-col.w-full.h-full`,`${qm} .scrollbar-none.flex.flex-col`,`${qm} [data-pane-id] .overflow-y-scroll`,`${qm} [data-pane-id] .scrollbar-none`].join(", "),Pm=['[id^="message-"].user-message',".user-message .chat-user.markdown-prose",".user-message .chat-user",`${qm} .chat-user.markdown-prose`,`${qm} .chat-user`,`${qm} [data-message-author-role="user"]`,`${qm} [data-role="user"]`,`${qm} .message-user`,`${qm} .user-message`,`${qm} .chat-message-user`,`${qm} .message.user`].join(", "),Dm=[`${qm} .markdown-prose:not(.chat-user)`,`${qm} [data-message-author-role="assistant"]`,`${qm} [data-role="assistant"]`,`${qm} .message-assistant`,`${qm} .assistant-message`,`${qm} .chat-message-assistant`,`${qm} .markdown`,`${qm} .markdown-body`,`${qm} .prose`,`${qm} article`,`${qm} [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(", "),Bm=['[id^="message-"]:not(.user-message)',Dm].join(", "),$m="data-gh-export-role",_m=`[${$m}="user"]`,Om=`[${$m}="assistant"]`,zm=".thinking-chain-container, .thinking-block",Fm=[".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"],Um=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Hm=["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"],Wm=['div[aria-label="停止"] button',"button:has(span.rounded-xs):has(span.size-3)","button:has(span.rounded-xs):has(span.block)"].join(", "),jm="#sidebar .w-full.mb-1.relative.group",Gm='div[dir="auto"]',Qm="theme",Vm={light:"#F4F6F8",dark:"#141618"},Km=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,Zm=/^message-([a-f0-9-]{36})$/i;const Ym=[new class extends qs{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 wo}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=Cs.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=Cs.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=Cs.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=Cs.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=Ji(i).trim();return a||this.extractTextWithLineBreaks(i)}getSidebarScrollContainer(){return Cs.query(".conversation-list",{shadow:true})||Cs.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=Cs.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:wh}}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,kh))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 Cs.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=Cs.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);}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=Cs.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=Ji(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",!!pu(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=Cs.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")||Cs.query("ucs-summary",{parent:e,shadow:true}):Cs.query("ucs-summary",{parent:e,shadow:true})||null;if(!t)return [];const n=this.extractSummaryContent(t);return Ns(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=(Cs.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{Cs.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=Cs.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=Cs.query("md-primary-tab",{all:!0,shadow:!0});for(const e of n){const n=e.querySelector("md-icon")||Cs.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 qs{cachedAccountEmail=null;accountEmailLastDetectAt=0;myStuffEnhancer=null;deepResearchPanelWatchStop=null;deepResearchPanelObservers=new WeakMap;deepResearchPanelTooltipBindings=new WeakMap;canvasPanelWatchStop=null;canvasPanelObservers=new WeakMap;canvasPanelTooltipBindings=new WeakMap;exportOpenedCanvasPanel=false;outlineWordCountCache=new WeakMap;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.injectGeminiPanelMarkdownActionStyles(),this.deepResearchPanelWatchStop=Cs.each(Vu,e=>this.watchDeepResearchPanel(e),{shadow:true}));}startGeminiCanvasPanelActions(){this.canvasPanelWatchStop||(this.injectGeminiPanelMarkdownActionStyles(),this.canvasPanelWatchStop=Cs.each(eh,e=>this.watchGeminiCanvasPanel(e),{shadow:true}));}watchDeepResearchPanel(e){if(this.syncDeepResearchPanelActions(e),this.deepResearchPanelObservers.has(e))return;let t=null;t=Cs.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);}watchGeminiCanvasPanel(e){if(this.syncGeminiCanvasPanelActions(e),this.canvasPanelObservers.has(e))return;let t=null;t=Cs.watch(e,()=>{if(!e.isConnected)return t?.(),void this.canvasPanelObservers.delete(e);this.syncGeminiCanvasPanelActions(e);},{childList:true,subtree:true,attributes:true,attributeFilter:["class","aria-checked","data-mode-id"],debounce:100}),this.canvasPanelObservers.set(e,t);}injectGeminiPanelMarkdownActionStyles(){Cs.css(`\n .${rh} {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n margin-inline-end: 4px;\n }\n\n .${oh} {\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 .${oh}:hover:not(:disabled),\n .${oh}: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 .${oh}:disabled {\n cursor: default;\n opacity: 0.38;\n }\n\n .${oh} svg {\n width: 18px;\n height: 18px;\n stroke: currentColor;\n }\n\n body.dark-theme .${oh},\n html.dark .${oh},\n html[dark-theme] .${oh} {\n color: rgba(232, 234, 237, 0.86);\n }\n\n body.dark-theme .${oh}:hover:not(:disabled),\n body.dark-theme .${oh}:focus-visible:not(:disabled),\n html.dark .${oh}:hover:not(:disabled),\n html.dark .${oh}:focus-visible:not(:disabled),\n html[dark-theme] .${oh}:hover:not(:disabled),\n html[dark-theme] .${oh}:focus-visible:not(:disabled) {\n background: rgba(232, 234, 237, 0.12);\n color: #ffffff;\n }\n `,"gh-gemini-panel-markdown-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(`[${ih}="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);}syncGeminiCanvasPanelActions(e){const t=e.querySelector("toolbar .action-buttons");if(!(t instanceof HTMLElement&&this.hasGeminiCanvasPanelExportSurface(e)))return void this.removeGeminiCanvasPanelActions(e);if(e.querySelector(`[${ah}="1"]`))return void this.updateGeminiCanvasPanelActionDisabledState(e);const n=this.createGeminiCanvasPanelActions(e),r=t.querySelector('[data-test-id="download-preview-button"]');r?.parentElement===t?t.insertBefore(n,r):t.prepend(n),this.updateGeminiCanvasPanelActionDisabledState(e);}removeDeepResearchPanelActions(e){e.querySelectorAll(`[${ih}="1"]`).forEach(e=>{e.querySelectorAll(`.${oh}`).forEach(e=>{e instanceof HTMLElement&&this.deepResearchPanelTooltipBindings.get(e)?.destroy();}),e.remove();});}removeGeminiCanvasPanelActions(e){e.querySelectorAll(`[${ah}="1"]`).forEach(e=>{e.querySelectorAll(`.${oh}`).forEach(e=>{e instanceof HTMLElement&&this.canvasPanelTooltipBindings.get(e)?.destroy();}),e.remove();});}createDeepResearchPanelActions(e){const t=document.createElement("div");t.className=rh,t.setAttribute(ih,"1");const n=this.createGeminiPanelMarkdownActionButton("copy",this.deepResearchPanelTooltipBindings),r=this.createGeminiPanelMarkdownActionButton("download",this.deepResearchPanelTooltipBindings);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}createGeminiCanvasPanelActions(e){const t=document.createElement("div");t.className=rh,t.setAttribute(ah,"1");const n=this.createGeminiPanelMarkdownActionButton("copy",this.canvasPanelTooltipBindings),r=this.createGeminiPanelMarkdownActionButton("download",this.canvasPanelTooltipBindings);return n.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.copyGeminiCanvasPanelMarkdown(e,n);}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.downloadGeminiCanvasPanelMarkdown(e);}),t.append(n,r),t}createGeminiPanelMarkdownActionButton(e,t){const n=document.createElement("button");n.type="button",n.className=oh,n.setAttribute("aria-label",this.getGeminiPanelMarkdownActionLabel(e)),n.title=this.getGeminiPanelMarkdownActionLabel(e),n.appendChild("copy"===e?Td({size:18}):this.createGeminiPanelMarkdownDownloadIcon());const r=wd(n,{getContent:()=>this.getGeminiPanelMarkdownActionLabel(e),preferredPlacement:"bottom"});return t.set(n,r),n}createGeminiPanelMarkdownDownloadIcon(){const e=kd("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 [Je,et,tt].forEach(t=>{e.appendChild(kd("path",{d:t}));}),e}getGeminiPanelMarkdownActionLabel(e){return "copy"===e?le("exportToClipboard"):`${le("webdavDownloadBtn")} ${le("exportToMarkdown")}`}updateDeepResearchPanelActionDisabledState(e){const t=this.hasDeepResearchPanelContent(e);e.querySelectorAll(`.${oh}`).forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}updateGeminiCanvasPanelActionDisabledState(e){const t=this.hasGeminiCanvasPanelExportSurface(e);e.querySelectorAll(`.${oh}`).forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}async copyDeepResearchPanelMarkdown(e,t){const n=this.getDeepResearchPanelMarkdown(e);if(!n)return void Gi(le("exportNoContent"));await va(n)?(Ed(t,{size:18}),Gi(le("copySuccess"))):Gi(le("copyFailed"));}async downloadDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdown(e);if(!t)return void Gi(le("exportNoContent"));await ba(ea(t),Na(this.getDeepResearchPanelTitle(e)||La(t,"deep-research-report"),"deep-research-report"),"text/markdown;charset=utf-8")&&Gi(le("exportSuccess"));}async copyGeminiCanvasPanelMarkdown(e,t){const n=await this.getGeminiCanvasPanelMarkdown(e);if(!n)return void Gi(le("exportNoContent"));await va(n)?(Ed(t,{size:18}),Gi(le("copySuccess"))):Gi(le("copyFailed"));}async downloadGeminiCanvasPanelMarkdown(e){const t=await this.getGeminiCanvasPanelMarkdown(e);if(!t)return void Gi(le("exportNoContent"));await ba(ea(t),Na(this.getGeminiCanvasPanelTitle(e)||La(t,"gemini-canvas"),"gemini-canvas"),"text/markdown;charset=utf-8")&&Gi(le("exportSuccess"));}getDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdownElement(e);return t?this.extractAssistantResponseTextWithAssets(t).trim():""}async getGeminiCanvasPanelMarkdown(e){return (await this.extractGeminiCanvasArtifactMarkdown(e,this.getGeminiCanvasPanelTitle(e)||"Gemini Canvas")).trim()}hasDeepResearchPanelContent(e){const t=this.getDeepResearchPanelMarkdownElement(e);return Boolean(t?.textContent?.trim())}hasGeminiCanvasPanelExportSurface(e){return null!==this.getGeminiCanvasDocumentMarkdownElement(e)||null!==this.findGeminiCanvasCodeBlock(e)||null!==e.querySelector(th)||null!==this.findGeminiCanvasCodeTab(e)}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}getGeminiCanvasPanelTitle(e){return this.getNormalizedText(e.querySelector("toolbar h2.title-text, .title-text"))||null}extractEmailFromAttr(e,t){return t&&("data-email"===e||"data-identifier"===e||$u.test(t))?this.extractEmail(t):null}extractEmail(e){if(!e)return null;const t=e.match(Bu);return t?t[1].toLowerCase():null}match(){return window.location.hostname.includes("gemini.google")&&!window.location.hostname.includes("business.gemini.google")}getSiteId(){return yo}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=Cs.query(yh,{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 this.getChatsScrollableContainer()}async loadAllConversations(){if(!(await this.ensureChatsExpandableSectionOpen()))return false;let e=this.getSidebarScrollContainer();if(!e)return false;let t=this.getLoadedGeminiConversationCount(),n=e.scrollHeight,r=Date.now();const o=Date.now();for(let i=0;Date.now()-o<9e4&&(e=this.getSidebarScrollContainer(),e);i++){this.scrollGeminiConversationHistoryToBottom(e),await this.sleep(900);const o=this.getLoadedGeminiConversationCount(),a=e.scrollHeight,s=this.isConversationHistoryLoading(),l=o>t||a>n||s;(o>t||a>n)&&(t=o,n=Math.max(n,a),r=Date.now()),s&&(r=Date.now());const c=!l&&Date.now()-r>=4e3;if(i>=6&&c)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=[fh,bh];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)}getLoadedGeminiConversationCount(){return (Cs.query(yh,{all:true,shadow:true})||[]).length}scrollGeminiConversationHistoryToBottom(e){const t=Math.max(e.scrollHeight,e.scrollTop+e.clientHeight);e.scrollTop=t,e.scrollTo?.({top:t,behavior:"auto"}),e.dispatchEvent(new Event("scroll",{bubbles:true,composed:true})),e.dispatchEvent(new WheelEvent("wheel",{bubbles:true,cancelable:true,deltaY:Math.max(600,2*e.clientHeight)}));}getChatsScrollableContainer(){const e=document.querySelector(['conversations-list[data-test-id="all-conversations"]',fh,bh,yh].join(","));if(!(e instanceof HTMLElement))return null;let t=e,n=null;for(;t&&t!==document.body;){n||"infinite-scroller"!==t.tagName.toLowerCase()||(n=t);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 n}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:Lu}}catch(vT){return console.error(`[GeminiAdapter] deleteConversationOnSiteInternal error for "${e.id}":`,vT),{id:e.id,success:false,method:"none",reason:Nu}}}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,Pu))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,Ru)&&!this.hasKeyword(e,Pu))return o}const r=n.filter(e=>!this.hasKeyword(this.getSignalText(e),Pu)).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(Ka),n=e?.getAttribute(Za);return t&&n===window.location.pathname?os(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 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(vh)}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:sh,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=null!==this.getDeepResearchDocumentOutlineRoot();return `conversation:1|${sh}:${e?1:0}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===sh?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){await this.loadCompleteExportHistory(),this.exportOpenedCanvasPanel=false,await this.prepareImagesForExport(e);const t={openedDeepResearchPanel:false};return this.isDeepResearchAppPage()&&!this.getDeepResearchAppDocumentElement()&&(t.openedDeepResearchPanel=await this.openDeepResearchAppDocumentPanel()),t}async loadCompleteExportHistory(){if(!this.isUserConversationPage())return;const e=await iu({adapter:this,waitMs:800,maxRounds:60,stableRounds:4,wheelDeltaY:-900,getSignature:e=>this.getExportHistoryLoadSignature(e)});e.success||console.warn("[GeminiAdapter] Export history load reached max rounds before stabilizing",{rounds:e.rounds,stableRounds:e.stableRounds,finalHeight:e.finalHeight});}getExportHistoryLoadSignature(e){const t=document.querySelector(this.getResponseContainerSelector())||this.getScrollContainer(),n=t?Array.from(t.querySelectorAll("user-query, model-response")).filter(e=>!e.closest("immersive-panel")):[],r=n[0],o=n[n.length-1];return [e.scrollHeight,e.clientHeight,e.scrollTop,n.length,r?this.getExportHistoryMessageMarker(r):"",o?this.getExportHistoryMessageMarker(o):""].join(":")}getExportHistoryMessageMarker(e){const t=e.closest("message-content, .conversation-turn")||e,n=t.id||t.getAttribute("data-message-id")||t.getAttribute("data-test-id")||t.getAttribute("aria-label");return n||(t.textContent||"").replace(/\s+/g," ").trim().slice(0,120)}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 ${Hu} img`,zu].join(", "))).filter(e=>e instanceof HTMLImageElement);for(const n of t)try{const t=await this.resolvePreparedExportImageSrc(n,e);if(!t)continue;n.setAttribute(Du,t);}catch(vT){console.warn("[GeminiAdapter] Failed to prepare export image source",vT);}}clearPreparedExportImageMetadata(){document.querySelectorAll(`[${Du}]`).forEach(e=>{e.removeAttribute(Du);});}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=>!_u.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(Du)||"",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(Du)||"",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(Ou):null!==e.closest(`share-landing-page ${Hu}`))}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=Iu.getActiveInstance();if(!n)return "";const r=[e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute(Du)||""],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 ti.fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.blob();return this.convertBlobToDataUrl(n)}catch(vT){return console.warn("[GeminiAdapter] Failed to inline user query image for Markdown export",vT),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/")||(!!mh.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(lh).forEach(e=>e.remove()),this.normalizeDeepResearchConfirmationWidgetsForExport(t),this.normalizeAssistantGeneratedImagesForExport(t),t}normalizeDeepResearchConfirmationWidgetsForExport(e){e.querySelectorAll(Qu).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(ch).forEach(e=>e.remove()),e.querySelectorAll(`img[${Du}]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=e.getAttribute(Du)||"";t&&(e.setAttribute("src",t),e.removeAttribute("srcset"),e.removeAttribute(Du));}),e.querySelectorAll(`${Ou} 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(Du)||"";r&&(n.setAttribute("src",r),n.removeAttribute("srcset"),n.removeAttribute(Du)),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(`${Wu} ${Gu}`):this.isDeepResearchConversationSharePage()?document.querySelector(`${ju} ${Gu}`):null)}extractDeepResearchDocumentOutline(e=6,t=false){const n=this.getDeepResearchDocumentOutlineRoot();return n?Ql(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?Vl(n,e,t,e=>this.shouldSkipOutlineHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===sh){return Kl(this.getDeepResearchDocumentOutlineRoot())||null}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===sh?this.findDeepResearchDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===sh){if(Zl(e,Kl(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,e));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(Xi,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(Xi,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(ch))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&&this.isGeminiCanvasCard(e))}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&&this.isGeminiCanvasCard(e))}isGeminiCanvasCard(e){return null!==e.querySelector(Yu)||null!==e.querySelector(Xu)}async extractGeminiCanvasAppArtifactsFromResponse(e,t){const n=this.getGeminiCanvasCardsFromResponse(e);if(0===n.length)return "";const r=[];for(const o of n){const e=this.extractGeminiCanvasTitle(o);try{const n=await this.openGeminiCanvasCardForExport(o);if(!n)continue;const i=await this.extractGeminiCanvasArtifactMarkdown(n,e,t);i&&r.push(i);}catch(vT){console.warn("[GeminiAdapter] Failed to export Gemini Canvas artifact",vT);}}return r.length>0?this.formatGeminiCanvasArtifactSections(r):this.formatGeminiCanvasFallbackTitles(n.map(e=>this.extractGeminiCanvasTitle(e)))}async extractGeminiCanvasShareArtifactsFromTurn(e,t){const n=this.getGeminiCanvasShareArtifactElements(e);if(0===n.length)return "";const r=[];for(const o of n)try{const e=await this.extractGeminiCanvasArtifactMarkdown(o,this.extractGeminiCanvasTitle(o),t);e&&r.push(e);}catch(vT){console.warn("[GeminiAdapter] Failed to export Gemini Canvas share artifact",vT);}return r.length>0?this.formatGeminiCanvasArtifactSections(r):this.formatGeminiCanvasFallbackTitles(n.map(e=>this.extractGeminiCanvasTitle(e)))}async extractGeminiCanvasArtifactMarkdown(e,t,n){if(this.isGeminiCanvasDocumentScope(e)){const r=this.extractGeminiCanvasDocumentMarkdown(e,n);if(r)return this.formatGeminiCanvasDocumentArtifact(e,t,r)}const r=this.findGeminiCanvasCodeBlock(e);if(r){const e=this.extractGeminiCanvasCodeBlockArtifact(r,t);if(e)return this.formatGeminiCanvasCodeArtifacts([e])}const o=this.findGeminiCanvasCodeEditor(e);if(o){const e=await this.extractGeminiCanvasCodeEditorArtifact(o,t);if(e)return this.formatGeminiCanvasCodeArtifacts([e])}await this.selectGeminiCanvasCodeTab(e);const i=await this.extractGeminiCanvasCodeArtifact(e,t);if(i)return this.formatGeminiCanvasCodeArtifacts([i]);const a=this.extractGeminiCanvasDocumentMarkdown(e,n);return a?this.formatGeminiCanvasDocumentArtifact(e,t,a):""}isGeminiCanvasDocumentScope(e){return e instanceof Element&&null!==e.closest(Ju)}extractGeminiCanvasDocumentMarkdown(e,t){const n=this.getGeminiCanvasDocumentMarkdownElement(e);return n?this.extractAssistantResponseTextWithAssets(n,t).trim():""}getGeminiCanvasDocumentMarkdownElement(e){return Array.from(e.querySelectorAll(nh)).find(e=>null===e.closest("thinking-panel")&&Boolean(e.textContent?.trim()))||null}formatGeminiCanvasDocumentArtifact(e,t,n){const r=e instanceof Element?this.extractGeminiCanvasTitle(e,t):t;return `${r?`### Gemini Canvas: ${r}`:"### Gemini Canvas"}\n\n${n.trim()}`}formatGeminiCanvasArtifactSections(e){const t=[],n=new Set;for(const r of e){const e=r.trim();e&&!n.has(e)&&(n.add(e),t.push(e));}return t.join("\n\n")}getGeminiCanvasPanelElement(){const e=document.querySelector(eh);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(th))return e.classList.contains("hidden")?null:e;const t=e.querySelector(th);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===V&&t.requestId===n&&i("string"==typeof t.code?t.code:"");};o=window.setTimeout(()=>i(""),900),window.addEventListener("message",a),window.postMessage({type:Q,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(eh)?.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 ${Qu}`))}getDeepResearchAppDocumentElement(){return document.querySelector(Ku)}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(Zu)&&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(`${Vu} [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(Wu)}isDeepResearchConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(ju)}isGeminiConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(Uu)}extractDeepResearchDocumentShareMessages(e){const t=document.querySelector(`${Wu} ${Gu}`),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(Gu);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(Uu));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(Hu)).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,e));i&&("assistant"===a&&(r=true),n.add(s),t.push({role:a,content:i}));}if(!r){const n=await this.extractGeminiCanvasShareArtifactsFromTurn(o,e);n&&t.push({role:"assistant",content:n});}}return {messages:this.dedupeAdjacentExportMessages(t),collectedElements:n}}collectDetachedDeepResearchArtifactMessages(e,t){return Array.from(document.querySelectorAll(`${ju} ${Gu}`)).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 Qa(e,t,{title:n,fallbackTitle:"deep-research-report",directory:"assets/documents",idPrefix:"gemini-deep-research-report"})}createUniqueGeminiExportPath(e,t){return ha(e,t.usedPaths)}extractMarkdownExportContent(e){return (Ji(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(`${Wu} h1`);return e?.textContent?.trim()||null}getDeepResearchArtifactShareTitle(){const e=document.querySelector(`${ju} 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",!!pu(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=new WeakMap,c=e=>{if(!e)return "none";const t=l.get(e);if(t)return t;const n=xl(e.textContent||"");return l.set(e,n),n},d=this.getUserQuerySelector(),u=(e,t,n)=>{if(!e)return 0;const r=[n?"user":"heading",c(e),c(t),c(o)].join("|"),i=this.outlineWordCountCache.get(e);if(i?.signature===r)return i.count;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 this.outlineWordCountCache.set(e,{signature:r,count:n}),n}const i=e.closest("message-content"),a=this.calculateRangeWordCount(e,t,i||o);return this.outlineWordCountCache.set(e,{signature:r,count:a}),a}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},c=i(t);if(c){const n=t.tagName.toLowerCase();e.id=s(c,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=u(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 xh({getUserPathPrefix:()=>this.getUserPathPrefix()}),this.myStuffEnhancer.start()),this.startDeepResearchPanelActions(),this.startGeminiCanvasPanelActions();}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(vT){return console.error("[GeminiAdapter] toggleTheme error:",vT),false}}},new class extends qs{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;outlineWordCountCache=new WeakMap;exportSnapshotRoot=null;exportSnapshotActive=false;exportBundle=null;match(){return window.location.hostname.includes("chatgpt.com")}getSiteId(){return vo}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"}getQuickQuoteSupportMode(){return "native"}getNativeQuotePopoverSelectors(){return ['div[aria-live="polite"].start-0.top-0.select-none.absolute','div[style*="transform: translate3d"] .shadow-long',"button.btn-secondary.rounded-none.border-none"]}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}getChatGPTConversationLinks(){return Array.from(document.querySelectorAll(ql)).filter(e=>"a"===e.tagName.toLowerCase()&&Boolean(this.getChatGPTConversationId(e)))}getChatGPTConversationId(e){const t=e.getAttribute("href")||"";return t.match(Rl)?.[1]||null}getChatGPTConversationTitleElement(e){return e.querySelector(".truncate [dir='auto']")||e.querySelector(".truncate span")||e.querySelector(".truncate")||e.querySelector("span")}extractConversationInfoFromLink(e,t){const n=this.getChatGPTConversationId(e);if(!n)return null;const r=this.getChatGPTConversationTitleElement(e);return {id:n,cid:t,title:r?.textContent?.trim()||"",url:`https://chatgpt.com/c/${n}`,isActive:e.hasAttribute("data-active"),isPinned:this.isChatGPTConversationPinned(e)}}isChatGPTConversationPinned(e){const t=document.querySelector("#history");if(t&&!t.contains(e))return true;const n=e.querySelector(".trailing-pair");return (n?.querySelectorAll(".trailing svg")||[]).length>1}getConversationList(){const e=this.getCurrentCid()||void 0,t=new Set,n=[];return this.getChatGPTConversationLinks().forEach(r=>{const o=this.extractConversationInfoFromLink(r,e);o&&!t.has(o.id)&&(t.add(o.id),n.push(o));}),n}getSidebarScrollContainer(){const e=document.querySelector("#history");if(e){const t=e.closest("nav");if(t)return t}const t=this.getChatGPTConversationLinks()[0],n=t?.closest("nav");return n||null}getConversationObserverConfig(){return {selector:ql,shadow:false,extractInfo:e=>{const t=this.getCurrentCid()||void 0;return this.extractConversationInfoFromLink(e,t)},getTitleElement:e=>this.getChatGPTConversationTitleElement(e)||e}}navigateToConversation(e,t){const n=this.findConversationRow(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:Tl};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?Al:this.toDeleteApiHttpReason(t??0)}}catch(vT){return vT instanceof Error&&"AbortError"===vT.name?{id:e,success:false,method:"api",reason:"delete_api_timeout"}:{id:e,success:false,method:"api",reason:El}}}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){const t=`/c/${e}`;return this.getChatGPTConversationLinks().find(e=>e.getAttribute("href")===t)||null}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(Sl.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(wl);return e&&e!==wl?e.replace(` | ${wl}`,"").replace(` - ${wl}`,"").trim():super.getSessionName()}getConversationTitle(){const e=this.getChatGPTConversationLinks().find(e=>e.hasAttribute("data-active")),t=e?this.getChatGPTConversationTitleElement(e)?.textContent?.trim():null;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=Ji(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, ${Wl}`}getChatContentSelectors(){return ['[data-message-author-role="assistant"]','[data-message-author-role="user"]',".markdown"]}getUserQuerySelector(){return this.isCodexTaskPage()?`[data-message-author-role="user"], ${jl}`:'[data-message-author-role="user"]'}isCodexTaskPage(){return /^\/(?:s\/cd_[^/]+|codex\/cloud\/tasks\/task_[^/]+)/i.test(window.location.pathname)}getCodexTaskOutlineContainer(){if(!this.isCodexTaskPage())return null;const e=document.querySelector(Wl);if(!e)return null;const t=e.parentElement;return t?.querySelector(jl)?t:e}getOutlineExtractionContainer(){return this.getCodexTaskOutlineContainer()||document.querySelector(this.getResponseContainerSelector())}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();Ml.has(n)&&!Ml.has(r)&&(e.className=`language-${n}`,e.textContent=t.slice(1).join("\n"));}});const r=Ji(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(Bl)}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:zl,assistantResponseSelector:Fl,turnSelector:Ol,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.clearExportSnapshot(),this.exportBundle=null;const t="markdown"===e.format&&"zip"===e.packaging?wa():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.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(`[${Pl}]`)&&!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(`[${Pl}]`)&&!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(`[${Pl}]`)&&!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:_l,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?$l:_l,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"",s=this.getExportTurnSortIndex(e);if(i===$l){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:$l,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:_l,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(`[${Pl}]`))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")?_l:$l,o=this.normalizeExportMessageContent(r===_l?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=Ji(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=Ha({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=Ga([{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?`[${Ca(o)}](${n})`:o,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return [{role:_l,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")&&(Ra(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=qa(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=qa(n.getAttribute("href")||n.href||"");if(Ra(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(Pl,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Dl,"1");const r=document.createElement("div");r.setAttribute(Bl,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(`[${Pl}]`).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(Ul);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&&!Hl.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)}findActiveOutlineItemId(){const e=this.getActiveNativeTocIndex();return null===e?null:`chatgpt-native-user-query::${e}::`}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 "none";const t=c.get(e);if(t)return t;const n=xl(e.textContent||"");return c.set(e,n),n},u=(e,t,n)=>{if(!e)return 0;const r=[n?"user":"heading",d(e),d(t),d(o)].join("|"),i=this.outlineWordCountCache.get(e);if(i?.signature===r)return i.count;try{if(n){let n="";for(const r of l){const o=e.compareDocumentPosition(r);if(!(o&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(r);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=r.querySelector(".markdown, .prose, [class*='prose']");if(i)n+=i.textContent||"";else {const e=r.cloneNode(!0);e.querySelectorAll(".sr-only, [class*='sr-only']").forEach(e=>e.remove()),n+=e.textContent||"";}}!n&&this.isCodexTaskPage()&&(n=o.querySelector(Wl)?.textContent||"");const i=n.trim().length;return this.outlineWordCountCache.set(e,{signature:r,count:i}),i}if(t){const n=this.calculateRangeWordCount(e,t,o);return this.outlineWordCountCache.set(e,{signature:r,count:n}),n}let i=!1,a=null;for(const t of s){if(i){a=t;break}(t===e||t.contains(e)||e.contains(t))&&(i=!0);}if(a){const t=this.calculateRangeWordCount(e,a,o);return this.outlineWordCountCache.set(e,{signature:r,count:t}),t}if(l.length>0){const t=l[l.length-1],n=this.calculateRangeWordCount(e,null,t);return this.outlineWordCountCache.set(e,{signature:r,count:n}),n}const c=this.calculateRangeWordCount(e,null,o);return this.outlineWordCountCache.set(e,{signature:r,count:c}),c}catch{return 0}},h=[];for(let b=1;b<=e;b++)h.push(`h${b}`);const g=`${a}, ${h.join(", ")}`,p=Array.from(o.querySelectorAll(g)),m=t?this.getNativeTocEntries():[];if(p.forEach((o,s)=>{const l=o.tagName.toLowerCase(),c=o.matches(a),d=/^h[1-6]$/.test(l);let h=false;if(t&&c&&(h=true),d&&!this.shouldSkipElement(o)&&!this.isInRenderedMarkdownContainer(o)){const t=(o.textContent||"").trim(),n=parseInt(l.charAt(1),10);t&&n<=e&&(h=true);}if(h){let e;if(c){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(l.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}const t=this.getChatGPTMessageId(o);if(t&&(e.id=c?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,l,e.text)),n){let t=null;for(let n=s+1;n0){const e=[],t=m.reduce((e,t)=>Math.max(e,t.index),-1),i=e=>{if(!n||!e.element)return;const r=m.find(t=>t.index>e.index);return r?.element?u(e.element,r.element,true):r||e.index!==t?void 0:u(e.element,null,true)},a=m.filter(e=>Boolean(e.element)).map(e=>({index:e.index,renderOrder:this.getElementRenderOrder(e.element,o)})).sort((e,t)=>e.renderOrder-t.renderOrder),s=m.find(e=>e.isActive),l=e=>{const t=this.getElementRenderOrder(e,o);let n,r;for(const o of a){if(!(o.renderOrder<=t)){r=o;break}n=o;}return n?n.index:r?Math.max(0,r.index-1):s?.index??0};m.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?l(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 f=this.getOrderedChatGPTTurnAnchors(o);return this.isInOutlineCacheTransition()?r:(this.recordTurnDocumentOrders(f),this.updateChatGPTOutlineCache(r,f),this.mergeCachedChatGPTOutlineItems(r,f,e,t,n,m.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([...Il])}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(Ll);if(!this.isVisible(e))return null;const t=Array.from(document.querySelectorAll(Nl));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:[...Il],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(vT){return console.error("[ChatGPTAdapter] toggleTheme error:",vT),false}}},new class extends qs{match(){const e=window.location.hostname;return "grok.com"===e||e.endsWith(".grok.com")}getSiteId(){return So}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'}getQuickQuoteSupportMode(){return "native"}getNativeQuotePopoverSelectors(){return [".absolute.bg-surface-l2.p-1.rounded-full.shadow-lg",".absolute.bg-surface-l2.p-1.rounded-full","button svg.lucide-text-quote",".absolute.bg-surface-l2.p-1.rounded-full button"]}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(()=>Vi);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||Eh}}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:Ih}:(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:Mh}}}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),Nh))return n;for(const n of e)if(this.hasKeyword(this.getIconSignal(n),Nh))return n;for(const n of e)if(this.hasKeyword(this.getElementSignal(n),Lh))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&&Th.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=Ji(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 Ji(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=Ji(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=Ha({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=qa(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)&&(Ra(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 ja(e,t,{siteId:this.getSiteId()})}formatGrokUserFileAttachments(e,t){return Ga(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=qa(o);if(Ra(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(vT){return console.warn("[GrokAdapter] Failed to load share attachment metadata:",vT),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 qa(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}`:qa(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=zi.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(nl)).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(`${tl} table`)||document.querySelector(`${tl} .prompt-cards-container`)||document.querySelector(nl)||this.getLibraryEmptyStateElement()}getLibraryEmptyStateElement(){return Array.from(document.querySelectorAll(rl)).find(e=>this.isVisible(e))||null}getLibraryScrollContainer(){const e=document.querySelector(`${tl} .lib-table-wrapper`);if(e)return e;const t=document.querySelector(`${tl} .prompt-cards-container`);return t?document.scrollingElement||document.documentElement||t:document.querySelector(tl)}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:nl,shadow:false,extractInfo:e=>this.extractLibraryConversationInfo(e),getTitleElement:e=>e}:null}navigateToConversation(e,t){const n=document.querySelector(`${tl} 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:Rs}}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:Ds};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||Rs}}shouldUseNativeDeleteApi(){return false}async tryDeleteViaGrpcApi(e){const t=await this.buildGoogleAuthorizationHeader(window.location.origin);if(!t)return {id:e,success:false,method:"none",reason:Bs};const n=this.resolveGoogleApiKey();if(!n)return {id:e,success:false,method:"none",reason:$s};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:Os}:{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(i||0)}}catch{return {id:e,success:false,method:"api",reason:_s}}}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}${Us}/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(Us))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"}getQuickQuoteSupportMode(){return "disabled"}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=Ji(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=qa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&Ra(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=qa(n.href||n.getAttribute("href")||"");if(Ra(e))return e}return ""}formatAIStudioUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId(),getExtensionHint:e=>e.mimeHint||e.name})}formatAIStudioUserFileAttachments(e,t){return Ga(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:Js,assistantResponseSelector:el,turnSelector:Xs,useShadowDOM:false}:{userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:js,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?wa():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(`${Gs}, .author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]`).forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Ji(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotesFromElement(e){const t=Array.from(e.querySelectorAll(Gs)),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=Ji(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(`${js}, .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(Ks)}async collectExportMessageSnapshots(e,t){const n=Array.from((e.querySelector("ms-chat-session")||document).querySelectorAll(Hs)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Qs}]`));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:Ys,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:Zs,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===Zs).map(e=>e.turnKey.replace(/^user:/,""))),i=new Set(t.filter(e=>e.role===Ys).map(e=>e.turnKey.replace(/^assistant:/,""))),a=[];let s=null;for(let c=0;c0&&t.push({role:Zs,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:Ys,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(Gs))}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(Hs)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Qs}]`)).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:Zs,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:Ys,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(Hs)===e)[0]||null}getAssistantFragmentsForTurn(e){return Array.from(e.querySelectorAll(Ws)).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(Hs)!==e)return false;const n=t.parentElement?.closest(Ws);return n?.closest(Hs)!==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!==Zs)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(Qs,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Vs,"1");const r=document.createElement("div");r.setAttribute(Ks,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(`[${Qs}]`).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(vT){return console.error("[AIStudioAdapter] toggleTheme error:",vT),false}}},new class extends qs{activeOrganizationId=null;activeOrganizationIdExpiresAt=0;exportDocumentCache=[];exportIncludeThoughtsOverride=null;exportThoughtBlocks=new WeakMap;exportThoughtBlocksByAssistantIndex=new Map;outlineWordCountCache=new WeakMap;match(){return window.location.hostname.includes("claude.ai")||window.location.hostname.includes("claude.com")}getSiteId(){return bo}getName(){return "Claude"}getThemeColors(){return {primary:"#d97757",secondary:"#c66045"}}getQuickQuoteSupportMode(){return "native"}getNativeQuotePopoverSelectors(){return ['[data-selection-tooltip="true"]']}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(pc))||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(pc)}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(fc))}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:gc,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=this.getClaudeDocumentSignature();return `conversation:1|${gc}:${e||"0"}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===gc?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=n?Array.from(o.querySelectorAll(a)):[],l=n?Array.from(o.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(pc)):[],c=new WeakMap,d=e=>{if(!e)return "none";const t=c.get(e);if(t)return t;const n=xl(e instanceof Document?e.body?.textContent||e.documentElement?.textContent||"":e.textContent||"");return c.set(e,n),n},u=(e,t,n)=>{const r=this.outlineWordCountCache.get(e);if(r?.signature===t)return r.count;const o=n();return this.outlineWordCountCache.set(e,{signature:t,count:o}),o},h=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(pc)&&null!==e.closest(".font-claude-response"));if(h.forEach((t,i)=>{const a=parseInt(t.tagName[1]);if(a>e)return;if(t.classList.contains("pointer-events-none"))return;if(t.classList.contains("sr-only"))return;const s=t.textContent?.trim()||"";if(!s)return;const l={level:a,text:s.length>200?s.slice(0,200):s,element:t,isUserQuery:false,isTruncated:s.length>80};if(n){let e=null;for(let t=i+1;tthis.calculateRangeWordCount(t,e,n));l.wordCount=i;}}r.push(l);}),t){o.querySelectorAll('[data-testid="user-message"]').forEach(e=>{const t=e.textContent?.trim()||"";if(!t)return;const a={level:0,text:t.length>200?t.slice(0,200):t,element:e,isUserQuery:true,isTruncated:t.length>60};n&&(a.wordCount=(e=>{const t=s.indexOf(e);if(-1===t)return 0;const n=s[t+1],r=["user",d(e),d(n||null),d(o)].join("|");return u(e,r,()=>{let t=0;for(const r of l){if(!(e.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(n&&n.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING)continue;const o=r.querySelector(".standard-markdown, .progressive-markdown");if(o){const e=o.textContent?.trim()||"";t+=i(e).length;}}return t})})(e)),r.push(a);}),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?Ql(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?Vl(n,e,t,e=>this.shouldSkipClaudeDocumentHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===gc){return Kl(this.getClaudeDocumentMarkdownElement())||this.getClaudeDocumentRoot()}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===gc?this.findClaudeDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===gc){if(Zl(e,Kl(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(pc));if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".standard-markdown, .progressive-markdown");if(n){return Ji(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||"";wc(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(!wc(t))return;const n=tc(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(bc)||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(pc)).flatMap(e=>{if(e.closest(bc))return [];const t=qa(e.currentSrc||e.src||e.getAttribute("src")||"");if(!t||!Ra(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(bc)).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=qa(o.href||o.getAttribute("href")||"");if(Ra(e))return e}const n=e.querySelector("img");if(n instanceof HTMLImageElement){const e=qa(n.currentSrc||n.src||n.getAttribute("src")||"");if(Ra(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=qa(r.getAttribute(e)||"");if(Ra(t))return t}return ""}formatClaudeUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId(),getAlt:e=>e.alt||e.name||"uploaded image"})}formatClaudeUserFileAttachments(e,t){return Ga(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(pc)),i=Math.max(r.length,o.length);for(let a=0;a{if(e.matches(fc))return void i.push(this.formatClaudeArtifactExportContent(e,t));const n=Ji(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(`${mc}, ${fc}`)).filter(e=>!e.closest(pc)&&!this.isInsideClaudeThoughtBlock(e)).filter(t=>{const n=t.parentElement?.closest(`${mc}, ${fc}`);return !n||!e.contains(n)})}prepareClaudeAssistantMarkdownBlockForExport(e,t){const n=this.getClaudeArtifactCells(e),r=e.cloneNode(true);return Array.from(r.querySelectorAll(fc)).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(yc);t instanceof HTMLElement&&"true"===t.getAttribute("aria-expanded")&&this.simulateClick(t);});}getClaudeThoughtToggleButtons(e=document){return Array.from(e.querySelectorAll(yc)).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(vc)?.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(vc),t=null!==r.querySelector(yc);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(pc)).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(pc)).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(vc)?.textContent?.trim()||"";n.push(this.formatAsThoughtBlockquote(o,i));}),n}extractClaudeThoughtMarkdown(e){const t=e.cloneNode(true);return t.querySelectorAll(`${yc}, ${vc}, svg`).forEach(e=>e.remove()),Ji(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?Qa(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:xc(),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(vT){return console.error("[ClaudeAdapter] toggleTheme error:",vT),false}}},new class extends qs{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 Eo}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(Sc);if(t?.[1])return t[1];const n=e.match(Cc);return n?.[1]||""}isNewConversation(){const e=window.location.pathname;return !this.isSharePage()&&("/"===e||"/a/chat"===e||"/a/chat/"===e||!Sc.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:Tc,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:Fc};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:Fc}));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(`${Tc}[href*="/a/chat/s/${e}"]`):null)||document.querySelector(`${Tc}[aria-current="page"]`);return t?this.extractConversationTitle(t):null}navigateToConversation(e,t){const n=document.querySelector(`${Tc}[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(Tc);return e?.closest(".ds-scroll-area")||null}getZenModeConfig(){return {hide:[".dc04ec1d","._0fcaa63"]}}getCleanModeConfig(){return {hide:["._0fcaa63"]}}getScrollContainer(){const e=Array.from(document.querySelectorAll(Ec)).filter(e=>!e.parentElement?.closest(Ec)),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll(`${Ac}, ${Mc}`)).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 Mc}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 [Ac,Mc]}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(Ec)).filter(e=>!e.parentElement?.closest(Ec));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:$c,assistantResponseSelector:_c,turnSelector:null,useShadowDOM:false}:{userQuerySelector:Mc,assistantResponseSelector:Ac,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportBundleCache=null,this.clearExportSnapshot();const t="markdown"===e.format&&"zip"===e.packaging?wa():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="${zc}"])`,`button.ds-icon-button:has(svg path[d="${zc}"])`]}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:Lc,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(Oc))return true}return false}getStopButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d^="${Oc}"])`,`button.ds-icon-button:has(svg path[d^="${Oc}"])`]}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(kc,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:kc,newValue:n,storageArea:localStorage})),!0}catch(vT){return console.error("[DeepSeekAdapter] toggleTheme error:",vT),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(Ec).length,i=e.querySelectorAll(Mc).length,a=e.querySelectorAll(Ac).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(Tc)&&!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(Ec)&&(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(Mc)).filter(e=>e instanceof HTMLElement&&!e.parentElement?.closest(Ec))}sleep(e){return new Promise(t=>window.setTimeout(t,e))}isExportSnapshotElement(e){return e.hasAttribute(Pc)}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(vT){return console.warn("[DeepSeekAdapter] Failed to collect share export payload:",vT),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:Dc,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:Bc,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?qa(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(Mc))return e;const t=e.closest(Mc);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 ja(e,t,{siteId:this.getSiteId()})}formatUserFileAttachments(e,t){return Ga(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=qa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&Ra(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=qa(r.getAttribute("href")||r.href||"");if(Ra(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(Ec))return e;const t=e.closest(Ec);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(Ic)}extractThoughtBlockquotesFromMessage(e){const t=Array.from(e.querySelectorAll(`${Ic} .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=Ji(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(Ac)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Rc}]`)&&!e.closest(".gh-root")&&!e.parentElement?.closest(Ec))}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(Ec)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Rc}]`)&&!e.parentElement?.closest(Ec)).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:Bc,content:t}:null}const n=this.normalizeExportMessageContent(this.extractDeepSeekUserQueryExportContent(e,t));return n?{role:Dc,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(Rc,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Pc,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(`[${Rc}]`).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:Uc}}}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 Hc;const t=e;if("string"==typeof t.msg&&t.msg.trim())return `${Wc}:${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 `${Wc}:${e.biz_msg.trim()}`}return Wc}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(qc,"1");}catch{}window.location.replace(Nc);}schedulePageReloadAfterDelete(){window.setTimeout(()=>{window.location.reload();},0);}consumePendingDeleteRefresh(){let e=false;try{if(e="1"===sessionStorage.getItem(qc),!e)return;sessionStorage.removeItem(qc);}catch{return}if("/"===window.location.pathname||""===window.location.pathname)setTimeout(()=>{window.location.reload();},0);else {try{sessionStorage.setItem(qc,"1");}catch{}window.location.replace(Nc);}}findNextAssistantMarkdown(e,t){for(let n=t+1;n!e.parentElement?.closest(Ec)),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(Tc)}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 qs{outlineCacheSessionKey="";outlineCacheTransitionEndAt=0;outlineItemCache=new Map;exportMessagesCache=null;exportBundleCache=null;match(){return "www.doubao.com"===window.location.hostname}getSiteId(){return ko}getName(){return "豆包"}getThemeColors(){return {primary:"#315efb",secondary:"#0f6eff"}}getQuickQuoteSupportMode(){return "native"}getNativeQuotePopoverSelectors(){return ['[data-word-selection-toolbar="true"]',".toolContainer-tlVomx",".toolItem-C_B5bD"]}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(jc);return n?.[1]||null}extractConversationTitle(e){const t=e.querySelector(Kc)||Array.from(e.querySelectorAll("span")).find(e=>e.textContent?.trim())||null;return t?.textContent?.trim()||""}getConversationRows(e=document){return Array.from(e.querySelectorAll(Vc))}getHistoryContainer(){return document.querySelector(Qc)}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(Yc)).find(e=>{if(!e.isConnected)return false;if(!(e.querySelector('[data-name="scroll_holder"]')||e.querySelector(Xc)||e.querySelector(Jc)))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(`${ed}, ${rd}`);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(id)&&t.push(e),Array.from(e.querySelectorAll(id)).forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);}),t}getAssistantContentRoot(e){return e.matches(id)?e:e.querySelector(id)||e}getConversationTitle(){const e=this.getActiveConversationRow();return e&&this.extractConversationTitle(e)||null}getSessionId(){const e=window.location.pathname.match(jc),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/`}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}, ${Vc}[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:Vc,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(Kc)||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:dd}}async deleteConversationsOnSite(e){const t=[];for(let n=0;ne.remove());const n=Ji(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(rd);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantMarkdown(t)||null}getUserMessageTextContainer(e){return e.matches(td)?e:e.matches(ed)?e.querySelector(td):e.querySelector(nd)||e.querySelector(td)}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 ja(e,t,{siteId:this.getSiteId()})}formatDoubaoUserFileAttachments(e,t){return Ga(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 Wa(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=qa(e);return t?/^data:image\/svg\+xml/i.test(t)?"":/^data:image\//i.test(t)||Ra(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)),cd.forEach(n=>{t.push(e.getAttribute(n)||"");});});for(const n of t){const e=qa(n);if(!/^data:image\/svg\+xml/i.test(e)&&(this.normalizeDoubaoImageSource(e)||Ra(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(Xc)).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(`${ed}, ${rd}`)).filter(e=>e instanceof HTMLElement)).forEach((e,i)=>{const a=this.getVirtualMessageMeta(e,i),s=e.matches(ed)?e:e.querySelector(ed)??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:ed,assistantResponseSelector:rd,turnSelector:Jc,useShadowDOM:false}}async prepareConversationExport(e){this.clearExportCache();const t="markdown"===e.format&&"zip"===e.packaging?wa():void 0,n=this.getVirtualScrollContainer(),r=this.getOutlineContentContainer()||document,o=n?await this.collectDoubaoExportSnapshotsByScrollSweep(n,t):this.readVisibleDoubaoExportSnapshots(r,t,this.createDoubaoAssistantImageFallbackState());if(0===o.length)return null;const i=o.map(({role:e,content:t})=>({role:e,content:t}));return this.exportMessagesCache=i,t&&(this.exportBundleCache={messages:i,assets:t.assets}),{count:i.length}}async restoreConversationAfterExport(e,t){this.clearExportCache();}async extractExportMessages(e){if(this.exportMessagesCache)return this.exportMessagesCache;const t=this.extractDoubaoExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.exportBundleCache?this.exportBundleCache:this.createExportBundleFromMessages(e=>this.extractDoubaoExportMessages(e))}clearExportCache(){this.exportMessagesCache=null,this.exportBundleCache=null;}async collectDoubaoExportSnapshotsByScrollSweep(e,t){const n=this.buildDoubaoExportSnapshotPositions(e),r=e.scrollTop,o=this.createDoubaoAssistantImageFallbackState();let i=[];try{for(const r of n){this.scrollVirtualContainerTo(e,r),e.getBoundingClientRect(),await this.sleep(120);const n=this.readVisibleDoubaoExportSnapshots(e,t,o);i=this.mergeDoubaoExportSnapshotBatch(i,n);}}finally{this.scrollVirtualContainerTo(e,r);}return i}buildDoubaoExportSnapshotPositions(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)}readVisibleDoubaoExportSnapshots(e,t,n){return this.getOrderedDoubaoMessages(e).map(({role:r,element:o})=>{const i="user"===r?this.extractUserQueryExportContentWithAssets(o,t):this.extractAssistantResponseTextWithAssets(o,t,n),a=this.normalizeDoubaoExportMessageContent(i);return a?{role:r,content:a,key:this.getDoubaoExportMessageKey(o,r,a),order:this.getDoubaoExportMessageOrder(e,o)}:null}).filter(e=>null!==e)}normalizeDoubaoExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}getDoubaoExportMessageKey(e,t,n){const r=e.getAttribute("data-message-id")||e.closest("[data-message-id]")?.getAttribute("data-message-id")||"";if(r)return `${t}:${r}`;const o=Math.round(this.getDoubaoExportMessageOrder(document,e));return `${t}:content:${this.hashOutlineText(n)}:${o}`}getDoubaoExportMessageOrder(e,t){if(t instanceof HTMLElement&&e instanceof HTMLElement)return this.getElementVirtualScrollTop(e,t);const n=t.getBoundingClientRect();return window.scrollY+n.top}mergeDoubaoExportSnapshotContent(e,t){return t?e?e===t||e.includes(t)?e:t.includes(e)||t.length>e.length?t:e:t:e}mergeDoubaoExportSnapshotBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));const n=new Map;return e.forEach(e=>n.set(e.key,{...e})),t.forEach(e=>{const t=n.get(e.key);t?n.set(e.key,{...t,order:Math.min(t.order,e.order),content:this.mergeDoubaoExportSnapshotContent(t.content,e.content)}):n.set(e.key,{...e});}),Array.from(n.values()).sort((e,t)=>e.order-t.order)}extractDoubaoExportMessages(e){const t=this.createDoubaoAssistantImageFallbackState();return this.readVisibleDoubaoExportSnapshots(document,e,t).map(({role:e,content:t})=>({role:e,content: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(ed)?r("user",e):e.matches(rd)&&r("assistant",e)),e.querySelectorAll(ed).forEach(e=>r("user",e)),e.querySelectorAll(rd).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 [Zc]}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:`${ed} .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 qs{exportIncludeThoughts=void 0;match(){return window.location.hostname===qh}getSiteId(){return To}getName(){return "ima"}getThemeColors(){return {primary:"#07a45f",secondary:"#05854d"}}supportsHostThemeSync(){return false}getSessionId(){const e=window.location.pathname.match(Rh);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 [ng]}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(ng);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(Ph);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Dh}getChatContentSelectors(){return [_h,Hh]}getUserQuerySelector(){return _h}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(Hh),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(Dh)||document.querySelector(Ph);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(`${_h}, ${Hh}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((r,a)=>{if(r.matches(_h)){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(Hh));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 [rg]}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([ig]),t=e?.innerText?.trim()||e?.textContent?.trim()||"";if(t)return t.split("\n")[0].trim();const n=this.findVisibleElementBySelectors([og]),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:[og,ig],menuItemSelector:'.modelDropdown .t-dropdown__item, .modelDropdown [class*="modelOption"], .t-popup .modelDropdown .t-dropdown__item',menuRenderDelay:200,checkInterval:1e3,maxAttempts:10}}getWidthSelectors(){return [{selector:Ph,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:Dh,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:Fh,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(Dh)||document.querySelector(Ph)||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${_h}, ${Hh}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches(_h)?"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(`${Kh}, ${eg}`).forEach(e=>e.remove()),n.querySelectorAll(Qh).forEach(e=>e.remove());const o=this.findAssistantMarkdownRoot(n),i=o instanceof HTMLElement?o:this.findAssistantBubbleRoot(n),a=(i?Ji(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,Yh).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractImaUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,Xh).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()||Ea(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:Aa(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}=Ia(t),i=this.extractImaDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||Ea(i,{ignoreGenericDownload:true})||this.extractDataAttributeFilename(e);if(!a&&!i)return null;const s=a||"attachment";return {kind:"file",name:s,source:i,type:r||Aa(s)||Ma(i),sizeLabel:o}}formatImaUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId()})}formatImaUserFileAttachments(e,t){return Ga(e,t,{siteId:this.getSiteId()})}extractImaAssistantImages(e){const t=this.findAssistantBubbleRoot(e)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,Jh).forEach(e=>{if(!(e instanceof HTMLImageElement))return;if(e.closest(".gh-root, .gh-user-query-markdown"))return;const t=this.extractImaImageSource(e),o=Ta(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 Wa(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||tg.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=qa(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(!Ra(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===qh&&/^\/(?:chat|share|ai-chat)(?:\/|$)/i.test(e.pathname))return "";if(e.hostname===qh&&/\/(?: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)||Aa(e)).find(Boolean)||""}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll(Kh).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=Ta(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(_h)?e:e.closest(_h)||e}findAssistantBubbleRoot(e){if(e.matches(Wh))return e;const t=e.querySelector(Wh);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(Uh)?e:e.querySelector(Uh)||e.querySelector("p")||e}findAssistantMarkdownRoot(e){return e.matches(Gh)?e:e.querySelector(Gh)}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll(Vh).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(Qh)),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=(Ji(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 qs{exportIncludeThoughtsOverride=null;exportApiMessages=null;match(){return ol.has(window.location.hostname)}getSiteId(){return xo}getName(){return "智谱清言"}getThemeColors(){return {primary:"#2454FF",secondary:"#1F46D6"}}getQuickQuoteSupportMode(){return "native"}getNativeQuotePopoverSelectors(){return ['[class*="quote-button"]','[class*="reference-button"]','[aria-label*="引用"]','[aria-label*="quote"]']}async toggleTheme(e){const t=sl[e]||sl.light;try{localStorage.setItem(al,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:al,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(ll);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 yl}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(il)?.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 [`${vl}:not(.empty)`]}findSubmitButton(){const e=document.querySelector(vl);return !e||e.classList.contains("empty")||null===e.offsetParent?null:e}getScrollContainer(){const e=document.querySelector(dl);if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chatScrollContainer");return t&&t.scrollHeight>t.clientHeight?t:super.getScrollContainer()}getResponseContainerSelector(){return dl}getChatContentSelectors(){return [pl,hl]}getUserQuerySelector(){return ul}extractUserQueryText(e){const t=e.querySelector(hl)||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(hl);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(dl)||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(dl);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(".conversation-item"));return i.forEach((r,a)=>{const s=r.querySelector(ul);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(pl);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(vT){return console.warn("[ChatGLMAdapter] Failed to load share export metadata:",vT),null}}getShareConversationId(){return new URLSearchParams(window.location.search).get(il)?.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(dl)||document.body,n=this.collectChatGLMAssistantExportElements(t),r=[...Array.from(t.querySelectorAll(ul)).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(`${gl}, ${ml}`)).forEach(e=>{if(e.closest(".gh-root, .gh-user-query-markdown"))return;const r=this.findChatGLMThoughtRoot(e),o=r?.closest(gl);if(r&&o&&o!==r)return;const i=r||e;!r&&e.closest(ml)||n.has(i)||(n.add(i),t.push(i));}),t.sort((e,t)=>this.compareDomOrder(e,t))}findChatGLMThoughtRoot(e){let t=e.matches(ml)?e:e.closest(ml);if(!t)return null;let n=t.parentElement?.closest(ml)||null;for(;n;)t=n,n=t.parentElement?.closest(ml)||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(ml),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(ml).forEach(e=>e.remove());const s=this.extractChatGLMAssistantImageMarkdown(e,t),l=(o.matches(gl)||o.matches(".markdown-body")?o:o.querySelector(".markdown-body")||o).cloneNode(true);l.querySelectorAll(fl).forEach(e=>e.remove()),l.querySelectorAll("img").forEach(e=>{e instanceof HTMLImageElement&&this.isExportableChatGLMImage(e)&&e.remove();});const c=(Ji(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(ul)?e:e.closest(ul);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 ja(e,t,{siteId:this.getSiteId()})}formatChatGLMAssistantImageAttachments(e,t){return ja(this.dedupeChatGLMAttachments(e),t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}formatChatGLMUserFileAttachments(e,t){return Ga(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(ml)?[e]:[],...Array.from(e.querySelectorAll(ml))].filter(e=>!e.parentElement?.closest(ml)),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(fl).forEach(e=>e.remove());const o=document.createElement("div");Array.from(t.childNodes).forEach(e=>o.appendChild(e.cloneNode(true)));const i=(Ji(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(!Ra(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 bl){const t=this.normalizeChatGLMAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeChatGLMAttachmentSource(e){const t=qa(e);if(!t||!Ra(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=[".enter.searching .enter-icon-container",".stop-generate",".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 [".enter.searching .enter-icon-container",".stop-generate",".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 qs{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 Ao}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(lg.some(e=>t.startsWith(e)))return "";const n=e.match(ag);if(n?.[1])return n[1];const r=e.match(sg);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:fg,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(`${yg}, ${vg}`)||e}}getSidebarScrollContainer(){const e=[document.querySelector(".history .group-list-container"),document.querySelector(bg),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(fg).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:Dg};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:Dg}));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(bg)?r:super.getScrollContainer()}getResponseContainerSelector(){return wg}getChatContentSelectors(){return [Ng,Ig]}getUserQuerySelector(){return Eg}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(Rg).forEach(e=>e.remove());const n=this.shouldIncludeThoughtsInExport()?this.extractThoughtBlockquotes(t):[];t.querySelectorAll(qg).forEach(e=>e.remove());const r=this.findAssistantBodyMarkdownRoot(t);if(!r)return n.length>0?n.join("\n\n"):"";const o=(Ji(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(Ng);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(wg);if(!r)return [];const o=[],i=this.getChatItems(r);return i.forEach((r,a)=>{if(r.matches(kg)||r.matches(Eg)||r.querySelector(Eg)){if(!t)return;const e=r.querySelector(Eg)||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(Tg)&&!r.matches(Ag)&&!r.querySelector(Ng))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(Pg,t);const n=document.documentElement;return n.classList.remove("light","dark"),n.classList.add(e),window.dispatchEvent(new StorageEvent("storage",{key:Pg,newValue:t,storageArea:localStorage})),!0}catch(vT){return console.error("[KimiAdapter] toggleTheme error:",vT),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:Sg,property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important; min-width: 0 !important; padding-left: 0 !important; padding-right: 0 !important;"},{selector:Sg,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:Mg,property:"width",extraCss:e,noCenter:true},{selector:Ig,property:"width",value:"100%",extraCss:t,noCenter:true},{selector:Lg,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(`${Tg} .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(Pg);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(Pg,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:Bg}}}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(dg);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 ug){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 hg){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(hg.includes(o)||t>0&&!pg.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 $g;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?`${_g}:${n}`:_g}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(yg)?.textContent?.trim()||e.querySelector(vg)?.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(ag);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(fg);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(`${mg}.router-link-active, ${mg}.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(mg).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(wg);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(Eg)?e:e.querySelector(Eg)}findKimiAssistantMessageRoot(e){if(e.matches(Ag))return e;const t=e.querySelector(Ag);if(t)return t;const n=this.findAssistantBodyMarkdownRoot(e);return n?.closest(Ag)||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(Rg).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=Ha({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=qa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&Ra(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=Ga([{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=qa(r.getAttribute("href")||r.href||"");if(Ra(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(Ng);return t&&!this.isInsideAssistantToolcall(t)?t:Array.from(e.querySelectorAll(".markdown")).find(e=>!this.isInsideAssistantToolcall(e))||null}isInsideAssistantToolcall(e){return null!==e.closest(qg)||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(Rg).forEach(e=>e.remove());const t=Array.from(e.querySelectorAll(".markdown")),o=(t.length>0?t.map(e=>Ji(e)||this.extractTextWithLineBreaks(e)).join("\n\n"):Ji(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(Cg)).filter(e=>!e.parentElement?.closest(Cg));return t.length>0?t:Array.from(e.children).filter(e=>e.matches(kg)||e.matches(Tg)||e.matches(Eg)||e.matches(Ag)||null!==e.querySelector(Eg)||null!==e.querySelector(Ng))}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:mp,shadow:false,extractInfo:e=>this.extractSidebarConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(fp)||e}}getSidebarScrollContainer(){return document.querySelector(`${gp} ${pp}`)||document.querySelector(pp)||document.querySelector(gp)}async loadAllConversations(){await this.refreshConversationSnapshot({force:true,fetchAllPages:true});}navigateToConversation(e,t){const n=this.getCurrentCid()||void 0,r=document.querySelectorAll(mp);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 [`${Cp}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Cp);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(bp);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return yp}getAssistantMermaidSupportMode(){return "native"}extractFormulaCopySource(e,t){const n=e.closest(Wp)||t.closest(Wp);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 [vp,xp]}getUserQuerySelector(){return vp}getLatestReplyText(){const e=document.querySelectorAll(xp),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(`${Rp}, ${Bp}`).forEach(e=>e.remove());const i=(Ji(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(xp);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(Tp));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(yp)||document.querySelector(bp);if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${vp}, ${xp}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(vp)){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(xp));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(Ip)&&!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 loadCompleteExportHistory(){const e=await iu({adapter:this,waitMs:800,maxRounds:60,stableRounds:4,wheelDeltaY:-900,getSignature:e=>this.getExportHistoryLoadSignature(e)});e.success||console.warn("[QwenAiAdapter] Export history load reached max rounds before stabilizing",{rounds:e.rounds,stableRounds:e.stableRounds,finalHeight:e.finalHeight});}getExportHistoryLoadSignature(e){const t=this.getQwenExportRoot(),n=this.getOrderedQwenMessages(t),r=n[0]?.element,o=n[n.length-1]?.element;return [e.scrollHeight,e.clientHeight,e.scrollTop,n.length,r?this.getExportHistoryMessageMarker(r):"",o?this.getExportHistoryMessageMarker(o):""].join(":")}getExportHistoryMessageMarker(e){const t=e.closest(".qwen-chat-message, [data-message-id]")||e,n=t.id||t.getAttribute("data-message-id")||t.getAttribute("data-testid")||t.getAttribute("aria-label");return n||(t.textContent||"").replace(/\s+/g," ").trim().slice(0,120)}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(vT){return console.error("[QwenAiAdapter] toggleTheme error:",vT),false}}getModelName(){const e=document.querySelector(Op),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:[_p,Op],menuItemSelector:Hp,checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:Up,subMenuTriggers:["展开更多模型","更多模型","view more","more models"]}}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [...kp]}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:[gp]}}getCleanModeConfig(){return {hide:[".chat-container-statement"]}}getMarkdownFixerConfig(){return {selector:`${xp} .qwen-markdown-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(xp);if(!t)return false;const n=document.querySelectorAll(xp);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(vT){console.warn("[QwenAiAdapter] Failed to refresh conversation snapshot:",vT);}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(mp);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(fp),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(up);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(yp)||document.querySelector(bp)||document.body}getOrderedQwenMessages(e){const t=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,vp)).filter(e=>!this.shouldSkipExportElement(e)),n=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,xp)).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,wp)),r=[],o=new Set;return n.forEach(e=>{if(e.closest(".gh-user-query-markdown"))return;const t=e.cloneNode(true);t.querySelectorAll(Rp).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,Pp)).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()||Ea(n)||"uploaded image";return {kind:"image",name:r,source:n,type:Aa(r)||Ma(n)||"image"}}extractQwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=Ia(t),i=this.extractQwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||Ea(i)||"attachment";return {kind:"file",name:a,source:i,type:r||Aa(a)||Ma(i),sizeLabel:o}}formatQwenUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId()})}formatQwenUserFileAttachments(e,t){return Ga(e,t,{siteId:this.getSiteId()})}extractQwenAssistantImages(e){const t=e.closest(xp)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,Dp).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 Wa(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(vp)?e:e.closest(vp)||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)),$p.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=qa(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(!Ra(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===window.location.hostname&&(up.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=Ta(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(Tp)).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(xp);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(Tp)).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(Mp,"true");}}async restoreMermaidBlocksAfterExport(){const e=Array.from(document.querySelectorAll(`${Tp}[${Mp}]`));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(Mp);}}clearMermaidExportMarkers(){document.querySelectorAll(`${Tp}[${Mp}]`).forEach(e=>e.removeAttribute(Mp));}getQwenMermaidActiveView(e){const t=e.querySelector(Ep);if(!(t instanceof HTMLElement))return null;const n=Array.from(t.querySelectorAll(Ap));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(Ep);if(!(n instanceof HTMLElement))return null;const r=Array.from(n.querySelectorAll(Ap));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(Lp)?.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(Np);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=(Ji(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(Up);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(()=>Vi);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(vT){console.error("[QwenAiAdapter] Failed to show model lock error:",vT);}}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(wp)?e:e.querySelector(wp)||e}findAssistantContentRoot(e){return e.matches(Sp)?e:e.querySelector(Sp)||e}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return this.normalizeQwenCodeBlocks(n),n.querySelectorAll(`${Ip}, ${qp}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}findModelTrigger(){const e=document.querySelector(_p);if(e instanceof HTMLElement&&this.isVisibleActionElement(e))return e;const t=document.querySelector(Op);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(Cp);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 qs{exportIncludeThoughts=void 0;match(){const e=window.location.hostname;return "www.qianwen.com"===e||"qianwen.com"===e}getSiteId(){return Mo}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"}getQuickQuoteSupportMode(){return "disabled"}getSessionId(){const e=window.location.pathname.match(Og);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()&&Og.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 zg.test(window.location.pathname)?null:super.getCurrentConversationInfo()}getConversationTitle(){return this.getSessionName()}getTextareaSelectors(){return ['[class*="chatTextarea"]',`${np} [contenteditable="true"]`,'[data-slate-editor="true"][contenteditable="true"]','div[role="textbox"][contenteditable="true"]',"textarea"]}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!e.closest(sp)&&(!!(e.isContentEditable||e instanceof HTMLTextAreaElement)&&!(!e.closest(np)&&!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{const n=window.getSelection();n&&n.selectAllChildren(t),document.execCommand("delete",!1);if(document.execCommand("insertText",!1,e))return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,composed:!0,data:e,inputType:"insertText",cancelable:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),requestAnimationFrame(()=>{t.focus();const e=window.getSelection();e&&e.collapse(t,t.childNodes.length);}),!0}catch(vT){console.warn("[QianwenAdapter] insertPrompt execCommand failed:",vT);}return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:true,composed:true,data:e,inputType:"insertText",cancelable:true})),t.dispatchEvent(new Event("change",{bubbles:true})),requestAnimationFrame(()=>{t.focus();const e=window.getSelection();e&&e.collapse(t,t.childNodes.length);}),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{const t=window.getSelection();t&&t.selectAllChildren(e);if(document.execCommand("delete",!1))return e.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,composed:!0,data:"",inputType:"deleteContentBackward",cancelable:!0})),void e.dispatchEvent(new Event("change",{bubbles:!0}))}catch(vT){console.warn("[QianwenAdapter] clearTextarea execCommand failed:",vT);}e.textContent="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward",cancelable:true})),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(np),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=[document.querySelector(op),document.querySelector(rp)].filter(Boolean);for(const r of e){const e=this.findConversationScrollableAncestor(r);if(e)return e}const t=[rp,op,ip];for(const r of t){const e=document.querySelectorAll(r);for(const t of Array.from(e)){const e=t;if(this.isScrollableConversationContainer(e))return e}}const n=document.scrollingElement;return n instanceof HTMLElement&&this.isScrollableConversationContainer(n)?n:null}getResponseContainerSelector(){return `${op}, ${rp}`}getChatContentSelectors(){return [Hg,jg]}getUserQuerySelector(){return Hg}getLatestReplyText(){const e=document.querySelectorAll(jg),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,await this.loadCompleteConversationHistory(),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(op)||document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${Hg}, ${jg}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(Hg)){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(jg));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(sp)&&!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(Ug,"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:`${op}`,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:Qg,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:`${Hg} ${Gg}`,property:"max-width",extraCss:e,noCenter:true},{selector:Wg,property:"max-width",extraCss:e,noCenter:true}]}getZenModeConfig(){return {hide:[ap]}}getCleanModeConfig(){return {hide:["#ice-container .root-G6nVVr"]}}getMarkdownFixerConfig(){return {selector:`${jg} .qk-md-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(jg);if(!t)return false;const n=document.querySelectorAll(jg);return t===n[n.length-1]}}}async loadCompleteConversationHistory(){let e=this.getScrollContainer();if(!e)return;let t="",n=0;for(let r=0;r<60;r++){const r=this.getScrollContainer();r&&(e=r),this.scrollConversationContainerToTop(e),await this.sleep(650);const o=this.getConversationLoadSignature(e);if(o===t?n++:(t=o,n=0),n>=4)return}}scrollConversationContainerToTop(e){e===document.documentElement||e===document.body?window.scrollTo({top:0,behavior:"auto"}):e.scrollTop=0,e.dispatchEvent(new Event("scroll",{bubbles:true})),e.dispatchEvent(new WheelEvent("wheel",{deltaY:-800,bubbles:true})),window.dispatchEvent(new Event("scroll"));}getConversationLoadSignature(e){return [e.scrollHeight,e.clientHeight,e.scrollTop,this.getExportableMessageBlockCount()].join(":")}getExportableMessageBlockCount(){const e=this.getExportRoot();return this.collectTopLevelBlocks(Array.from(e.querySelectorAll(`${Hg}, ${jg}`))).filter(e=>!e.closest(".gh-root")).length}findConversationScrollableAncestor(e){let t=e.parentElement;for(;t&&t!==document.body;){if(this.isScrollableConversationContainer(t))return t;t=t.parentElement;}return null}isScrollableConversationContainer(e){if(!e.isConnected)return false;if(!(e===document.documentElement||e===document.body||Boolean(e.querySelector(`${op}, ${rp}, ${Hg}, ${jg}`))))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return false;const n=e.getBoundingClientRect();return (e===document.documentElement||e===document.body||!(n.width<=0||n.height<=0))&&e.scrollHeight>e.clientHeight+5}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(op)||document.querySelector(rp)||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,`${Hg}, [data-chat-question-wrap]`)),i=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,jg));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([ep,Jg,"picture","img"].join(", ")).forEach(e=>e.remove());const r=`${sp}, [class*="thinkingTitle"]`;n.querySelectorAll(r).forEach(e=>e.remove());const o=(Ji(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,Ta(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,Kg).forEach(e=>o(this.extractQianwenUserImageAttachment(e))),this.queryElementsIncludingSelf(t,Zg).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()||Ea(n)||"uploaded image";return {kind:"image",name:r,source:n,type:Aa(r)||Ma(n)}}extractQianwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=Ia(t),i=this.extractQianwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||Ea(i)||"attachment";return {kind:"file",name:a,source:i,type:r||Aa(a)||Ma(i),sizeLabel:o}}formatQianwenUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId()})}formatQianwenUserFileAttachments(e,t){return Ga(e,t,{siteId:this.getSiteId()})}extractQianwenAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,Xg).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 Wa(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}findUserMessageScope(e){return e.matches(Hg)||e.matches("[data-chat-question-wrap]")?e:e.closest(Hg)||e.closest("[data-chat-question-wrap]")||e}findAssistantContentRoot(e){return e.matches(Yg)?e:e.querySelector(Yg)||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)),tp.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=qa(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!Ra(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=(Ji(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(`${sp}, .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(Gg)?e:e.querySelector(Gg)||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(ap))return false;if(t.closest(np))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(cp)).filter(e=>this.isVisibleElement(e));if(0===e.length)return [];const t=[];return e.forEach(e=>{const n=e.querySelectorAll(dp);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(cp)).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()}sleep(e){return new Promise(t=>setTimeout(t,e))}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 qs{exportIncludeThoughtsOverride=null;match(){return window.location.hostname===jp}getSiteId(){return Lo}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 [Vp]}findSubmitButton(){const e=document.querySelector("#yuanbao-send-btn");if(this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e;const t=Array.from(document.querySelectorAll(Vp));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(Gp);return e?.[2]||""}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,""),t=e.match(Gp);return t?!t[2]:""===e||"/"===e}isSharePage(){return window.location.pathname.startsWith("/s/")}getNewTabUrl(){const e=this.getAgentId();return e?`https://${jp}/chat/${e}`:`https://${jp}/`}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(Yp);return e?this.extractConversationTitle(e):null}getCurrentConversationInfo(){const e=super.getCurrentConversationInfo();if(!e)return null;const t=document.querySelector(Yp),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(Zp),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:Zp,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(Xp)||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(Xp),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:Sm}}catch(vT){return console.error(`[YuanbaoAdapter] deleteConversationOnSite error for "${e.id}":`,vT),{id:e.id,success:false,method:"none",reason:Cm}}}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 Jp}getChatContentSelectors(){return [em,tm]}getUserQuerySelector(){return em}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(tm),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Jp)||this.getScrollContainer()||document,o=Array.from(r.querySelectorAll(`${em}, ${tm}`)).filter(e=>!e.closest(".gh-root")),i=[];return o.forEach((r,a)=>{if(r.matches(em)){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(tm));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 [Kp]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/chat/"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:":root",property:ym,noCenter:true},{selector:":root",property:"--hunyuan-chat-list-width",value:`min(100%, var(${ym}))`,noCenter:true}]}async toggleTheme(e){try{return localStorage.setItem(Qp,e),window.dispatchEvent(new StorageEvent("storage",{key:Qp,newValue:e,storageArea:localStorage})),document.documentElement.style.colorScheme=e,!0}catch(vT){return console.error("[YuanbaoAdapter] toggleTheme error:",vT),false}}getModelName(){const e=document.querySelector(dm);return e?.textContent?.trim()||""||null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".ybc-model-select-button",dm],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(Gp);if(e?.[1])return e[1];const t=document.querySelector(`${Zp}[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://${jp}/chat/${t}/${e}`:`https://${jp}/`}extractConversationInfo(e,t){const n=e.closest(Zp)||(e.matches(Zp)?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(Xp);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,gm.slice(0,2));if(t)return t;if(e.matches(nm)&&!this.isThoughtElement(e))return e;const n=Array.from(e.querySelectorAll(nm));return n.find(e=>!this.isThoughtElement(e))||n[0]||null}extractYuanbaoExportMessages(e){const t=document.querySelector(Jp)||this.getScrollContainer()||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${em}, ${tm}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches(em)?"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([om,rm,lm].join(", ")).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove());const r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(hm).forEach(e=>e.remove());const o=this.findAssistantBodyRoot(n)||n,i=Ji(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(im).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractYuanbaoUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,am).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()||Ea(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:Aa(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}=Ia(t),i=this.extractYuanbaoDownloadableSource(e,{allowDataImage:false,includeImages:false});if(!n&&!i)return null;const a=n||Ea(i,{ignoreGenericDownload:true})||this.extractResourceIdFilename(i)||"attachment";return {kind:"file",name:a,source:i,type:r||Aa(a)||Ma(i),sizeLabel:o}}formatYuanbaoUserImageAttachments(e,t){return ja(e,t,{siteId:this.getSiteId()})}formatYuanbaoUserFileAttachments(e,t){return Ga(e,t,{siteId:this.getSiteId()})}extractYuanbaoAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,sm).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractYuanbaoImageSource(e),o=Ta(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 Wa(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)),cm.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=qa(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!Ra(n))return "";try{const e=new URL(n,window.location.href);if(e.hostname===jp&&/\/(?: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)||Aa(e)).find(Boolean)||""}findUserMessageScope(e){return e.matches(em)?e:e.closest(em)||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=Ta(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(`${om}, ${rm}`).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,gm);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(um)).filter(e=>!e.parentElement?.closest(um)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(`${rm}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const t=(Ji(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(hm)}findConversationRowById(e){const t=document.querySelector(`${Zp}[dt-cid="${e}"]`);if(t)return t;const n=Array.from(document.querySelectorAll(Zp));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(Xp),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(fm)),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(Xp))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(mm)||!!e.querySelector(mm)}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=>vm.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 xm.test(t)&&!wm.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(Kp));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 qs{exportIncludeThoughtsOverride=null;exportUserAttachmentsByMessageId=new Map;exportShareTitle=null;match(){return window.location.hostname===Tm}getSiteId(){return No}getName(){return "Z.ai"}getThemeColors(){return {primary:"#0881F0",secondary:"#0B6ED8"}}getTextareaSelectors(){return [...Mm]}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 [`${Im}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Im);return !e||e.hasAttribute("disabled")||null===e.offsetParent?null:e}getResponseContainerSelector(){return Rm}getConversationContentContainer(e){const t=document.querySelector(this.getResponseContainerSelector())||document.querySelector(qm);if(t)return t;const n=this.getScrollContainer();if(n)return n;return Boolean(document.body.querySelector(`${Pm}, ${Bm}`))&&(this.isSharePage()||e?.allowBodyFallback)||e?.allowBodyFallback?document.body:null}getChatContentSelectors(){return [Pm,Bm]}getUserQuerySelector(){return Pm}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:_m,assistantResponseSelector:Om,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(`[${$m}]`).forEach(e=>e.removeAttribute($m));}shouldSkipExportElement(e){return !!e.closest(".gh-root")||(!!e.closest(".gh-user-query-markdown")||!!e.closest(zm))}collectExportMessages(e){const t=Array.from(e.querySelectorAll(Pm)),n=this.collectTopLevelBlocks(t).filter(e=>!this.shouldSkipExportElement(e)),r=Array.from(e.querySelectorAll(Bm));return {users:n,assistants:this.collectTopLevelBlocks(r).filter(e=>!this.shouldSkipExportElement(e)&&!e.closest(Pm))}}markExportMessages(e){const{users:t,assistants:n}=this.collectExportMessages(e);t.forEach(e=>e.setAttribute($m,"user")),n.forEach(e=>e.setAttribute($m,"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))),Ji(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(zm)),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(zm).forEach(e=>e.remove());const i=this.findAssistantBodyRoot(t).cloneNode(true);i.querySelectorAll(Um).forEach(e=>e.remove());const a=(Ji(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(Dm)).filter(e=>!e.closest(Pm)&&!e.closest(zm)&&!e.closest(".gh-root"));return this.collectTopLevelBlocks(t)[0]||e}isAssistantBodyElement(e){return e.matches(Dm)&&!e.closest(Pm)&&!e.closest(zm)}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(Bm);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(`${zm}, .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(Bm);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(jm);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:jm,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(Gm)||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(jm);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(Nm),n=t?.textContent?.trim();return n||null}lockModel(e,t){this.isNewConversation()&&super.lockModel(e,t);}getModelSwitcherConfig(e){return this.isNewConversation()?{targetModelKeyword:e,selectorButtonSelectors:[...Nm],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(Qm,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",Vm[n]),window.dispatchEvent(new StorageEvent("storage",{key:Qm,newValue:e,storageArea:localStorage})),!0}catch(vT){return console.error("[ZaiAdapter] toggleTheme error:",vT),false}}getWidthSelectors(){return [{selector:`${qm} [class*="max-w-[1000px]"]`,property:"max-width"},{selector:`${qm} [class*="max-w-[960px]"]`,property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${qm} .chat-user [class*="max-w-[90%]"]`,property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["#sidebar"]}}extractConversationTitle(e){const t=e.querySelector(Gm);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(`${Pm}, ${Bm}`));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(Pm).length,i=e.querySelectorAll(Bm).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(zm)))}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(vT){console.warn("[ZaiAdapter] Failed to load export attachment metadata:",vT);}}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(Zm);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=qa(t?.cdn_url||e.url||"");return {kind:this.isZaiImageAttachment(r,o,i)?"image":"file",name:r,source:Ra(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(Pm)?e:e.closest(Pm);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 Hm){const t=this.normalizeZaiAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeZaiAttachmentSource(e){const t=qa(e);if(!t||!Ra(t))return "";try{const e=new URL(t,window.location.href);if(e.hostname===Tm&&/^\/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 ja(e,t,{siteId:this.getSiteId()})}formatZaiUserFileAttachments(e,t){return Ga(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(Pm)?e:e.closest(Pm))||e;for(const n of Fm){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(Km);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 Xm(){for(const e of Ym)if(e.match())return e;return null}const Jm=Object.freeze(Object.defineProperty({__proto__:null,SiteAdapter:qs,getAdapter:Xm},Symbol.toStringTag,{value:"Module"}));let ef=null;const tf=Vo()(Yo((e,t)=>(ef=()=>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}}),applyConversationChanges:({upserts:t,updates:n,deleteIds:r,lastUsedFolderId:o})=>e(e=>{let i=e.conversations,a=false;const s=Date.now(),l=()=>(i===e.conversations&&(i={...e.conversations}),i);r?.forEach(e=>{if(!i[e])return;delete l()[e],a=true;}),n?.forEach(({id:e,updates:t})=>{const n=i[e];if(!n)return;l()[e]={...n,...t,updatedAt:s},a=true;}),t?.forEach(e=>{l()[e.id]=e,a=true;});const c={};return a&&(c.conversations=i),o&&o!==e.lastUsedFolderId&&(c.lastUsedFolderId=o),Object.keys(c).length>0?c:e}),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:Ko(()=>Ti),partialize:e=>({conversations:e.conversations,lastUsedFolderId:e.lastUsedFolderId}),onRehydrateStorage:()=>()=>{ef?.();}})),nf=()=>tf.getState(),rf=Object.freeze(Object.defineProperty({__proto__:null,getConversationsStore:nf,useConversationsStore:tf},Symbol.toStringTag,{value:"Module"})),of=(e,t)=>{const n=(e||"").trim(),r=(t||"").trim();return r&&n.startsWith(r)?n.slice(r.length).trim():n},af=e=>({...e,name:of(e.name,e.icon)});let sf=null;const lf=Vo()(Yo((e,t)=>(sf=()=>e({_hasHydrated:true}),{folders:go,_hasHydrated:false,addFolder:(t,n)=>{const r={id:"folder_"+Date.now(),name:of(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:of(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:Ko(()=>Ti),partialize:e=>({folders:e.folders}),merge:(e,t)=>{const n=e;return n?.folders?{...t,...n,folders:(r=n.folders,r.map(af))}:t;var r;},onRehydrateStorage:()=>()=>{sf?.();}})),cf=()=>lf.getState(),df=Object.freeze(Object.defineProperty({__proto__:null,getFoldersStore:cf,useFoldersStore:lf},Symbol.toStringTag,{value:"Module"}));let uf=null;const hf=Vo()(Yo((e,t)=>(uf=()=>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:Ko(()=>Ti),partialize:e=>({tags:e.tags}),onRehydrateStorage:()=>()=>{uf?.();}})),gf=()=>hf.getState(),pf=Object.freeze(Object.defineProperty({__proto__:null,getTagsStore:gf,useTagsStore:hf},Symbol.toStringTag,{value:"Module"})),mf="⁣",ff="#ophel-quick-quote",bf="ophel-quick-quote:",yf=/\[\u2063\]\(#ophel-quick-quote\s+"ophel-quick-quote:([A-Za-z0-9_-]+)"\)/g,vf=/\[\u2063\]\((?:[^)\s"]*#ophel-quick-quote|#ophel-quick-quote)(?:\s+"ophel-quick-quote:[A-Za-z0-9_-]+")?\)/g,xf=/\[\u2063\]\($/,wf=/^(?:"ophel-quick-quote:[A-Za-z0-9_-]+")?\)/,Sf=[],Cf=new Map,kf=(e,t)=>{const n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t).trimEnd()},Tf=(e,t)=>{const n=(e||"").replace(/\s+/g," ").trim();return n?n.slice(0,t).trimEnd():void 0},Ef=(e,t)=>{const n=(e||"").replace(/\s+/g," ").trim();return n?n.slice(Math.max(0,n.length-t)).trimStart():void 0},Af=[{label:80,edge:60,context:40,rootSignature:60,rootSelector:true},{label:64,edge:48,context:32,rootSignature:40,rootSelector:true},{label:48,edge:36,context:24,rootSignature:0,rootSelector:true},{label:36,edge:28,context:16,rootSignature:0,rootSelector:false}],Mf=(e,t)=>{const n=e.anchor,r=(e=>{const t=e;return Object.keys(e).forEach(e=>{const n=t[e];void 0!==n&&""!==n&&null!==n||delete t[e];}),e})({n:n.selectedLength,h:n.selectedHash,p:Tf(n.selectedPrefix||n.textSignature||n.selectedText,t.edge),s:Ef(n.selectedSuffix||n.selectedText,t.edge),b:Ef(n.beforeText,t.context),f:Tf(n.afterText,t.context),r:t.rootSelector?n.rootSelector:void 0,x:n.rootIndex,g:t.rootSignature>0?Tf(n.rootTextSignature,t.rootSignature):void 0,o:n.selectionIndex});return {v:3,t:"q",i:e.id,l:kf(e.selectedText,t.label),a:r}},If=e=>(e=>{const t=(new TextEncoder).encode(e);let n="";return t.forEach(e=>{n+=String.fromCharCode(e);}),btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")})(JSON.stringify(e)),Lf=(e,t)=>"ref"===t?If((e=>({v:3,t:"r",i:e.id,l:kf(e.selectedText,48)}))(e)):(e=>{for(const t of Af){const n=If(Mf(e,t));if(n.length<=1600)return n}return If(Mf(e,Af[Af.length-1]))})(e),Nf=e=>{yf.lastIndex=0,vf.lastIndex=0;const t=e.replace(yf,"").replace(vf,"").replace(new RegExp(mf,"g"),"");return yf.lastIndex=0,vf.lastIndex=0,t},qf=e=>Nf(e).replace(/^[ \t]{0,3}>[ \t]?/gm,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_`~]/g,"").replace(/\s+/g," ").trim(),Rf=e=>{const t=[],n=new Set;let r;for(yf.lastIndex=0;r=yf.exec(e);){const e=Df(r[1]);e&&!n.has(`${e.kind}:${e.id}`)&&(n.add(`${e.kind}:${e.id}`),t.push(e));}return yf.lastIndex=0,t},Pf=e=>{const t={siteId:"",sessionId:"",selectedText:e.l,textSignature:e.a.p||e.l,selectedPrefix:e.a.p,selectedSuffix:e.a.s,selectedLength:e.a.n,selectedHash:e.a.h,beforeText:e.a.b,afterText:e.a.f,rootSelector:e.a.r,rootIndex:e.a.x,rootTextSignature:e.a.g,selectionIndex:e.a.o,createdAt:Date.now()};return {id:e.i,selectedText:e.l,quoteText:e.l.split("\n").map(e=>`> ${e}`).join("\n"),anchor:t,createdAt:Date.now()}},Df=e=>{if(!e||e.length>3200)return null;try{const t=JSON.parse((e=>{const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(4*Math.ceil(t.length/4),"="),r=atob(n),o=Uint8Array.from(r,e=>e.charCodeAt(0));return (new TextDecoder).decode(o)})(e));if(3!==t.v||"string"!=typeof t.i)return null;if("q"===t.t){const e=t;return "string"==typeof e.l&&e.a&&"object"==typeof e.a?{id:t.i,label:e.l,reference:Pf(e),kind:"full"}:null}if("r"===t.t){const e=t;return {id:t.i,label:"string"==typeof e.l?e.l:"",kind:"ref"}}return null}catch{return null}},Bf=(e=Date.now())=>{const t=e-72e5;for(let r=Sf.length-1;r>=0;r-=1)Sf[r].createdAt120;)Sf.shift();const n=new Set(Sf.map(e=>e.reference.id));Array.from(Cf.keys()).forEach(e=>{n.has(e)||Cf.delete(e);});},$f=(e,t,n={})=>{if(!t)return;const r=qf(e);if(!r)return;const o=Date.now();Bf(o),Cf.set(t.id,t);const i=Sf.find(e=>e.reference.id===t.id&&e.contentKey===r&&e.requireMarkerResidue===(n.requireMarkerResidue??true));if(i)return i.createdAt=o,i.reference=t,void(i.matchedScopeKey=void 0);Sf.push({contentKey:r,reference:t,createdAt:o,requireMarkerResidue:n.requireMarkerResidue??true});},_f=(e,t)=>{$f(e,t,{requireMarkerResidue:false});},Of=(e,t,n={})=>{const r=e.trim();if(!r||!t)return r;if($f(r,t),(e=>{yf.lastIndex=0;const t=yf.test(e);return yf.lastIndex=0,t})(r))return r;const o=Lf(t,n.kind||"full");return `${r}\n\n[${mf}](${ff} "${bf}${o}")`},zf=e=>Nf(e).replace(new RegExp(mf,"g"),"").replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim(),Ff=(e,t,n={})=>{const r=function(e){if(e.querySelector(`a[href*="${ff}"]`))return true;const t=e.textContent||"";yf.lastIndex=0,vf.lastIndex=0;const n=t.includes(mf)||yf.test(t)||vf.test(t);return yf.lastIndex=0,vf.lastIndex=0,n}(e);Bf();const o=qf(t||e.textContent||"");if(!o)return [];const i=[],a=[],s=[];Sf.forEach(e=>{if(e.requireMarkerResidue&&!r)return;if(!e.requireMarkerResidue){if(!n.markerlessScopeKey)return;if(!((e,t)=>{const{siteId:n,sessionId:r}=e.anchor;return !(t.currentSiteId&&n&&n!==t.currentSiteId||t.currentSessionId&&r&&r!==t.currentSessionId)})(e.reference,n))return;if(e.matchedScopeKey&&e.matchedScopeKey!==n.markerlessScopeKey)return;if(!e.matchedScopeKey&&false===n.allowMarkerlessMatch)return}const t=e.contentKey===o,i=!e.requireMarkerResidue&&(false!==n.allowMarkerlessMatch||e.matchedScopeKey===n.markerlessScopeKey),l=e.requireMarkerResidue?24:1,c=(r||i)&&Math.min(e.contentKey.length,o.length)>=l&&(e.contentKey.includes(o)||o.includes(e.contentKey));t?a.push(e):c&&s.push(e);});const l=a.at(-1)||s.at(-1);return l&&(l.requireMarkerResidue||!n.markerlessScopeKey||l.matchedScopeKey||(l.matchedScopeKey=n.markerlessScopeKey),i.push({id:l.reference.id,label:l.reference.selectedText,reference:l.reference,kind:"full"})),i},Uf=e=>e.title.startsWith(bf)?e.title.slice(18):null;const Hf=e=>{const t=zf(e);Rf(e).forEach(e=>{$f(t,Cf.get(e.id)||e.reference);});},Wf=e=>{e.querySelectorAll("a[href]").forEach(e=>{if((e=>!!Uf(e)||(e.getAttribute("href")||"").includes(ff))(e)){const t=e.previousSibling;t instanceof Text&&(t.data=t.data.replace(xf,""),t.data||t.remove());const n=e.nextSibling;n instanceof Text&&(n.data=n.data.replace(wf,""),n.data||n.remove()),e.remove();}});const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>e.parentElement?.closest(".gh-root, .gh-main-panel, .gh-quick-quote-chip-row, .gh-quick-quote-chip")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}),n=[];let r=t.nextNode();for(;r;)n.push(r),r=t.nextNode();n.forEach(e=>{const t=(n=e.data,Nf(n).replace(new RegExp(mf,"g"),""));var n;t!==e.data&&(e.data=t);});};class jf{siteAdapter;observerConfig=null;sidebarObserverStop=null;titleWatcher=null;pollInterval=null;geminiMigrationTimer=null;geminiMigrationRetryCount=0;initialAutoFullSyncPromise=null;syncUnpin=false;syncDelete=true;onChangeCallbacks=[];onExportProgressCallbacks=[];constructor(e){this.siteAdapter=e;}get folders(){return cf().folders}get conversations(){return nf().conversations}get lastUsedFolderId(){return nf().lastUsedFolderId}get tags(){return gf().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(Si||(Si=(async()=>{try{const e=await ti.storage.get(wi);if(void 0===e)return !1;const t="number"==typeof e?e:Number(e);return !Number.isFinite(t)||Date.now()-t<=1e4||(await ti.storage.remove(wi),!1)}catch(vT){return console.warn("[Ophel] Failed to consume restore flag:",vT),false}})(),Si));if(0===Object.keys(this.getAllConversations()).length&&this.siteAdapter.loadAllConversations&&!e)try{await this.runInitialAutoFullSync();}catch(vT){console.warn("[ConversationManager] Initial auto conversation sync failed:",vT);}this.startSidebarObserver();}tryMigrateGeminiLegacyCidToEmail(){if(this.siteAdapter.getSiteId()!==yo)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)};}),tf.setState({conversations:d}),this.notifyDataChange(),console.warn(`[ConversationManager] Gemini legacy cid migrated: ${l} -> ${r}, updated ${c.length} conversations.`),"migrated"}startGeminiMigrationRetry(){if(this.siteAdapter.getSiteId()!==yo)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===yo||(!e.siteId||e.siteId===yo)&&("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=[lf,hf,tf];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()-t{this.initialAutoFullSyncPromise=null;})),this.initialAutoFullSyncPromise}async autoFullSyncWithRetry(){let e=0,t=0;for(let n=0;n<4;n++){if(!(await this.waitForSidebarReady(0===n?1e4:5e3))){n<3&&await this.delay(2500);continue}const r=await this.autoFullSync();if(r.scannedCount>e?(e=r.scannedCount,t=0):r.loadSucceeded&&r.scannedCount>0&&0===r.changedCount&&t++,r.loadSucceeded&&r.scannedCount>0&&t>=2)break;n<3&&await this.delay(2500);}}async autoFullSync(){const e=await this.siteAdapter.loadAllConversations();if(await this.delay(400),false===e){const{newCount:e,updatedCount:t}=this.syncConversations(null,true),n=e+t;return n>0&&this.notifyDataChange(),{scannedCount:this.siteAdapter.getConversationList().length,changedCount:n,loadSucceeded:false}}let t=0,n=this.siteAdapter.getConversationList().length,r=0,o=0;for(let i=0;i<10;i++){if(i>0){const e=this.siteAdapter.getSidebarScrollContainer();if(!e)break;const t=e;t.scrollTop=t.scrollHeight,t.dispatchEvent(new Event("scroll",{bubbles:true})),await this.delay(400);}const{newCount:e,updatedCount:a}=this.syncConversations(null,true);r+=e,o+=a,(e>0||a>0)&&this.notifyDataChange(),await this.delay(300);const s=this.siteAdapter.getConversationList().length;if(e>0||s>n?(n=Math.max(n,s),t=0):t++,t>=2)break}return {scannedCount:this.siteAdapter.getConversationList().length,changedCount:r+o,loadSucceeded:true}}delay(e){return new Promise(t=>setTimeout(t,e))}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.sidebarObserverStop=Cs.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.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)nf().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&&(nf().updateConversation(e.id,r),this.notifyDataChange());}}startPolling(){this.pollInterval||(this.pollInterval=setInterval(()=>{if(!this.observerConfig)return;const e=this.observerConfig,t=Cs.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&&(nf().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=Cs.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&&(nf().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 cf().addFolder(e,t)}updateFolder(e,t){cf().updateFolder(e,t);}deleteFolder(e){"inbox"!==e&&(nf().moveConversationsToInbox(e),cf().deleteFolder(e));}moveFolder(e,t){cf().moveFolder(e,t);}reorderFolders(e){cf().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(vT){console.error(`[ConversationManager] deleteConversationsOnSite failed on ${this.siteAdapter.getName()}:`,vT);const t=vT instanceof Error&&vT.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&&(nf().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){nf().moveToFolder(e,t);}setLastUsedFolder(e){nf().setLastUsedFolderId(e);}getTags(){return this.tags}createTag(e,t){return gf().addTag(e,t)}updateTag(e,t,n){return gf().updateTag(e,t,n)}deleteTag(e){gf().deleteTag(e),nf().removeTagFromAll(e);}setConversationTags(e,t){nf().setConversationTags(e,t);}togglePin(e){return nf().togglePin(e)}renameConversation(e,t){t&&nf().updateConversation(e,{title:t});}updateConversation(e,t){nf().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=nf(),u=new Set(r.map(e=>e.id)),h=[],g=[],p=[];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&&(g.push({id:t,updates:r}),a++);}else h.push({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)||(p.push(n),s++));});}return d.applyConversationChanges({upserts:h,updates:g,deleteIds:p,lastUsedFolderId:e||void 0}),{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=Cs.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=zi.getState().settings,r={privacyTitle:n.tab?.privacyTitle||"Google",siteName:this.siteAdapter.getName(),titleFormat:n.tab?.titleFormat};let o=rs(e,r);const i=rs(t.managedTitleReference,r);if(i){const t=rs(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()}sanitizeExportFilename(e,t){return e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g," ").trim()||t}buildExportTimestampSuffix(e){if(!e)return "";const t=new Date;return `_${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`}createExportMetadataForConversation(e){const t=zi.getState().settings,n=le("untitledConversation"),r=this.sanitizeConversationTitleForUse(e.title)||n,o=this.siteAdapter.getName();return {title:r,safeTitle:this.sanitizeExportFilename(r,n).substring(0,50),filenamePrefix:`${this.sanitizeExportFilename(o,o)} - `,timestampSuffix:this.buildExportTimestampSuffix(t.export?.exportFilenameTimestamp),metadata:xa(r,o,e.id,{customUserName:t.export?.customUserName,customModelName:t.export?.customModelName})}}normalizeExportSegmentText(e,t){const n=e.replace(/\r\n?/g,"\n").replace(/```[\s\S]*?```/g," ").replace(/~~~[\s\S]*?~~~/g," ").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/(^|\n)\s*>+\s?/g,"$1").replace(/[`*_~]/g,"").replace(/\s+/g," ").trim();return !t||n.length<=t?n:`${n.slice(0,t).trim()}...`}normalizeExportSegmentTitle(e){return e.replace(/\r\n?/g,"\n").replace(/```[^\n]*\n?([\s\S]*?)```/g," $1 ").replace(/~~~[^\n]*\n?([\s\S]*?)~~~/g," $1 ").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/(^|\n)\s*>+\s?/g,"$1").replace(/[`*_~]/g,"").replace(/\s+/g," ").trim()}countExportSegmentCharacters(e){return e.reduce((e,t)=>e+this.normalizeExportSegmentText(t.content).length,0)}createFallbackSegmentTitle(e,t){return t||1!==e?le("segmentedExportUntitledSegment").replace("{index}",String(e)):le("segmentedExportOpeningSegment")}createConversationExportSegments(e){const t=[];let n=[];const r=()=>{if(0===n.length)return;const e=t.length+1,r=n.filter(e=>"user"===e.role.toLowerCase()),o=n.filter(e=>"user"!==e.role.toLowerCase()),i=r[0]?.content||n[0]?.content||"",a=this.normalizeExportSegmentText(i,80)||this.createFallbackSegmentTitle(e,r.length>0),s=this.normalizeExportSegmentTitle(i)||this.createFallbackSegmentTitle(e,r.length>0),l=this.normalizeExportSegmentText(n.map(e=>e.content).join(" "),180)||a;t.push({id:`segment-${e}`,index:e,title:a,exportTitle:s,preview:l,messages:n,userMessageCount:r.length,assistantMessageCount:o.length,characterCount:this.countExportSegmentCharacters(n)}),n=[];};return e.forEach(e=>{"user"===e.role.toLowerCase()&&r(),n.push(e);}),r(),t}getSelectedExportSegments(e,t){const n=new Set(t);return e.segments.filter(e=>n.has(e.id))}createSegmentMetadata(e,t){return {...e.metadata,title:`${e.title} - ${t.index}. ${t.exportTitle}`}}getSegmentReplyMessages(e){const t=e.messages.filter(e=>"user"!==e.role.toLowerCase());return t.length>0?t:e.messages}formatSegmentBody(e){return this.getSegmentReplyMessages(e).map(e=>e.content.trim()).filter(Boolean).join("\n\n").trim()}formatSingleSegmentMarkdown(e,t){const n=[ta(this.createSegmentMetadata(e,t),[]).trimEnd(),"",`## ${t.index}. ${t.exportTitle}`],r=this.formatSegmentBody(t);return r&&n.push("",r),`${n.join("\n").trimEnd()}\n`}formatSegmentedMarkdown(e,t){const n=[ta(e.metadata,[]).trimEnd()];return t.forEach(e=>{n.push("",`## ${e.index}. ${e.exportTitle}`);const t=this.formatSegmentBody(e);t&&n.push("",t);}),`${n.join("\n").trimEnd()}\n`}createSegmentFilename(e){const t=String(e.index).padStart(3,"0");return `${t} - ${this.sanitizeExportFilename(e.title,`segment-${t}`).substring(0,70)}.md`}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){nf().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()||(nf().addConversation(l),this.notifyDataChange()),l}async withConversationExportData(e,t,n,r="export",o={}){if(this.siteAdapter.getSessionId()!==e)return Gi(le("exportNeedOpenFirst")),null;const i=this.resolveConversationForExport(e);if(!i)return console.error("[ConversationManager] Conversation not found:",e),null;const a=this.siteAdapter.getScrollContainer?.()||null,s=a?.scrollTop??null,l=window.scrollY,c=zi.getState().settings,d=o.packaging??("zip"===c.export?.packaging?"zip":"markdown"),u={conversationId:e,format:t,includeThoughts:c.export?.includeThoughts??true,packaging:d};let h=false,g=null;const p=n=>{this.notifyExportProgress({conversationId:e,format:t,stage:n,operation:r});};try{if(p("loading-history"),a){let e=0,t=0;const n=50;for(;tsetTimeout(e,500));const n=a.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}p("preparing"),h=!0,g=await this.siteAdapter.prepareConversationExport(u),p("extracting");const e="markdown"===t&&"zip"===d?await this.siteAdapter.extractExportBundle(u):null,r=e?.messages||await this.extractConversationMessages(u),o=this.stripQuickQuoteMarkersFromExportMessages(r);return 0===o.length?(console.error("[ConversationManager] No messages found"),null):await n({conv:i,messages:o,exportBundle:e,exportPackaging:d,notifyProgress:p})}catch(vT){return console.error("[ConversationManager] Export failed:",vT),null}finally{if(p("restoring"),h)try{await this.siteAdapter.restoreConversationAfterExport(u,g);}catch(m){console.warn("[ConversationManager] Export state restore failed:",m);}a&&null!==s?a.scrollTop=s:window.scrollTo({top:l,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"):(Gi(le("exportNeedOpenFirst")),null)}async prepareSegmentedConversationExport(e){return this.withConversationExportData(e,"markdown",({conv:e,messages:t})=>{const n=this.createConversationExportSegments(t);if(0===n.length)return null;const r=this.createExportMetadataForConversation(e);return {conversationId:e.id,...r,totalMessages:t.length,segments:n}},"segment-export",{packaging:"markdown"})}async exportSegmentedConversation(e,t,n){const r=this.getSelectedExportSegments(e,t);if(0===r.length)return Gi(le("segmentedExportNoSelection")),false;try{if("clipboard"===n){const t=this.formatSegmentedMarkdown(e,r);return await navigator.clipboard.writeText(t),Gi(le("copySuccess")),!0}if("merged-markdown"===n){const t=`${e.filenamePrefix}${e.safeTitle}${e.timestampSuffix} - segments.md`,n=await ba(this.formatSegmentedMarkdown(e,r),t,"text/markdown;charset=utf-8");return n&&Gi(le("exportSuccess")),n}const t=r.map(t=>({path:this.createSegmentFilename(t),data:this.formatSingleSegmentMarkdown(e,t),mimeType:"text/markdown;charset=utf-8"}));t.push({path:"manifest.json",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},totalMessages:e.totalMessages,segments:r.map(e=>({id:e.id,index:e.index,title:e.title,file:this.createSegmentFilename(e),userMessageCount:e.userMessageCount,assistantMessageCount:e.assistantMessageCount,characterCount:e.characterCount}))},null,2),mimeType:"application/json;charset=utf-8"});const o=`${e.filenamePrefix}${e.safeTitle}${e.timestampSuffix} - segments.zip`,i=await async function(e,t){try{const n=await fa(e);return await ya(n,t)}catch(vT){return console.error("[Exporter] ZIP download failed:",vT),Gi(le("exportFailed")),!1}}(t,o);return i&&Gi(le("exportSuccess")),i}catch(vT){return console.error("[ConversationManager] Segmented export failed:",vT),Gi(le("exportFailed")),false}}async exportConversation(e,t){return true===await this.withConversationExportData(e,t,async({conv:e,messages:n,exportBundle:r,exportPackaging:o,notifyProgress:i})=>{const a=zi.getState().settings,s=le("untitledConversation"),l=this.sanitizeConversationTitleForUse(e.title)||s,c=l.replace(/[<>:"/\\|?*]/g,"_").substring(0,50),d=xa(l,this.siteAdapter.getName(),e.id,{customUserName:a.export?.customUserName,customModelName:a.export?.customModelName});let u,h,g,p="";if(a.export?.exportFilenameTimestamp){const e=new Date;p=`_${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 m=`${this.siteAdapter.getName().replace(/[<>:"/\\|?*]/g,"_")} - `;if("clipboard"===t)return i("copying"),u=ta(d,n),await navigator.clipboard.writeText(u),Gi(le("copySuccess")),true;if("markdown"===t){u=ta(d,n),h=`${m}${c}${p}.md`,g="text/markdown;charset=utf-8";if("zip"===o){i("packaging");return !!(await async function(e){const t=new Set,n=ua(da(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=ha(i.relativePath||ga(i),t);try{const t=await pa(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(vT){console.warn("[Exporter] Failed to include export asset:",i.name,vT),o.push({name:i.name,path:e,kind:i.kind,mimeType:i.mimeType,sourceUrl:i.sourceUrl,description:i.description,included:false,error:ma(vT)});}}r.push({path:ua("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 fa(r);return await ya(t,e.packageFilename)}catch(vT){return console.error("[Exporter] Package download failed:",vT),Gi(le("exportFailed")),false}}({markdownFilename:h,markdownContent:u,assets:this.normalizeExportAssets(r),packageFilename:`${m}${c}${p}.zip`,metadata:d}))&&(Gi(le("exportSuccess")),true)}}else "json"===t?(u=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),h=`${m}${c}${p}.json`,g="application/json;charset=utf-8"):(u=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),h=`${m}${c}${p}.txt`,g="text/plain;charset=utf-8");i("downloading");return !!(await ba(u,h,g))&&(Gi(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=Cs.query(a,{all:true,shadow:s})||[];if(e.length>0){const t=(e,t)=>{const n=[];e.matches?.(t)&&n.push(e);return (Cs.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=qs.prototype.extractAssistantResponseText;let i="";r&&r!==o&&(i=r.call(this.siteAdapter,t)),i||(i=Ji(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=Cs.query(o,{all:true,shadow:s})||[],c=Cs.query(i,{all:true,shadow:s})||[],d=Math.max(l.length,c.length);for(let u=0;u({...e,content:zf(e.content)}))}normalizeExportAssets(e){return e?.assets?e.assets.filter(e=>!!e.name?.trim()&&(void 0!==e.content||Boolean(e.sourceUrl))):[]}}const Gf={getItem:async e=>{const t=await Ti.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 Ti.setItem("bookmarks",JSON.stringify(r));},removeItem:async e=>{await Ti.removeItem("bookmarks");}},Qf=Vo()(Yo((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:Ko(()=>Gf)})),Vf="gh-inline-bookmark",Kf="gh-inline-bookmark--bookmarked",Zf="h1, h2, h3, h4, h5, h6",Yf="gh-inline-bookmark-global-styles",Xf="gh-inline-bookmark-scoped-styles";class Jf{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({includeAdapterScan:false});}),this.unsubscribeBookmarks=Qf.subscribe(()=>{this.updateAllIconStates();}),this.startDomObserver(),this.injectBookmarkIcons();}injectGlobalStyles(){if(document.getElementById(Yf))return;const e=document.createElement("style");e.id=Yf,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(Xf))return void this.injectedRoots.add(e)}else if(e.querySelector(`#${Xf}`))return void this.injectedRoots.add(e);const t=document.createElement("style");t.id=Xf,t.textContent=`\n .${Vf} {\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 .${Vf}:hover {\n opacity: 1 !important;\n transform: translateY(-50%) scale(1.1);\n }\n\n .${Vf}.${Kf} {\n opacity: 1 !important;\n }\n\n /* Parent Hover Effect */\n .gh-has-inline-bookmark:hover .${Vf}:not(.${Kf}) {\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(e={}){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const t=this.getInlineBookmarkItems(e.includeAdapterScan??true),n=Qf.getState();for(let r=0;r{t.stopPropagation(),t.preventDefault(),this.handleBookmarkClick(e,o,l,u);}),i.insertBefore(u,i.firstChild),this.injectedSignatures.set(i,l);}}startDomObserver(){const e=this.adapter.getObserveTarget()??document.body;e&&(this.observer=new MutationObserver(e=>{this.hasRelevantMutation(e)&&this.scheduleInjectBookmarkIcons({includeAdapterScan:true});}),this.observer.observe(e,{childList:true,subtree:true}));}scheduleInjectBookmarkIcons(e){"hidden"!==this.displayMode&&(this.injectDebounceTimer&&clearTimeout(this.injectDebounceTimer),this.injectDebounceTimer=setTimeout(()=>{this.injectDebounceTimer=null,this.injectBookmarkIcons({includeAdapterScan:e.includeAdapterScan});},120));}hasRelevantMutation(e){const t=this.getInlineBookmarkTargetSelector(),n=this.getInlineBookmarkContentChangeSelector();return e.some(e=>{if(this.nodeIsInsideInlineBookmarkContent(e.target,n))return true;for(const r of e.addedNodes)if(this.nodeMatchesInlineBookmarkTarget(r,t)||this.nodeIsInsideInlineBookmarkContent(r,n))return true;return false})}getInlineBookmarkTargetSelector(){const e=[Zf,this.adapter.getUserQuerySelector(),...this.adapter.getChatContentSelectors()].filter(e=>Boolean(e?.trim()));return Array.from(new Set(e)).join(", ")}getInlineBookmarkContentChangeSelector(){const e=[Zf,this.adapter.getUserQuerySelector()].filter(e=>Boolean(e?.trim()));return Array.from(new Set(e)).join(", ")}nodeMatchesInlineBookmarkTarget(e,t){if(!(e instanceof Element))return false;try{return e.matches(t)||null!==e.querySelector(t)}catch{return e.matches(Zf)||null!==e.querySelector(Zf)}}nodeIsInsideInlineBookmarkContent(e,t){const n=e instanceof Element?e:e.parentElement;if(!n)return false;try{return n.matches(t)||null!==n.closest(t)}catch{return n.matches(Zf)||null!==n.closest(Zf)}}getInlineBookmarkItems(e){const t=[],n=new Set,r=(e,r)=>{e.forEach(e=>{const o=e.element;o&&!n.has(o)&&(n.add(o),t.push({item:e,sourceId:r}));});};return e&&r(this.adapter.getInlineBookmarkItems(),"conversation"),r(this.outlineManager.getFlatItems(),this.outlineManager.getActiveSourceId()),t}createStarSvgElement(e){const t=kd("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=kd("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,r){const o=Qf.getState(),i=this.outlineManager.getBookmarkSessionId(t),a=this.adapter.getSiteId(),s=this.adapter.getCurrentCid()||"",l=this.adapter.getOutlineScrollContainer(t),c=e.element.offsetTop+(l?.scrollTop||0);o.toggleBookmark(i,a,s,e,n,c);}updateAllIconStates(){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const e=Qf.getState();Cs.query(`.${Vf}`,{all:true,shadow:true}).forEach(t=>{const n=t,r=n.dataset.signature,o=n.dataset.sourceId||"conversation";if(!r)return;const i=this.outlineManager.getBookmarkSessionId(o),a=null!==e.getBookmarkId(i,r);a!==n.classList.contains(Kf)&&(a?(n.classList.add(Kf),n.replaceChildren(this.createStarSvgElement(true))):(n.classList.remove(Kf),n.replaceChildren(this.createStarSvgElement(false))));});}removeInjectedIcons(){Cs.query(`.${Vf}`,{all:true,shadow:true}).forEach(e=>e.remove());Cs.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(Yf)?.remove(),document.getElementById(Xf)?.remove();Cs.query(`#${Xf}`,{all:true,shadow:true}).forEach(e=>e.remove());Cs.query(`.${Vf}`,{all:true,shadow:true}).forEach(e=>e.remove());Cs.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),Jf.cleanupInjectedArtifacts(),this.injectedSignatures=new WeakMap,this.injectedRoots=new WeakSet;}}class eb{siteAdapter;settings;tree=[];flatItems=[];flatNodes=[];scrollNodes=[];scrollPositions=[];scrollHeights=[];scrollPositionsStale=true;sources=[];activeSourceId="conversation";minLevel=1;treeKey="";listeners=[];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;activeConsumers=new Set;isRefreshing=false;refreshDebounceTimer=null;REFRESH_DEBOUNCE_MS=300;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)),Qf.subscribe(()=>{this.isActive&&this.refresh();});}setActive(e){this.setActiveConsumer("outlineTab",e);}setGlobalSearchActive(e){this.setActiveConsumer("globalSearch",e);}setActiveConsumer(e,t){const n=this.isActive,r=this.activeConsumers.has(e);t?this.activeConsumers.add(e):this.activeConsumers.delete(e),this.isActive=this.activeConsumers.size>0,this.updateAutoUpdateState();const o=!n||"outlineTab"===e&&t&&!r;this.isActive&&o&&(this.pendingPostGenerationRefresh&&(this.pendingPostGenerationRefresh=false,this.treeKey=""),this.refresh());}updateAutoUpdateState(){const e=this.shouldEnableAutoUpdate();e&&!this.isAutoUpdating?this.startAutoUpdate():!e&&this.isAutoUpdating&&this.stopAutoUpdate();const t=this.shouldEnablePeriodicOutlineRefreshFallback();t&&!this.periodicOutlineRefreshTimer?this.startPeriodicOutlineRefreshFallback():!t&&this.periodicOutlineRefreshTimer&&this.stopPeriodicOutlineRefreshFallback();const n=this.settings.enabled&&this.isActive&&this.siteAdapter.supportsDynamicOutlineSources();n&&!this.sourceObserver?this.startSourceObserver():!n&&this.sourceObserver&&this.stopSourceObserver();}updateSettings(e){const t=this.settings.updateInterval!==e.updateInterval;this.settings=e,t&&this.periodicOutlineRefreshTimer&&this.stopPeriodicOutlineRefreshFallback(),void 0!==e.expandLevel&&(this.expandLevel=e.expandLevel),this.refresh(),this.updateAutoUpdateState();}observer=null;updateDebounceTimer=null;periodicOutlineRefreshTimer=null;sourceObserver=null;sourceRefreshTimer=null;outlineSourcesSignature="";routeChangeVersion=0;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());}shouldEnableAutoUpdate(){return this.settings.enabled&&this.settings.autoUpdate&&this.isActive}shouldEnablePeriodicOutlineRefreshFallback(){return this.shouldEnableAutoUpdate()&&"conversation"===this.activeSourceId&&this.siteAdapter.usesPeriodicOutlineRefreshFallback()}getOutlineUpdateIntervalMs(){return 1e3*(this.settings.updateInterval||2)}startAutoUpdate(){if(this.observer||!this.shouldEnableAutoUpdate())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:false});}stopAutoUpdate(){this.observer&&(this.observer.disconnect(),this.observer=null),this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null),this.isAutoUpdating=false;}startPeriodicOutlineRefreshFallback(){!this.periodicOutlineRefreshTimer&&this.shouldEnablePeriodicOutlineRefreshFallback()&&(this.periodicOutlineRefreshTimer=setInterval(()=>{this.shouldEnablePeriodicOutlineRefreshFallback()&&this.refresh();},this.getOutlineUpdateIntervalMs()));}stopPeriodicOutlineRefreshFallback(){this.periodicOutlineRefreshTimer&&(clearInterval(this.periodicOutlineRefreshTimer),this.periodicOutlineRefreshTimer=null);}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(void 0,true),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>=eb.FALLBACK_DELAY-100&&this.treeKey===e&&(this.treeKey="",this.refresh());},eb.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(e=this.activeSourceId){const t=this.siteAdapter.getSessionId();return "conversation"===e?t:`${t}::${e}`}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.updateAutoUpdateState(),this.refresh(),this.notify());}getSignature(e,t=this.activeSourceId){return this.generateSignature(e,t)}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,t=this.activeSourceId){if(e.id)return "conversation"===t?e.id:`${t}:${e.id}`;let n="";if(e.context)n=e.context;else try{e.element?.nextElementSibling&&(n=(e.element.nextElementSibling.textContent||"").trim().substring(0,50));}catch{}const r=`${e.text}::${n}`;return "conversation"===t?r:`${t}:${r}`}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=Qf.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,t=false){if(this.settings.enabled&&!this.isRefreshing)if(t){this.refreshDebounceTimer&&(clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=null),this.isRefreshing=true;try{this._doRefresh(e);}finally{this.isRefreshing=false;}}else this.refreshDebounceTimer&&clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=setTimeout(()=>{if(this.refreshDebounceTimer=null,this.settings.enabled&&!this.isRefreshing){this.isRefreshing=true;try{this._doRefresh(e);}finally{this.isRefreshing=false;}}},this.REFRESH_DEBOUNCE_MS);}handleUrlChange(){const e=++this.routeChangeVersion;this.refreshDebounceTimer&&(clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=null),this.isAutoUpdating&&this.stopAutoUpdate(),this.stopPeriodicOutlineRefreshFallback(),this.tree=[],this.flatItems=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.treeKey="",this.levelCounts={},this.notify();const t=[80,250,600,1200];t.forEach((n,r)=>{setTimeout(()=>{e===this.routeChangeVersion&&(this.refresh(void 0,true),r===t.length-1&&this.updateAutoUpdateState());},n);});}_doRefresh(e){const t=this.updateSources(),n=zi.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=Qf.getState().getBookmarksBySession(i);if(this.ghostBookmarkIds=new Set,a.length>0){const e=new Map(a.map(e=>[e.id,e])),t=new Map;a.forEach(e=>{let n=t.get(e.signature);n||(n=new Map,t.set(e.signature,n)),n.has(e.title)||n.set(e.title,e);});const n=new Set(a.map(e=>e.id));o.forEach(e=>{const r=this.generateSignature(e),o=t.get(r)?.get(e.text);o&&(e.isBookmarked=true,e.bookmarkId=o.id,n.delete(o.id));});const r={},i={};n.forEach(t=>{const n=e.get(t);n&&(r[n.title]||(r[n.title]=[]),r[n.title].push(n.id));}),o.forEach(e=>{e.isBookmarked||(i[e.text]||(i[e.text]=[]),i[e.text].push(e));});const s=Qf.getState();Object.keys(r).forEach(e=>{const t=r[e],o=i[e];if(t&&o&&1===t.length&&1===o.length){const e=t[0],r=o[0],i=this.generateSignature(r);s.updateBookmark(e,{signature:i}),r.isBookmarked=true,r.bookmarkId=e,n.delete(e);}}),this.ghostBookmarkIds=new Set(n);const l=[];if(n.forEach(t=>{const n=e.get(t);if(n){if(0===n.level&&!this.settings.showUserQueries)return;l.push({level:n.level,text:n.title,element:null,isUserQuery:0===n.level,isBookmarked:true,isGhost:true,bookmarkId:n.id,scrollTop:n.scrollTop});}}),l.length>0){const e=e=>e.isGhost?e.scrollTop:e.element instanceof HTMLElement?e.element.offsetTop:0;o=[...o,...l].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){const e=this.syncFlatNodeRuntimeData(o);return 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=this.isDocumentScrollContainer(e),n=t?null:e.getBoundingClientRect(),r=n?.top??0,o=e.ownerDocument,i=t?e.scrollTop||o.documentElement.scrollTop||o.body.scrollTop||o.defaultView?.scrollY||0:e.scrollTop,a=[],s=new WeakMap;let l=0;const c=e=>{const t=e.scrollTop;if("number"!=typeof t||Number.isNaN(t))return false;const n="number"!=typeof e.scrollHeight||Number.isNaN(e.scrollHeight)?0:e.scrollHeight;return a.push({node:e,top:t,height:n,order:l}),l+=1,true};if(this.flatNodes.forEach(e=>{if(e.isGhost)return;let t=e.element;if(t&&t.isConnected||("conversation"===this.activeSourceId&&(t=e.isUserQuery&&0===e.level&&void 0!==e.queryIndex?this.findUserQueryElement(e.queryIndex,e.text):this.findElementByHeading(e.level,e.text)),t&&(e.element=t)),!t||!t.isConnected)return void c(e);const n=(e=>{const t=s.get(e);if(void 0!==t)return t;const n=e.getClientRects();if(0===n.length)return s.set(e,null),null;let o=n[0].top,a=n[0].bottom;for(let r=1;re.top===t.top?e.order-t.order:e.top-t.top),a.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 Gi(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){return this.findVisibleItemNode(e,t)?.index??null}findVisibleItemNode(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]:s+1{const n=e.navigationId||e.id||"";return n===t||n.startsWith(t)});if(e&&!e.isGhost)return e}const n=this.getScrollViewportRect(e);if(!n)return null;const r=this.getViewportScrollTop(e,n);if(null===r)return null;this.scrollPositionsStale&&this.updateScrollPositions();const o=n.top+Math.min(Math.max(.25*n.height,48),160),i=r+(o-n.top),a=this.findLatestCachedUserQueryBefore(i),s=this.collectActiveCandidateNodes(i,r,n.height,a),l=[],c=[],d=e=>{if(e.isGhost)return null;const t=e.element;if(t?.isConnected){const o=(e=>{const t=e.getClientRects();if(0===t.length)return null;let n=t[0].top,r=t[0].bottom;for(let o=1;oo&&((!g||f.top>g.top)&&(g=f),h=f),f.top<=o&&(!h||f.top>h.top)&&(h=f);}if(g)return g.node;let p=null,m=null;for(const f of l){const e=f.top+f.height;f.top<=o?(!p||f.top>p.top)&&(p=f):f.topn.top&&(!m||f.top{e&&!e.isGhost&&o.add(e);},a=(e,t)=>{if(e<0)return;const n=Math.max(0,e-t),r=Math.min(this.scrollNodes.length-1,e+t);for(let o=n;o<=r;o+=1)i(this.scrollNodes[o]);};return a(this.findScrollNodeIndexAtOrBefore(e),12),a(this.findScrollNodeIndexAtOrBefore(t),6),a(this.findScrollNodeIndexAtOrBefore(t+n),6),r&&(i(r),i(this.findFirstHeadingInUserQuerySection(r))),Array.from(o)}findScrollNodeIndexAtOrBefore(e){let t=0,n=this.scrollPositions.length-1,r=-1;for(;t<=n;){const o=t+n>>1;this.scrollPositions[o]<=e?(r=o,t=o+1):n=o-1;}return r}findLatestCachedUserQueryBefore(e){for(let t=this.findScrollNodeIndexAtOrBefore(e);t>=0;t-=1){const e=this.scrollNodes[t];if(e?.isUserQuery)return e}return null}findFirstHeadingInUserQuerySection(e){const t=[...e.children];for(;t.length>0;){const e=t.shift();if(e){if(!e.isGhost&&!e.isUserQuery)return e;t.unshift(...e.children);}}return null}findCachedActiveNode(e,t){if(!this.shouldKeepPreviousVisibleItem())return null;if(this.scrollPositionsStale)return null;const n=this.getViewportScrollTop(e,t);if(null===n)return null;const r=this.findVisibleItemNode(n,t.height);return !r||r.isUserQuery?null:r}getViewportScrollTop(e,t){if(this.isDocumentScrollContainer(e)){const t=e.ownerDocument;return e.scrollTop||t.documentElement.scrollTop||t.body.scrollTop||t.defaultView?.scrollY||0}const n=e.getBoundingClientRect(),r=Math.max(0,t.top-n.top);return e.scrollTop+r}isDocumentScrollContainer(e){const t=e.ownerDocument;return e===t.scrollingElement||e===t.documentElement||e===t.body}getScrollViewportRect(e){const t=e.ownerDocument.defaultView??window;if(this.isDocumentScrollContainer(e)){const e=t.innerWidth,n=t.innerHeight;return e<=2||n<=2?null:{left:0,top:0,right:e,bottom:n,width:e,height:n}}const n=e.getBoundingClientRect(),r=Math.max(0,n.left),o=Math.max(0,n.top),i=Math.min(t.innerWidth,n.right),a=Math.min(t.innerHeight,n.bottom),s=i-r,l=a-o;return s<=2||l<=2?null:{left:r,top:o,right:i,bottom:a,width:s,height:l}}shouldKeepPreviousVisibleItem(){const e=this.siteAdapter.getSiteId();return e===Eo||e===No}}let tb=null;const nb=Vo()(Yo((e,t)=>(tb=()=>e({_hasHydrated:true}),{prompts:co(),_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:Ko(()=>Ti),partialize:e=>({prompts:e.prompts}),onRehydrateStorage:()=>()=>{tb?.();}})),rb=()=>nb.getState().prompts,ob=()=>nb.getState(),ib=()=>{const e=rb(),t=new Set;return e.forEach(e=>{e.category&&t.add(e.category);}),Array.from(t)},ab=(e="",t=Ro)=>{let n=rb();if(t!==Ro&&t!==Po&&(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},sb=Object.freeze(Object.defineProperty({__proto__:null,filterPrompts:ab,getCategories:ib,getPromptsState:rb,getPromptsStore:ob,usePromptsStore:nb},Symbol.toStringTag,{value:"Module"}));function lb(){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 cb="ophel:aistudio-submit-shortcut-synced";class db{adapter;constructor(e){this.adapter=e;}async init(){nb.getState()._hasHydrated||await new Promise(e=>{const t=nb.subscribe(n=>{n._hasHydrated&&(t(),e());});});}getPrompts(){return ob().prompts}addPrompt(e){return ob().addPrompt(e)}updatePrompt(e,t){ob().updatePrompt(e,t);}deletePrompt(e){ob().deletePrompt(e);}getCategories(){return ib()}renameCategory(e,t){ob().renameCategory(e,t);}deleteCategory(e,t="未分类"){ob().deleteCategory(e,t);}updateOrder(e){ob().updateOrder(e);}filterPrompts(e="",t=Ro){return ab(e,t)}togglePin(e){ob().togglePin(e);}updateLastUsed(e){ob().updateLastUsed(e);}setPrompts(e){ob().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 Hf(e),true}return false}getEditorContent(e){return e?e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement?e.value||"":e.textContent||"":""}getCurrentEditorContent(){const e=this.adapter.getTextareaElement()||this.adapter.findTextarea();return this.getEditorContent(e)}hasEditorContent(){return this.getCurrentEditorContent().replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim().length>0}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=Cs.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()===Co&&lb()?"ctrlEnter":e}syncAiStudioSubmitShortcut(e="enter"){if(this.adapter.getSiteId()!==Co)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(cb,{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={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,ctrlKey:"Ctrl+Enter"===this.resolveSubmitKeyConfig(t).key,metaKey:false,shiftKey:false};return e.dispatchEvent(new KeyboardEvent("keydown",n)),e.dispatchEvent(new KeyboardEvent("keypress",n)),e.dispatchEvent(new KeyboardEvent("keyup",n)),true}dispatchNativeSubmitByKeyboard(e){return this.dispatchSubmitByKeyboard(e)}submitCurrentInputImmediately(e){this.syncAiStudioSubmitShortcut(e??"enter");const t=this.adapter.getSubmitButtonSelectors(),n=this.adapter.getTextareaElement()||this.adapter.findTextarea(),r=this.findBestSubmitButton(t,n);if(r&&!this.isElementDisabled(r))return r.click(),true;const o=this.getEditorContent(n).replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();return !(!n||!o)&&this.dispatchNativeSubmitByKeyboard(n)}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 e=n||this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!e)return false;i=this.dispatchNativeSubmitByKeyboard(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.dispatchNativeSubmitByKeyboard(d)&&(c=await this.waitForSubmitConfirmation(r,t,{button:this.findBestSubmitButton(t,d),clicked:false,wasDisabled:false}),c)}}const ub=(e,t)=>({id:`q_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,content:e,createdAt:Date.now(),status:"pending",type:"prompt",metadata:t}),hb=e=>{const t=("string"==typeof e?e:e.content).trim();return t?{content:t,metadata:"string"==typeof e?void 0:e.metadata}:null},gb=Vo()((e,t)=>({items:[],isProcessing:false,isPaused:false,enqueue:(t,n)=>{const r=ub(t.trim(),n);return e(e=>({items:[...e.items,r]})),r},enqueueMany:t=>{const n=t.map(hb).filter(e=>null!==e).map(e=>ub(e.content,e.metadata));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 pb{adapter;promptManager;intervalId=null;idleCount=0;isDispatching=false;postSubmitWaitPromise=null;IDLE_THRESHOLD=2;POLL_INTERVAL=1e3;POST_SUBMIT_MIN_WAIT_MS=2500;POST_SUBMIT_QUIET_MS=2500;GENERATION_START_GRACE_MS=8e3;POST_SUBMIT_MAX_WAIT_MS=6e5;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(){if(this.isDispatching)return;if(this.postSubmitWaitPromise)return;const e=gb.getState();if(e.isPaused)return void(this.idleCount=0);const t=e.items.filter(e=>"sending"===e.status);if(t.length>0)return void(await this.recoverSendingItem(t[0]));if(0===e.items.filter(e=>"pending"===e.status).length)return void(this.idleCount=0);if(this.promptManager.hasEditorContent())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(){if(this.isDispatching)return;const e=gb.getState(),t=e.dequeue();if(t){this.isDispatching=true;try{if(this.adapter.isGenerating())return e.updateStatus(t.id,"pending"),void(this.idleCount=0);const n=zf(t.content);_f(n,t.metadata?.quoteRef);const r=t.metadata?.quoteMarkerKind,o=Of(t.content,t.metadata?.quoteRef,r?{kind:r}:void 0);if(!(await this.promptManager.insertPrompt(o)))return void e.updateStatus(t.id,"failed");if("insert"===(t.metadata?.runMode??"enqueue"))return void this.completeItem(t.id);const i=zi.getState().settings.features?.prompts?.submitShortcut??"enter";if(!(await this.promptManager.submitPrompt(i)))return this.isItemContentInEditor(t)?e.updateStatus(t.id,"sending"):(this.completeItem(t.id),this.startPostSubmitWait()),void(this.idleCount=0);this.completeItem(t.id),this.startPostSubmitWait();}catch(vT){console.error("[QueueDispatcher] 发送失败:",vT),e.updateStatus(t.id,this.isItemContentInEditor(t)?"sending":"pending"),this.idleCount=0;}finally{this.isDispatching=false;}}}normalizeContent(e){return e.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").replace(/\s+/g," ").trim()}isItemContentInEditor(e){const t=this.normalizeContent(this.promptManager.getCurrentEditorContent());if(!t)return false;return [this.normalizeContent(e.content),this.normalizeContent(zf(e.content))].some(e=>e&&(t===e||t.includes(e)||e.includes(t)))}completeItem(e){const t=gb.getState();t.updateStatus(e,"sent"),t.remove(e);}async recoverSendingItem(e){if(this.adapter.isGenerating())this.idleCount=0;else {if(!this.isItemContentInEditor(e))return this.completeItem(e.id),void(this.idleCount=0);if(this.idleCount++,!(this.idleCountsetTimeout(e,500));const o=Date.now(),i=this.adapter.isGenerating();i&&(r=true,t=o);const a=this.getConversationActivitySignature();a!==n&&(n=a,t=o);const s=o-e,l=o-t,c=r||s>=this.GENERATION_START_GRACE_MS;if(s>=this.POST_SUBMIT_MIN_WAIT_MS&&l>=this.POST_SUBMIT_QUIET_MS&&!i&&c)return}}startPostSubmitWait(){this.postSubmitWaitPromise||(this.postSubmitWaitPromise=this.waitForConversationIdleAfterSubmit().catch(e=>{console.error("[QueueDispatcher] 等待回复结束失败:",e);}).finally(()=>{this.postSubmitWaitPromise=null,this.idleCount=0;}));}async sendImmediately(e,t,n){try{const r=zf(e);_f(r,n?.quoteRef);const o=n?.quoteMarkerKind,i=Of(e,n?.quoteRef,o?{kind:o}:void 0);if(!(await this.promptManager.insertPrompt(i)))return !1;return await this.promptManager.submitPrompt(t)}catch(vT){return console.error("[QueueDispatcher] 立即发送失败:",vT),false}}async processNextNow(){const e=gb.getState();if(e.isPaused)return false;if(this.isDispatching)return false;if(this.postSubmitWaitPromise)return false;if(this.adapter.isGenerating())return false;if(this.promptManager.hasEditorContent())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 mb=({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 Re("label",{style:{position:"relative",display:"inline-block",width:`${o.w}px`,height:`${o.h}px`,flexShrink:0},children:[ qe("input",{type:"checkbox",checked:e,onChange:()=>t(!e),disabled:n,style:{opacity:0,width:0,height:0,position:"absolute"}}), qe("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:qe("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 fb=false;const bb=({children:e,onClose:t,closeOnOverlayClick:n=true,closeOnEscape:r=true,dialogClassName:o,dialogStyle:i})=>{const a=$(null);L(()=>{(()=>{if(fb)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),fb=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 vs(e,{capture:false})},[]);const s=qe("div",{ref:a,className:"gh-dialog-overlay gh-interactive",...ms,onClick:n?t:void 0,children:qe("div",{className:o?`gh-dialog ${o}`:"gh-dialog",style:i,onClick:e=>e.stopPropagation(),children:e})});return gd(s,document.body)},yb=({title:e,message:t,confirmText:n,cancelText:r,danger:o=false,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s,extraAction:l})=>Re(bb,{onClose:s,closeOnOverlayClick:i,children:[ qe("div",{className:"gh-dialog-title",children:e}), qe("div",{className:"gh-dialog-message",children:t}), Re("div",{className:"gh-dialog-buttons",style:{justifyContent:l?"space-between":"flex-end"},children:[l&&Re("button",{className:"gh-dialog-btn",style:{background:"transparent",color:"var(--gh-primary, #4285f4)",padding:"8px 12px",textDecoration:"underline"},onClick:l.onClick,children:["↗ ",l.text]}), Re("div",{style:{display:"flex",gap:"8px"},children:[ qe("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:r||le("cancel")}), qe("button",{className:"gh-dialog-btn "+(o?"gh-dialog-btn-danger":"gh-dialog-btn-primary"),onClick:a,children:n||le("confirm")})]})]})]}),vb=({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 Re(bb,{onClose:s,closeOnOverlayClick:i,children:[ qe("div",{className:"gh-dialog-title",children:e}), qe("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()}), Re("div",{className:"gh-dialog-buttons",children:[ qe("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:o||le("cancel")}), qe("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:u,children:r||le("confirm")})]})]})},xb=({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 qe("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})},wb=({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 Re("div",{className:s,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),style:{...a,position:"relative",display:"inline-flex",alignItems:"center"},children:[ qe("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&&Re("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:[ qe("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:qe(Pt,{size:8})}), qe("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:qe(Dt,{size:8})})]})]})},Sb=(e,t,n)=>Math.min(n,Math.max(t,e)),Cb=({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=Sb(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:Sb(l,o,i),T=void 0!==k&&m===k,A=E((e=x.current)=>{v.current&&!c&&(v.current=false,t(Sb(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 qe("div",{className:`settings-slider ${c?"disabled":""} ${u}`.trim(),style:{...d,"--slider-progress":`${S}%`},children:Re("div",{className:"settings-slider-main",children:[ Re("div",{className:"settings-slider-track",children:[ qe("input",{type:"range",className:"settings-slider-input",min:o,max:i,step:a,value:m,onChange:e=>{const t=Sb(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}), Re("div",{className:"settings-slider-boundary",children:[ qe("span",{children:h?h(o):`${o}${s||""}`}), qe("span",{children:h?h(i):`${i}${s||""}`})]})]}), qe("span",{className:"settings-slider-value",children:C}),void 0!==k&&qe("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:qe(At,{size:14})})]})})},kb=({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=D(()=>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 Re("div",{ref:b,className:s,style:{position:"relative",width:"100%"},children:[ Re("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:[ qe("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:"8px"},children:w?.label||r}), qe(Dt,{size:16,style:{flexShrink:0,transition:"transform 0.2s ease",transform:g?"rotate(180deg)":"rotate(0deg)"}})]}),g&&qe("div",{role:"listbox",tabIndex:-1,className:c,...ms,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?qe("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 qe("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 Tb(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( qe("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 Re("div",{className:"placeholder-input-field "+(a?"placeholder-input-disabled":""),style:i,children:[ Re("div",{className:"placeholder-input-surface",children:[ qe("div",{className:"placeholder-input-mirror","aria-hidden":"true",children:qe("span",{ref:l,className:"placeholder-input-mirror-scroll",children:Tb(e,n)})}), qe("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})]}), qe("div",{className:"placeholder-input-list","aria-label":"Title format placeholders",children:n.map(e=>qe("button",{type:"button",className:"placeholder-input-button",disabled:a,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:e,children:e},e))})]})},Ab=new Set(["svg","g","path","circle","rect","line","polyline","polygon","ellipse","defs","linearGradient","radialGradient","stop","title","desc"]),Mb=new Set(["aria-hidden","class","clip-rule","cx","cy","d","fill","fill-rule","height","id","offset","opacity","points","r","rx","ry","stroke","stroke-linecap","stroke-linejoin","stroke-width","style","transform","viewBox","width","x","x1","x2","y","y1","y2"]),Ib=/<[^>]+>/g,Lb=/([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,Nb=/\b(?:href|src|url|xlink:href)\b/i,qb=/^on/i,Rb=/url\s*\(|expression\s*\(|javascript:/i,Pb=/javascript:|data:/i,Db=e=>{if(/^<\s*(?:!|\?)/.test(e))return null;const t=e.match(/^<\s*\/\s*([A-Za-z][\w:-]*)\s*>$/);if(t)return {tagName:t[1],isClosing:true,isSelfClosing:false,attrs:[]};const n=/\/\s*>$/.test(e),r=e.match(/^<\s*([A-Za-z][\w:-]*)([\s\S]*?)\/?\s*>$/);if(!r)return null;const o=(e=>{const t=[];let n=0;for(const r of e.matchAll(Lb)){const o=r.index??0;if(e.slice(n,o).trim())return null;t.push({name:r[1],value:r[2]??r[3]??""}),n=o+r[0].length;}return e.slice(n).trim()?null:t})(r[2].trim());return o?{tagName:r[1],isClosing:false,isSelfClosing:n,attrs:o}:null},Bb=(e,t,n)=>{if(!t)return true;const r=e[e.length-1];return r?("title"!==r.tagName&&"desc"!==r.tagName||r.appendChild(n.createTextNode(t)),true):0===t.trim().length},$b=(e,t=document)=>{const n=e.trim();if(!n)return null;let r=null;const o=[];let i=0;for(const a of n.matchAll(Ib)){const e=a.index??0;if(!Bb(o,n.slice(i,e),t))return null;const s=Db(a[0]);if(!s)return null;if(!Ab.has(s.tagName))return null;if(s.isClosing){const t=o[o.length-1];if(!t||t.tagName!==s.tagName)return null;o.pop(),i=e+a[0].length;continue}const l=t.createElementNS("http://www.w3.org/2000/svg",s.tagName);if(s.attrs.forEach(e=>{var t,n;t=e.name,n=e.value,qb.test(t)||Nb.test(t)||!Mb.has(t)||Pb.test(n)||"style"===t&&Rb.test(n)||l.setAttribute(e.name,e.value);}),r){const e=o[o.length-1];if(!e)return null;e.appendChild(l);}else {if("svg"!==s.tagName)return null;r=l;}s.isSelfClosing||o.push(l),i=e+a[0].length;}return Bb(o,n.slice(i),t)?!r||o.length>0||"svg"!==r.tagName?null:(r.getAttribute("viewBox")||r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("aria-hidden","true"),r):null},_b=e=>{const t=$b(e);return t?(new XMLSerializer).serializeToString(t):""},Ob=({svg:e,className:t,fallback:n=null,title:r})=>{const o=$(null),i=D(()=>_b(e||""),[e]);return L(()=>{const e=o.current;if(!e)return;if(e.replaceChildren(),!i)return;const t=$b(i,document);t&&e.replaceChildren(t);},[i]),i?qe("span",{ref:o,className:t,title:r}):qe(Ne,{children:n})},zb=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}},Fb=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(zb(e)));}return r},Ub=(e,t)=>e.replace(/\{\{([^\s{}]+)\}\}/g,(e,n)=>void 0!==t[n]?t[n]:e),Hb=e=>{const t=e.replace(/\r\n?/g,"\n").trim();return t?t.split("\n").map(e=>e.trim().length>0?`> ${e}`:">").join("\n"):""},Wb=({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 qe(bb,{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:Re("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:[ Re("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ qe("h3",{style:{margin:0,fontSize:"16px",fontWeight:600,color:"var(--gh-text, #374151)"},children:le("promptVariableTitle")}), qe("button",{onClick:n,style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:qe($e,{size:18})})]}), qe("div",{style:{padding:"16px",overflowY:"auto",flex:1},children:e.map((e,t)=>Re("div",{style:{marginBottom:"16px",display:"flex",flexDirection:"column",gap:"6px"},children:[ qe("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",wordBreak:"break-all"},children:e.name}),e.options? qe("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=>qe("option",{value:e,children:e},e))}): qe("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))}), Re("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ qe("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")}), qe("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")})]})]})})},jb="selection",Gb="quote",Qb=(e,t)=>e.find(e=>e.id===t)??null,Vb=e=>{const t=e.selectedText.trim();return {[jb]:t,[Gb]:e.quoteText||Hb(t)}},Kb=(e,t,n={})=>{const r=new Set(Object.keys(n)),o=((e,t)=>e.steps.map(e=>"inline"===e.mode&&e.inlineContent?e.inlineContent:e.promptId&&Qb(t,e.promptId)?.content||"").filter(Boolean))(e,t).flatMap(Fb);return (e=>{const t=new Set,n=[];return e.forEach(e=>{t.has(e.raw)||(t.add(e.raw),n.push(e));}),n})(o).filter(e=>!r.has(e.raw))},Zb=({chain:e,prompts:t,selection:n,values:r={}})=>{const o={...Vb(n),...r},i=e.steps.length;return e.steps.map((r,a)=>{let s=null,l="";if("inline"===r.mode&&r.inlineContent)l=r.inlineContent,s={id:r.id,title:`Inline Step ${a+1}`,content:r.inlineContent,category:""};else {if(s=Qb(t,r.promptId),!s)return null;l=s.content;}const c=Ub(l,o).trim();if(!c)return null;let d=(e=>Fb(e).some(e=>e.raw===jb||e.raw===Gb))(l)?n.quoteRef:void 0;return d&&(d={...d,chainId:e.id,chainTitle:e.title,stepId:r.id,stepIndex:a+1,stepTotal:i}),{step:{id:r.id,promptId:s.id,template:l,runMode:r.runMode,splitMode:r.splitMode},prompt:s,content:c,quoteRef:d}}).filter(e=>null!==e)},Yb="gh-quick-quote-source-highlight",Xb="gh-quick-quote-source-text";let Jb=null;const ey=e=>"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&"),ty=e=>e.replace(/\s+/g," ").trim().slice(0,60),ny=e=>e.replace(/\s+/g," ").trim(),ry=e=>{const t=ny(e);return t.slice(Math.max(0,t.length-60))},oy=e=>{let t=2166136261;for(const n of ny(e))t^=n.codePointAt(0)||0,t=Math.imul(t,16777619);return (t>>>0).toString(36)},iy=e=>{const t=e.getResponseContainerSelector();return e.getScrollContainer()||(t?document.querySelector(t):null)||document},ay=e=>{const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>e instanceof Text&&!(e=>{const t=e.parentElement;return !t||Boolean(t.closest(".gh-root, .gh-main-panel, .gh-quick-quote-chip-row, .gh-quick-quote-chip"))})(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}),n=[];let r="",o=true,i=t.nextNode();for(;i;){const e=i;for(let t=0;t0&&!o&&(r+=" ",n.push({node:e,offset:t}),o=true):(r+=i,n.push({node:e,offset:t}),o=false);}i=t.nextNode();}for(;r.endsWith(" ");)r=r.slice(0,-1),n.pop();return {text:r,positions:n}},sy=(e,t)=>{const n=t.getChatContentSelectors();if(0===n.length)return;const r=Array.from(iy(t).querySelectorAll(n.join(", "))).filter(e=>!e.closest(".gh-root, .gh-main-panel")).indexOf(e);return r>=0?r:void 0},ly=(e,t)=>{const n=(r=e.startContainer)?r.nodeType===Node.ELEMENT_NODE?r:r.parentElement:null;var r;if(!n)return null;const o=t.getChatContentSelectors().join(", ");if(o){const e=n.closest(o);if(e)return e}const i=t.getUserQuerySelector();if(i){const e=n.closest(i);if(e)return e}return n},cy=({selectedText:e,adapter:t,range:n})=>{const r=(({range:e,selectedText:t,adapter:n})=>{const r=ly(e,n);if(!r)return null;const o=ay(r),i=o.text,a=ny(t),s=((e,t,n)=>{let r=-1,o=-1;for(let i=0;i=0&&o>=r){const t=e.text.slice(r,o+1).indexOf(n);return t>=0?r+t:r}return e.text.indexOf(n)})(o,e,a),l=t.length<20?80:40,c=s>=0?i.slice(Math.max(0,s-l),s):"",d=s>=0?i.slice(s+a.length,s+a.length+l):"",u=r.getAttribute("data-message-id")||r.closest("[data-message-id]")?.getAttribute("data-message-id")||r.id||"",h=u?r.id===u?`#${ey(u)}`:`[data-message-id="${ey(u)}"]`:void 0,g=n.getScrollContainer();return {siteId:n.getSiteId(),sessionId:n.getSessionId(),cid:n.getCurrentCid()||void 0,selectedText:t,textSignature:ty(t),selectedPrefix:ty(a),selectedSuffix:ry(a),selectedLength:a.length,selectedHash:oy(a),beforeText:ty(c),afterText:ty(d),rootSelector:h,rootIndex:sy(r,n),rootTextSignature:ty(i),selectionIndex:s>=0?s:void 0,scrollTop:g?.scrollTop,createdAt:Date.now()}})({range:n,selectedText:e,adapter:t});if(!r)return null;const o=Hb(e);return {id:`quote_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,selectedText:e,quoteText:o,anchor:r,createdAt:Date.now()}},dy=e=>ny(e.textContent||""),uy=(e,t)=>{const n=ny(t||"");return Boolean(n)&&e.includes(n)},hy=(e,t)=>{const n=((e,t)=>{const n=iy(t),r=new Map,o=(e,t)=>{e&&!e.closest(".gh-root, .gh-main-panel")&&r.set(e,Math.max(r.get(e)||0,t));};if(e.rootSelector){const t=n.querySelector(e.rootSelector);o(t,40);}const i=t.getChatContentSelectors();return 0===i.length||Array.from(n.querySelectorAll(i.join(", "))).filter(e=>!e.closest(".gh-root, .gh-main-panel")).forEach((t,n)=>{const r=dy(t),i=uy(r,e.rootTextSignature);void 0!==e.rootIndex&&n===e.rootIndex&&o(t,i?18:4),i&&o(t,14);const a=ny(e.selectedPrefix||e.textSignature||e.selectedText);a&&r.includes(a)&&o(t,8);}),r})(e,t);let r=null;return n.forEach((t,n)=>{const o=my(n,e),i=((e,t,n)=>{const r=dy(e);let o=n;return uy(r,t.rootTextSignature)&&(o+=10),uy(r,t.selectedPrefix||t.textSignature)&&(o+=4),uy(r,t.beforeText)&&(o+=3),uy(r,t.afterText)&&(o+=3),o})(n,e,t),a=i+(o?20+o.score:0);(!r||a>r.score)&&(r={root:n,textMatch:o,score:a});}),r&&r.score>=18?r:null},gy=e=>{e.classList.remove(Yb),e.offsetWidth,e.classList.add(Yb),window.setTimeout(()=>e.classList.remove(Yb),2400);},py=(e,t)=>{const n=[];if(!t)return n;let r=0;for(;r{const n=ny(t.selectedText),r=t.selectedLength&&t.selectedLength>0?t.selectedLength:n.length;if(r<=0)return null;const o=ay(e),i=n.length===r?n:"",a=ny(t.selectedPrefix||t.textSignature||i),s=ny(t.selectedSuffix||""),l=new Set;i?py(o.text,i).forEach(e=>l.add(e)):a&&py(o.text,a).forEach(e=>l.add(e)),void 0!==t.selectionIndex&&l.add(t.selectionIndex);const c=Array.from(l).filter(e=>e>=0&&e+r<=o.text.length);if(0===c.length)return null;const d=e=>{const n=o.text.slice(e,e+r);let l=((e,t,n,r)=>{let o=0;const i=ny(r.beforeText||""),a=ny(r.afterText||"");if(i){const n=e.slice(Math.max(0,t-i.length-40),t);n.endsWith(i)?o+=8:n.includes(i)&&(o+=4);}if(a){const r=e.slice(t+n,t+n+a.length+40);r.startsWith(a)?o+=8:r.includes(a)&&(o+=4);}if(void 0!==r.selectionIndex){const e=Math.abs(t-r.selectionIndex);0===e?o+=4:e<=24?o+=2:e<=120&&(o+=1);}return o})(o.text,e,r,t);if(t.selectedHash){if(oy(n)!==t.selectedHash)return Number.NEGATIVE_INFINITY;l+=12;}if(i&&n===i&&(l+=10),a){if(!n.startsWith(a))return Number.NEGATIVE_INFINITY;l+=6;}if(s){if(!n.endsWith(s))return Number.NEGATIVE_INFINITY;l+=6;}return l},u=c.reduce((e,t)=>{const n=d(e);return d(t)>n?t:e},c[0]),h=d(u);if(!Number.isFinite(h))return null;const g=o.positions[u],p=o.positions[u+r-1];if(!g||!p)return null;const m=document.createRange();return m.setStart(g.node,g.offset),m.setEnd(p.node,p.offset+1),{range:m,score:h,matchIndex:u,matchCount:c.length}},fy=e=>{const t=e.startContainer,n=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement;return n instanceof HTMLElement?n:null},by=(e,t)=>{const n=hy(e.anchor,t);if(!n)return false;const r=n.root instanceof HTMLElement?n.root:n.root.parentElement;if(!r)return false;if(n.textMatch){if(((e,t)=>{const n=e.getBoundingClientRect(),r=t.getScrollContainer();if(r instanceof HTMLElement&&n.width>0&&n.height>0&&r.contains(fy(e))){const e=r.getBoundingClientRect(),t=r.scrollTop+n.top-e.top-e.height/2+n.height/2;return void r.scrollTo({top:t,behavior:"smooth"})}fy(e)?.scrollIntoView({behavior:"smooth",block:"center"});})(n.textMatch.range,t),!(e=>{const t=window.Highlight,n=CSS.highlights;return !(!t||!n||(null!==Jb&&(window.clearTimeout(Jb),Jb=null),n.delete(Xb),n.set(Xb,new t(e.cloneRange())),Jb=window.setTimeout(()=>{n.delete(Xb),Jb=null;},2400),0))})(n.textMatch.range)){const e=fy(n.textMatch.range);e&&gy(e);}return true}return r.scrollIntoView({behavior:"smooth",block:"center"}),gy(r),true},yy=e=>({...e,iconSvg:e.iconSvg?_b(e.iconSvg):"",showInSelectionPopover:false!==e.showInSelectionPopover,steps:Array.isArray(e.steps)?e.steps:[],createdAt:e.createdAt||Date.now(),updatedAt:e.updatedAt||Date.now()}),vy=(e,t=false)=>{const n=ho().map(yy),r=new Set(n.map(e=>e.id)),o=t?e.filter(e=>!r.has(e.id)):e,i=new Set(o.map(e=>e.id));return [...n.filter(e=>!i.has(e.id)),...o]};let xy=null;const wy=Vo()(Yo((e,t)=>(xy=()=>e({_hasHydrated:true}),{chains:ho().map(yy),defaultChainsVersion:2,_hasHydrated:false,addChain:t=>{const n=Date.now(),r=yy({id:`chain_${n}_${Math.random().toString(36).slice(2,8)}`,...t,createdAt:n,updatedAt:n});return e(e=>({chains:[...e.chains,r]})),r},updateChain:(t,n)=>e(e=>({chains:e.chains.map(e=>e.id===t?yy({...e,...n,updatedAt:Date.now()}):e)})),deleteChain:t=>e(e=>({chains:e.chains.filter(e=>e.id!==t)})),duplicateChain:n=>{const r=t().chains.find(e=>e.id===n);if(!r)return null;const o=Date.now(),i=yy({...r,id:`chain_${o}_${Math.random().toString(36).slice(2,8)}`,title:`${r.title} Copy`,createdAt:o,updatedAt:o,lastUsedAt:void 0});return e(e=>({chains:[...e.chains,i]})),i},updateOrder:t=>e(e=>{const n=[];return t.forEach(t=>{const r=e.chains.find(e=>e.id===t);r&&n.push(r);}),e.chains.forEach(e=>{n.some(t=>t.id===e.id)||n.push(e);}),{chains:n}}),updateLastUsed:t=>e(e=>({chains:e.chains.map(e=>e.id===t?{...e,lastUsedAt:Date.now()}:e)})),setChains:t=>e({chains:t.map(yy)}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"promptChains",storage:Ko(()=>Ti),partialize:e=>({chains:e.chains,defaultChainsVersion:e.defaultChainsVersion}),merge:(e,t)=>{const n=e,r=n?.chains,o=Array.isArray(r)?r.map(yy):t.chains,i=!n||2!==n.defaultChainsVersion;return {...t,chains:i?vy(o,true):o,defaultChainsVersion:2}},onRehydrateStorage:()=>()=>{xy?.();}})),Sy="gh-quick-quote-host-styles",Cy=".gh-quick-quote-chip-row",ky=e=>{if(!(e instanceof HTMLElement))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||"0"===t.opacity)return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0},Ty=e=>Boolean(e?.closest(".gh-root, .gh-main-panel, "+fs)),Ey=(e,t)=>{const n=10,r=Math.min(window.innerWidth-n,Math.max(n,e.left+e.width/2)),o=Math.max(n,e.top-48);if("native"!==t.getQuickQuoteSupportMode())return {left:r,top:o};const i=t.getNativeQuotePopoverSelectors();if(0===i.length)return {left:r,top:o};let a=null;for(const l of i){const e=document.querySelector(l);if(e&&ky(e)){a=e;break}}if(!a)return {left:r,top:o};const s=a.getBoundingClientRect();return s.bottome.bottom?{left:r,top:o}:s.righte.right?{left:Math.max(n,e.left-200),top:Math.max(n,e.top)}:{left:Math.min(window.innerWidth-n,s.right+n),top:Math.max(n,e.top)}},Ay=(e,t)=>{const n=(e=>{if(!e)return null;const t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t instanceof HTMLElement?t:null})(e.commonAncestorContainer);if(!n)return false;if(Ty(n))return false;if((e=>ys(e))(n))return false;if(n.closest("input, textarea, select, [contenteditable='true'], .ProseMirror"))return false;const r=t.getChatContentSelectors().join(", ");if(r&&n.closest(r))return true;const o=t.getUserQuerySelector();if(o&&n.closest(o))return true;const i=t.getResponseContainerSelector();return !i||Array.from(document.querySelectorAll(i)).some(e=>e.contains(n))},My=(e,t)=>{const n=t.getQuickQuoteChipHost(e);return n instanceof HTMLElement&&e.contains(n)?n:e},Iy=(e,t)=>{const n=e.querySelector(Cy),r=n instanceof HTMLElement?n:document.createElement("span");return r.className="gh-quick-quote-chip-row",r.parentElement===t&&t.firstElementChild===r||t.prepend(r),r},Ly=["#4285f4","#ea4335","#fbbc04","#34a853","#ff6d01","#46bdc6","#7b61ff","#e91e63"],Ny=({title:e})=>{const t=e.trim().charAt(0)||"C";let n=0;for(let o=0;o{if(e.querySelector(`#${Sy}`))return;const t=document.createElement("style");t.id=Sy,t.textContent='\n .gh-quick-quote-chip-row {\n box-sizing: border-box !important;\n display: flex !important;\n align-items: center !important;\n justify-content: flex-start !important;\n flex-wrap: wrap !important;\n gap: 4px !important;\n width: fit-content !important;\n max-width: 100% !important;\n margin: 0 0 6px !important;\n padding: 0 !important;\n pointer-events: auto !important;\n }\n button.gh-quick-quote-chip {\n all: unset !important;\n box-sizing: border-box !important;\n display: inline-flex !important;\n align-items: center !important;\n gap: 6px !important;\n width: fit-content !important;\n max-width: min(360px, 100%) !important;\n margin: 0 !important;\n padding: 4px 8px !important;\n border: 1px solid rgba(66, 133, 244, 0.28) !important;\n border-radius: 8px !important;\n background: rgba(66, 133, 244, 0.07) !important;\n color: #2563eb !important;\n font: 500 12px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif !important;\n letter-spacing: 0 !important;\n vertical-align: baseline !important;\n cursor: pointer !important;\n user-select: none !important;\n }\n button.gh-quick-quote-chip::before {\n content: "";\n width: 2px;\n height: 14px;\n flex: 0 0 2px;\n border-radius: 999px;\n background: rgba(66, 133, 244, 0.72);\n }\n button.gh-quick-quote-chip:hover {\n background: rgba(66, 133, 244, 0.12) !important;\n border-color: rgba(66, 133, 244, 0.45) !important;\n color: #1d4ed8 !important;\n }\n .gh-quick-quote-chip-text {\n min-width: 0 !important;\n overflow: hidden !important;\n text-overflow: ellipsis !important;\n white-space: nowrap !important;\n }\n .gh-quick-quote-source-highlight {\n outline: 2px solid rgba(66, 133, 244, 0.75) !important;\n outline-offset: 4px !important;\n animation: gh-quick-quote-source-pulse 2.4s ease;\n }\n ::highlight(gh-quick-quote-source-text) {\n background: rgba(66, 133, 244, 0.28);\n color: inherit;\n }\n @media (prefers-color-scheme: dark) {\n button.gh-quick-quote-chip {\n background: rgba(96, 165, 250, 0.13) !important;\n border-color: rgba(147, 197, 253, 0.34) !important;\n color: #bfdbfe !important;\n }\n button.gh-quick-quote-chip:hover {\n background: rgba(96, 165, 250, 0.2) !important;\n color: #dbeafe !important;\n }\n ::highlight(gh-quick-quote-source-text) {\n background: rgba(96, 165, 250, 0.34);\n color: inherit;\n }\n }\n @keyframes gh-quick-quote-source-pulse {\n 0%, 100% { box-shadow: 0 0 0 rgba(66, 133, 244, 0); }\n 30% { box-shadow: 0 0 0 8px rgba(66, 133, 244, 0.16); }\n }\n ',e instanceof Document?e.head.appendChild(t):e.prepend(t);},Ry=({adapter:e,enabled:t})=>{const n=$(null),r=$(false),o=$(new Map),i=$(new WeakSet),a=$(new Set),s=$(false),l=$(null),c=E(()=>{const t=e.getUserQuerySelector();if(!t)return;(Cs.query(t,{all:true,shadow:true})||[]).forEach(e=>{e instanceof HTMLElement&&(e.querySelectorAll(Cy).forEach(e=>e.remove()),delete e.dataset.ghQuickQuoteRefs);});},[e]),d=E(()=>{c(),i.current=new WeakSet,a.current=new Set,s.current=false;},[c]),u=E(()=>{if(t&&!r.current){r.current=true;try{const t=e.getUserQuerySelector();if(!t)return;const n=e.getSessionId(),r=e.getSiteId();l.current!==n&&(l.current=n,i.current=new WeakSet,a.current=new Set,o.current.clear(),s.current=!1),qy(document);const c=Cs.query(t,{all:!0,shadow:!0})||[],d=i.current,u=a.current,h=[];c.forEach((t,n)=>{if(!(t instanceof HTMLElement))return;const r=e.extractUserQueryText(t),o=((e,t)=>{const n=t.replace(/\s+/g," ").trim();return `${e}:${n.length}:${n.slice(0,120)}:${n.slice(-120)}`})(n,r||t.textContent||"");h.push({message:t,visibleText:r,scopeKey:o,isKnown:d.has(t)||u.has(o)});});const g=new Map,p=o.current;[...h].reverse().forEach(({message:e,visibleText:t,scopeKey:o,isKnown:i})=>{const a=(e=>{const t=[],n=new Set,r=e=>{e&&!n.has(`${e.kind}:${e.id}`)&&(n.add(`${e.kind}:${e.id}`),t.push(e));};e.querySelectorAll("a[href]").forEach(e=>{const t=Uf(e);t&&r(Df(t));});const o=e.textContent||"";return Rf(o).forEach(r),t})(e),l=0===a.length?Ff(e,t,{allowMarkerlessMatch:s.current&&!i,currentSessionId:n,currentSiteId:r,markerlessScopeKey:o}):[],c=[...a,...l];g.set(e,c),c.forEach(e=>{e.reference&&p.set(e.id,e.reference);});}),h.forEach(({message:t})=>{const n=new Set(Array.from(t.querySelectorAll("button.gh-quick-quote-chip")).map(e=>e.dataset.ghQuickQuoteRefId).filter(e=>Boolean(e))),r=g.get(t)||[],o=r.map(e=>e.reference||p.get(e.id)).filter(e=>Boolean(e));r.some(e=>!e.reference&&!p.has(e.id))||Wf(t);const i=o.filter((e,t,r)=>!n.has(e.id)&&r.findIndex(t=>t.id===e.id)===t);if(t.querySelector(Cy)instanceof HTMLElement&&n.size>0&&Iy(t,My(t,e)),0===i.length)return;const a=Iy(t,My(t,e)),s=t.getRootNode();(s instanceof Document||s instanceof ShadowRoot)&&qy(s);const l=document.createDocumentFragment();i.forEach(t=>{const r=document.createElement("button");r.type="button",r.className="gh-quick-quote-chip",r.dataset.ghQuickQuoteRefId=t.id,r.title=le("quickQuoteJumpToSource");const o=document.createElement("span");o.className="gh-quick-quote-chip-text",o.textContent=((e,t=72)=>{const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}...`:n})(t.selectedText),r.append(o),r.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation();by(t,e)||Gi(le("quickQuoteSourceNotFound"),2400);}),l.append(r),n.add(t.id);}),a.append(l),t.dataset.ghQuickQuoteRefs=Array.from(n).join(",");}),h.forEach(({message:e,scopeKey:t})=>{d.add(e),u.add(t);}),s.current=!0;}finally{r.current=false;}}},[e,t]),h=E(()=>{null!==n.current&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{n.current=null,u();},100);},[u]);return L(()=>{if(!t)return void d();u();const r=e.getResponseContainerSelector(),o=e.getObserveTarget()||(r?document.querySelector(r):null)||document.body,i=new MutationObserver(e=>{e.some(e=>e.addedNodes.length>0||"characterData"===e.type||"attributes"===e.type&&["class","style","href","title"].includes(e.attributeName||""))&&h();});return i.observe(o,{attributes:true,attributeFilter:["class","style","href","title"],characterData:true,childList:true,subtree:true}),()=>{i.disconnect(),null!==n.current&&window.clearTimeout(n.current);}},[e,h,t,u,d]),null},Py=({adapter:e,promptManager:t})=>{const n=wy(e=>e.chains),r=wy(e=>e.updateLastUsed),o=nb(e=>e.prompts),i=zi(e=>e.settings.features?.prompts?.promptQueue??false),a=zi(e=>e.settings.features?.prompts?.quickQuoteEnabled??true),s=zi(e=>e.updateDeepSetting),l=gb(e=>e.enqueueMany),[c,d]=_(null),[u,h]=_(null),[g,p]=_(null),[m,f]=_(false),[b,y]=_(false),[v,x]=_(false),w=$(false),S=$(null),C=D(()=>n.map((e,t)=>({chain:e,index:t})).filter(({chain:e})=>e.showInSelectionPopover).sort((e,t)=>(t.chain.lastUsedAt??0)-(e.chain.lastUsedAt??0)||e.index-t.index).map(({chain:e})=>e),[n]),k=C.slice(0,3),T=C.slice(3),A=C.some(e=>!(e=>e.id===uo)(e)),M=D(()=>e.getQuickQuoteSupportMode(),[e]),I=D(()=>{return e=M,!!a&&("enabled"===e||"native"===e);var e;},[a,M]),N=D(()=>{return e=M,t=A,!(!a||"enabled"!==e&&("native"!==e||!t));var e,t;},[A,a,M]),q=E(()=>{d(null);const e=window.getSelection();e?.removeAllRanges();},[]),R=E(()=>{if(!N)return void d(null);const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed)return void d(null);const n=t.toString().trim();if(!n||n.length>8e3)return void d(null);const r=t.getRangeAt(0).cloneRange();if(!Ay(r,e))return void d(null);const o=(e=>{const t=Array.from(e.getClientRects()).filter(e=>e.width>0&&e.height>0);return t[t.length-1]||e.getBoundingClientRect()||null})(r);if(!o||0===o.width||0===o.height)return void d(null);"native"===e.getQuickQuoteSupportMode()?setTimeout(()=>{const e=window.getSelection();e&&!e.isCollapsed&&e.toString().trim()===n&&d({text:n,range:r,rect:o});},100):d({text:n,range:r,rect:o});},[e,N]);L(()=>{c&&0!==T.length||f(false);},[T.length,c]),L(()=>{x(false),null!==S.current&&(window.clearTimeout(S.current),S.current=null);},[c?.text]),L(()=>()=>{null!==S.current&&window.clearTimeout(S.current);},[]),L(()=>{if(!c)return y(false),void p(null);i&&(y(false),p(null));},[i,c]),L(()=>{if(!N)return d(null),void h(null);const e=()=>{const e=window.getSelection();e&&0!==e.rangeCount&&!e.isCollapsed||d(null);},t=()=>d(null),n=e=>{if(0!==e.button)return;const t=e.target instanceof Element?e.target:null;Ty(t)||(w.current=true,d(null));},r=e=>{0===e.button&&w.current&&(w.current=false,window.setTimeout(R,0));},o=()=>window.setTimeout(R,0);return document.addEventListener("selectionchange",e),document.addEventListener("mousedown",n),document.addEventListener("mouseup",r),document.addEventListener("keyup",o),window.addEventListener("scroll",t,true),window.addEventListener("resize",t),()=>{document.removeEventListener("selectionchange",e),document.removeEventListener("mousedown",n),document.removeEventListener("mouseup",r),document.removeEventListener("keyup",o),window.removeEventListener("scroll",t,true),window.removeEventListener("resize",t);}},[R,N]);const P=E(()=>{if(!c)return null;const t=I?cy({selectedText:c.text,adapter:e,range:c.range}):null;return {selectedText:c.text,quoteText:Hb(c.text),quoteRef:t||void 0}},[e,I,c]),B=E(()=>{y(false),p(null),window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:"prompt-queue"}}));},[]),O=E(async()=>{if(c)try{await navigator.clipboard.writeText(c.text),x(!0),Gi(le("copySuccess"),1500),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{x(!1),S.current=null;},1500);}catch(vT){console.error("[QuickQuote] Copy failed:",vT),Gi(le("copyFailed"),1800);}},[c]),z=E(async()=>{if(!c)return;const e=Hb(c.text)+"\n\n",n=P();_f(e,n?.quoteRef);const r=Of(e,n?.quoteRef);await t.insertPrompt(r)?(Gi(le("quickQuoteInserted"),1800),q()):Gi(le("insertFailed"));},[q,P,t,c]),F=E(async(e,n,i)=>{const a=Zb({chain:e,prompts:o,selection:n,values:i});if(0===a.length)return void Gi(le("promptEnqueueEmpty"),2500);if(a.every(e=>"insert"===e.step.runMode)){const n=a.map(e=>e.content).join("\n\n"),o=a.find(e=>e.quoteRef)?.quoteRef;_f(n,o);const i=await t.insertPrompt((e=>{let t=false;return e.map(e=>{const n=e.quoteRef?t?"ref":"full":void 0;return "full"===n&&(t=true),Of(e.content,e.quoteRef,n?{kind:n}:void 0)}).join("\n\n")})(a));return i?(r(e.id),Gi(le("quickQuoteInserted"),1800),void q()):void Gi(le("insertFailed"))}if(!(zi.getState().settings.features?.prompts?.promptQueue??false))return p({chain:e,selection:n}),void y(true);const s=((e,t)=>{let n=false;return t.map((r,o)=>{const i=r.quoteRef?n?"ref":"full":void 0;return "full"===i&&(n=true),{content:Of(r.content,r.quoteRef,i?{kind:i}:void 0),metadata:{source:"quick-follow-up",promptId:r.prompt.id,promptTitle:r.prompt.title,chainId:e.id,chainTitle:e.title,stepId:r.step.id,stepIndex:o+1,stepTotal:t.length,quoteRef:r.quoteRef,quoteMarkerKind:i,runMode:r.step.runMode}}})})(e,a),c=l(s);r(e.id),Gi(le("quickQuoteChainQueued",{count:String(c.length)}),2500),q();},[q,l,t,o,r]),U=E((e,t)=>{const n=Vb(t),r=Kb(e,o,n);r.length>0?h({chain:e,selection:t,variables:r}):F(e,t,{});},[o,F]),H=E(()=>{const e=g;s("features","prompts","promptQueue",true),y(false),p(null),Gi(le("chainQueueEnabledToast"),1800),e&&U(e.chain,e.selection);},[g,U,s]),W=E(e=>{if(!c)return;f(false);const t=P();return t?i||(e=>e.steps.length>0&&e.steps.every(e=>"insert"===e.runMode))(e)?void U(e,t):(h(null),p({chain:e,selection:t}),void y(true)):void 0},[P,U,i,c]),j=D(()=>{if(!c)return {};const{left:t,top:n}=Ey(c.rect,e);return {left:t,top:n}},[c,e]);return L(()=>{if(!c)return;if("native"!==e.getQuickQuoteSupportMode())return;const t=setTimeout(()=>{const t=e.getNativeQuotePopoverSelectors();if(0===t.length)return;let n=null;for(const e of t){const t=document.querySelector(e);if(t&&ky(t)){n=t;break}}if(n){const t=document.querySelector(".gh-quick-quote-popover");if(t instanceof HTMLElement){const{left:n,top:r}=Ey(c.rect,e);t.style.left=`${n}px`,t.style.top=`${r}px`;}}},100);return ()=>clearTimeout(t)},[c,e]),c||u?Re(Ne,{children:[ qe(Ry,{adapter:e,enabled:I}),c&&Re("div",{className:"gh-quick-quote-popover gh-interactive",style:j,onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onKeyDown:e=>{"Escape"===e.key&&f(false);},children:[I&&Re(Ne,{children:[ qe("button",{className:"gh-quick-quote-action gh-quick-quote-copy-action"+(v?" active":""),title:le(v?"copySuccess":"copy"),"aria-label":le(v?"copySuccess":"copy"),onClick:()=>{O();},children:qe(v?tn:Nt,{size:15})}), Re("button",{className:"gh-quick-quote-action",title:le("quickQuoteQuote"),onClick:()=>{z();},children:[ qe(hn,{size:15}), qe("span",{children:le("quickQuoteQuote")})]})]}),I&&k.length>0&&qe("span",{className:"gh-quick-quote-divider"}),k.map(e=>Re("button",{className:"gh-quick-quote-action icon-only",title:e.title,onClick:()=>W(e),children:[ qe(Ob,{className:"gh-quick-quote-svg",svg:e.iconSvg,fallback:qe(Ny,{title:e.title})}), qe("span",{children:e.title})]},e.id)),T.length>0&&Re("span",{className:"gh-quick-quote-more-wrap",children:[ Re("button",{type:"button",className:"gh-quick-quote-action gh-quick-quote-more-trigger"+(m?" active":""),title:`${le("floatingToolbarMore")} (${T.length})`,"aria-haspopup":"menu","aria-expanded":m,onClick:()=>f(e=>!e),children:[ qe(Rt,{size:15}), Re("span",{children:["+",T.length]})]}),m&&qe("div",{className:"gh-quick-quote-more-menu",role:"menu",children:T.map(e=>Re("button",{type:"button",className:"gh-quick-quote-more-item",title:e.title,role:"menuitem",onClick:()=>W(e),children:[ qe(Ob,{className:"gh-quick-quote-svg",svg:e.iconSvg,fallback:qe(Ny,{title:e.title})}), qe("span",{children:e.title})]},e.id))})]}),b&&Re("div",{className:"gh-quick-quote-queue-gate",children:[ Re("div",{className:"gh-quick-quote-queue-gate-copy",children:[ qe("div",{className:"gh-quick-quote-queue-gate-title",children:le("chainQueueRequiredTitle")}), qe("div",{className:"gh-quick-quote-queue-gate-description",children:le("chainQueueRunRequiredDescription")})]}), Re("div",{className:"gh-quick-quote-queue-gate-actions",children:[ qe("button",{type:"button",onClick:H,children:le("chainQueueEnableAndRun")}), qe("button",{type:"button",onClick:B,children:le("chainQueueViewSettings")})]})]})]}),u&&qe(Wb,{variables:u.variables,onConfirm:e=>{const{chain:t,selection:n}=u;h(null),F(t,n,e);},onCancel:()=>h(null)})]}):qe(Ry,{adapter:e,enabled:I})},Dy=[{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"}}],By=[{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)"}}],$y=(e,t)=>{const n=((e,t)=>("light"===t?Dy:By).find(t=>t.id===e))(e,t);return n||("light"===t?Dy[0]:By[0])},_y="google-gradient",Oy="classic-dark",zy="ophel-native-adaptive-style";class Fy{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 vo:return localStorage.setItem("theme","system"),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case No: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 So: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 Io:{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 Co:{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 Eo:case xo:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case yo: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 bo:case wo:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case ko:return !1;case Lo: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(zy))return;const t=document.createElement("style");t.id=zy,t.textContent=e,document.head.appendChild(t);}removeNativeThemeOverrideCss(){document.getElementById(zy)?.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()===yo;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 vo:case So:case No:case Io:{const e=localStorage.getItem("theme");return "light"===e||"dark"===e||"system"===e?e:null}case Co:{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 Eo:{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 xo:{const e=localStorage.getItem("SKIN_MODE");return "1"===e?"light":"2"===e?"dark":"3"===e?"system":null}case yo:{const e=localStorage.getItem("Bard-Color-Theme");return e?/dark/i.test(e)?"dark":/light/i.test(e)?"light":null:"system"}case bo:{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 wo:{const e=Cs.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=Cs.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 ko:return "light";case Lo:{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);}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=$y(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()!==vo||!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 Uy(e){const{mode:t,onModeChange:n,adapter:r,lightPresetId:o=_y,darkPresetId:i=Oy,syncNativePageTheme:a=true,apply:s=false}=e,l=window.__ophelThemeManager||new Fy(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 Hy=new Set(["outline-search-input","conversations-search-input","prompt-search-input"]),Wy=e=>{const t=e.composedPath().find(e=>e instanceof HTMLElement);return t||(e.target instanceof HTMLElement?e.target:null)};function jy({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(()=>bs(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=Wy(e);t&&ys(t)&&(t.closest(".settings-modal-overlay, .settings-modal")||(u.current=true,y(),f()));},a=e=>{const t=Wy(e);t&&ys(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(Hy).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 Gy{handlers=new Map;settings=null;isMac=mr();isListening=false;processedEvents=new WeakSet;updateSettings(e){this.settings=gr(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=hr(t);if(!n)return false;const r=ur(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(false===e.isTrusted)return;if(this.shouldIgnoreEvent(e))return;if(this.processedEvents.has(e))return;if(this.processedEvents.add(e),!this.settings?.enabled)return;if(!this.isMac&&e.getModifierState("AltGraph"))return;const t={...sr,...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 Qy=null;let Vy=null;const Ky=new Set,Zy=()=>Vy,Yy=e=>{Vy=e,Ky.forEach(e=>e());},Xy=e=>(Ky.add(e),()=>Ky.delete(e)),Jy=()=>Vy;function ev(e,t,n){if(!t)return;const r=t.getSessionId(),o=e.getConversations();if(0===o.length)return void Gi(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(Qy||(Qy=new Gy),Qy),[]),f=E(async()=>{if(!t)return;const e=await Zd(t);Yy(e.scrollTop),await ou({adapter:t,loadAll:true,allowShortCircuit:true}),await Gd(t),Gi(le("scrolledToTop"));},[t]),b=E(async()=>{if(!t)return;const e=await Zd(t);Yy(e.scrollTop),await Qd(t),Gi(le("scrolledToBottom"));},[t]),y=E(async()=>{if(!t)return;const e=Zy();if(null===e)return void Gi(le("noAnchor"));const n=(await Zd(t)).scrollTop;await Vd(t,e),Yy(n);},[t]),v=E(()=>{n&&(n.refresh(),Gi(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.findMountedActiveItemIndex(e);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"});Gi(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(()=>{Gi(le("syncingConversations")),window.dispatchEvent(new CustomEvent("ophel:refreshConversations"));},[]),q=E(()=>{s();},[s]),R=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 Gi(le("outlineDisabled"));!d?i():u&&h&&h(),window.__ophelPendingLocateOutline=true,window.dispatchEvent(new CustomEvent("ophel:locateOutline")),Gi(le("locatingOutline"));},[e,d,u,i,h]),F=E(()=>{if(!e?.features?.outline?.enabled)return void Gi(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 Gi(le("conversationsDisabled"));if(t?.isSharePage()||t?.isNewConversation())return void Gi(le("noConversationToLocate"));!d?i():u&&h&&h(),window.__ophelPendingLocateConversation=true,window.dispatchEvent(new CustomEvent("ophel:locateConversation")),Gi(le("locatingConversation"));},[t,e,d,u,i,h]),H=E(()=>{if(t?.startNewConversation())return;const e=mr(),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")||Gi(le("exportFailed"));}catch(vT){console.error("Export failed:",vT),Gi(le("exportFailed"));}else Gi(le("exportNeedOpenFirst"));},[r,t]),j=E(async()=>{if(!t)return;const e=t.getLatestReplyText();if(e)try{await navigator.clipboard.writeText(e),Gi(le("replyCopied"));}catch{Gi(le("copyFailed"));}else Gi(le("noReplyToCopy"));},[t]),G=E(()=>{g?g():Gi(le("scrollLockToggled"));},[g]),Q=E(()=>{if(p)p();else {const{settings:e,updateNestedSetting:t}=zi.getState();t("panel","panelMode","edge-snap"===(e?.panel?.panelMode??"edge-snap")?"floating":"edge-snap");}},[p]),V=E(()=>{if(!t)return;const e=t.getSiteId(),n=yi(zi.getState().settings,e),r=!n.enabled;zi.getState().updateDeepSetting("layout","zenMode",e,{...n,enabled:r}),Gi(le(r?"zenModeEnabledToast":"zenModeDisabledToast"));},[t]),K=E(()=>{if(!t)return;const e=t.findTextarea();e?(e.focus(),Gi(le("inputFocused"))):Gi(le("noTextarea"));},[t]),Z=E(()=>{if(!t)return;if(t.stopGeneration())return void Gi(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 Gi(le("generationStopped"))}Gi(le("notGenerating"));},[t]),Y=E(()=>{r&&ev(r,t,"prev");},[r,t]),X=E(()=>{r&&ev(r,t,"next");},[r,t]),J=E(async()=>{const e=t?.getLastCodeBlockText?.()||"";if(e.trim()){try{await navigator.clipboard.writeText(e),Gi(le("codeBlockCopied"));}catch{Gi(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 Gi(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),Gi(le("codeBlockCopied"));}catch{Gi(le("copyFailed"));}else Gi(le("noCodeBlock"));},[t]),ee=E(()=>{c?c():(q(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"shortcuts"}}));},100));},[c,q]),te=E(()=>{if(!t)return;t.clickModelSelector()||Gi(le("modelSelectorNotFound"));},[t]),ne=E(()=>{window.dispatchEvent(new CustomEvent("ophel:togglePromptQueue"));},[]),re=E((e,t)=>{q(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:e,subTab:t}}));},100);},[q]),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(()=>ni);return {platform:e}},void 0),t=await e.switchNextClaudeKey();if(t.success)Gi(le("claudeKeySwitched")+`: ${t.keyName}`,2e3);else if("claudeOnlyOneKey"===t.error)Gi(le("claudeOnlyOneKeyTip"),2e3);else if("noClaudeKeys"===t.error)Gi(le("noClaudeKeys"),2e3);else {const e=le(t.error);Gi(e!==t.error?e:t.error||le("operationFailed"),2e3);}}catch{Gi(le("operationFailed"),2e3);}else Gi(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={[gn]:f,[pn]:b,[mn]:y,[fn]:i,[bn]:Q,[yn]:a,[vn]:q,[xn]:B,[wn]:_,[Sn]:O,[Mn]:v,[Nn]:x,[qn]:()=>w(1),[Rn]:()=>w(2),[Pn]:()=>w(3),[Dn]:()=>w(4),[Bn]:()=>w(5),[$n]:()=>w(6),[Cn]:S,[Tn]:C,[kn]:k,[In]:M,[Ln]:I,[En]:z,[An]:F,[_n]:H,[On]:N,[zn]:U,[Fn]:Y,[Un]:X,[Hn]:W,[Wn]:j,[jn]:J,[Gn]:G,[Qn]:V,[Vn]:K,[Kn]:R,[Zn]:Z,[Xn]:ee,[Jn]:te,[er]:oe,[tr]:ce,[nr]:ie,[rr]:ae,[or]:se,[Yn]:ne};return m.registerAll(e),m.startListening(),()=>{m.stopListening(),m.clearAll();}},[m,f,b,y,i,a,Q,q,B,_,O,v,x,w,S,C,k,M,I,z,F,H,N,U,Y,X,W,j,J,G,V,K,R,Z,ee,oe,te,ce,ie,ae,se,ne]),m}const nv="ophel",rv="Ophel Atlas",ov=GM_info?.script?.version??"1.0.0",iv="undefined"!=typeof window&&window.__OPHEL_USERSCRIPT_ASSET_URLS__?.icon||"",av={version:"1.1.2",date:"2026-06-30",notes:{en:"### 🚀 New Features\n\n- **Gemini Canvas document export** — Gemini Canvas export now supports regular document Canvas panels, so article Canvas content is included in conversation exports and Canvas Markdown copy/download actions. (#736)\n\n### ✨ Improvements\n\n- **Long conversation export loading** — Gemini and Qwen Studio exports now load earlier lazy-loaded history before collecting messages, reducing missed content in long conversation exports. (#739)\n\n### 🐛 Bug Fixes\n\n- **AI Studio model lock in userscript** — Fixed issue where the AI Studio model lock feature on the options page couldn't fetch the model list in the userscript build because it tried to use the background script proxy which doesn't exist in userscripts. Now it directly calls the adapter in userscript mode. (#733)",zh:"### 🚀 新增功能\n\n- **Gemini Canvas 文档导出** — Gemini Canvas 导出现在支持普通文档 Canvas 面板,会把文章类 Canvas 正文写入对话导出和 Canvas Markdown 复制/下载结果。(#736)\n\n### ✨ 功能优化\n\n- **长对话导出加载** — Gemini 和 Qwen Studio 导出现在会先加载更早的懒加载历史再收集消息,减少长对话导出遗漏内容的情况。(#739)\n\n### 🐛 问题修复\n\n- **AI Studio 油猴脚本模型锁定** — 修复了选项页的 AI Studio 模型锁定功能在油猴脚本中无法获取模型列表的问题。原因是油猴脚本没有后台代理,现在改为在油猴模式下直接调用适配器获取模型列表。(#733)"},fullChangelogUrls:{en:"https://ophel.app/docs/changelog",zh:"https://ophel.app/docs/zh/changelog"},media:[]},sv=new Set(["zh-CN","zh-TW"]),lv=e=>sv.has(se(e))?"zh":"en",cv=(e,t)=>e[lv(t)],dv="ophel:releaseNotesState";let uv=false;const hv=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},gv=({children:e,onClose:t})=>{L(()=>{(()=>{if(uv)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),uv=true;})();const e=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t]);const n=qe("div",{className:"conversations-dialog-overlay",...ms,onClick:t,children:qe("div",{className:"conversations-dialog",onClick:e=>e.stopPropagation(),children:e})});return gd(n,document.body)},pv=({title:e,message:t,confirmText:n,cancelText:r,danger:o,onConfirm:i,onCancel:a})=>Re(gv,{onClose:a,children:[ qe("div",{className:"conversations-dialog-title",children:e}), qe("div",{className:"conversations-dialog-message",children:t}), Re("div",{className:"conversations-dialog-buttons",children:[ qe(xb,{variant:"secondary",onClick:a,children:r||le("cancel")}), qe(xb,{variant:o?"danger":"primary",onClick:i,children:n||le("confirm")})]})]}),mv=({folder:e,onConfirm:t,onCancel:n})=>{const r=e?.icon||"📁",[o,i]=_(e?.name.replace(e.icon,"").trim()||""),[a,s]=_(r),[l,c]=_(Xr.includes(r)?r:null),d=$(null);L(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{const e=o.trim();e&&t(e,a);}; return Re(gv,{onClose:n,children:[ qe("div",{className:"conversations-dialog-title",children:le(e?"conversationsRename":"conversationsAddFolder")}), Re("div",{className:"conversations-dialog-section",children:[ qe("label",{children:le("conversationsIcon")}), Re("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:[ qe("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:le("conversationsCustomIcon")}), qe("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&&!Xr.includes(t)?c(null):Xr.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)"}})]}), qe("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:Xr.map(e=>qe("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))})]}), Re("div",{className:"conversations-dialog-section",children:[ qe("label",{children:le("conversationsFolderName")}), qe("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()})]}), Re("div",{className:"conversations-dialog-buttons",children:[ qe(xb,{variant:"secondary",onClick:n,children:le("cancel")}), qe(xb,{variant:"primary",onClick:u,children:le("confirm")})]})]})},fv=({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 Re(gv,{onClose:o,children:[ qe("div",{className:"conversations-dialog-title",children:e}), qe("div",{className:"conversations-dialog-section",children:qe("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()})}), Re("div",{className:"conversations-dialog-buttons",children:[ qe(xb,{variant:"secondary",onClick:o,children:le("cancel")}), qe(xb,{variant:"primary",onClick:l,children:le("confirm")})]})]})},bv=({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||hv(e).toLowerCase().includes(s.toLowerCase()))); return Re(gv,{onClose:i,children:[ qe("div",{className:"conversations-dialog-title",children:r||le("conversationsMoveTo")}), Re("div",{style:{display:"flex",gap:"8px",marginBottom:"12px"},children:[ qe("input",{ref:c,type:"text",className:"conversations-dialog-input",style:{flex:1},placeholder:le("conversationsSearchFolder"),value:s,onChange:e=>l(e.target.value)}),a&&qe(xb,{variant:"primary",style:{padding:"8px 12px"},onClick:()=>{i(),a();},title:le("conversationsAddFolder"),children:"+"})]}), Re("div",{className:"conversations-folder-select-list",children:[d.map(e=>Re("div",{id:`folder-select-${e.id}`,className:"conversations-folder-select-item",onClick:()=>o(e.id),children:[e.icon," ",hv(e)]},e.id)),0===d.length&&qe("div",{style:{padding:"16px",textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)"},children:le("conversationsNoSearchResult")})]}), qe("div",{className:"conversations-dialog-buttons",children:qe(xb,{variant:"secondary",onClick:i,children:le("cancel")})})]})},yv=({tags:e,conv:t,onCancel:n,onCreateTag:r,onUpdateTag:o,onDeleteTag:i,onSetConversationTags:a,onRefresh:s})=>{const[l,c]=_(null),[d,u]=_(""),[h,g]=_(Jr[0]),[p,m]=_(Jr[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 Re(gv,{onClose:n,children:[ Re("div",{className:"conversations-dialog-title",style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ qe("span",{children:le("conversationsManageTags")}), qe(Sd,{content:le("close"),children:qe("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:qe($e,{size:18})})})]}), Re("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",marginBottom:"16px",background:"var(--gh-bg-secondary, #fafafa)"},children:[ Re("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:[ qe("span",{children:le(t?"conversationsSelectTag":"conversationsExistingTags")}), Re("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #9ca3af)"},children:[e.length," 个"]})]}), qe("div",{style:{maxHeight:"320px",overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none"},children:0===e.length?qe("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 Re("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:[ Re("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t&&qe("input",{type:"checkbox",checked:n,onChange:()=>{},onClick:e=>e.stopPropagation(),style:{cursor:"pointer",width:"16px",height:"16px",accentColor:e.color}}), Re("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&&qe(Ht,{size:10})]})]}), Re("div",{style:{display:"flex",gap:"2px"},children:[ qe(Sd,{content:le("edit"),children:qe("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:qe(Ht,{size:14})})}), qe(Sd,{content:le("delete"),children:qe("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:qe($e,{size:18})})})]})]},e.id)})})]}), Re("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:[ Re("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:[ qe("span",{children:le(l?"conversationsEditTag":"conversationsNewTag")}),l&&qe("button",{style:{background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"11px",padding:"2px 6px"},onClick:()=>{c(null),u(""),M(Jr[0]);},children:le("conversationsCancelEdit")})]}), qe("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}}), Re("div",{style:{marginBottom:"12px",position:"relative"},children:[ Re("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:[ qe("div",{style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h,border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",flexShrink:0}}), qe("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #666)",flex:1},children:le(x?"conversationsCollapseColor":"conversationsSelectColor")}), qe(Dt,{size:16,color:"#9ca3af",style:{transition:"transform 0.2s",transform:x?"rotate(180deg)":"rotate(0deg)"}})]}),x&&Re("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:[ qe("div",{style:{display:"grid",gridTemplateColumns:"repeat(10, 1fr)",gap:"6px",marginBottom:"12px"},children:Jr.map(e=>qe(Sd,{content:e,children:qe("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))}), Re("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Re("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:Jr.includes(h.toUpperCase())?"2px solid transparent":"2px solid #666",flexShrink:0},children:[ qe("div",{style:{width:"100%",height:"100%",background:Jr.includes(h.toUpperCase())?"conic-gradient(from 180deg, red, yellow, lime, aqua, blue, magenta, red)":h}}), qe("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"}})]}), Re("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:[ qe("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #6b7280)",marginRight:"6px",fontFamily:"monospace",fontWeight:600},children:"HEX"}), qe("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"}})]})]})]})]}), qe(xb,{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&&qe(pv,{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)})]})},vv="https://chromewebstore.google.com/detail/ai-chat-organizer-outline/lpcohdfbomkgepfladogodgeoppclakd",xv="https://microsoftedge.microsoft.com/addons/detail/ophel-atlas-ai-chat-navi/ffpenkdeifijngifjmbbpijfpdhlolga",wv="https://addons.mozilla.org/firefox/addon/ophel-ai-chat-enhancer/",Sv="https://greasyfork.org/scripts/563646-ophel-ai-chat-page-enhancer",Cv="https://scriptcat.org/script-show-page/6519",kv=()=>({url:Sv,icon:qe(zt,{size:14}),label:le("reviewBtn")}),Tv=()=>{const{settings:e,setSettings:t}=zi();if(!Fi()||!e||e.hasAgreedToTerms)return null; return Re("div",{className:"disclaimer-modal-overlay",children:[ Re("div",{className:"disclaimer-modal",children:[ Re("div",{className:"disclaimer-header",children:[ qe("img",{src:iv,alt:"Ophel",className:"disclaimer-icon-img"}), Re("div",{className:"disclaimer-slogan-container",children:[ qe("span",{className:"sparkle","aria-hidden":"true",children:"✨"}), qe("h2",{className:"disclaimer-title",children:le("welcomeSlogan")}), qe("span",{className:"sparkle","aria-hidden":"true",children:"✨"})]})]}), Re("div",{className:"disclaimer-content",children:[ Re("div",{className:"disclaimer-section",children:[ qe("p",{children:le("disclaimerText")}), qe("p",{className:"disclaimer-warning",children:le("disclaimerWarning")})]}), Re("div",{className:"disclaimer-section privacy-section",children:[ Re("div",{className:"privacy-header",children:[ qe(ft,{size:20,className:"privacy-icon"}), qe("h3",{className:"privacy-title",children:le("privacyTitle")})]}), qe("p",{className:"privacy-content",children:le("privacyText")})]}), Re("div",{className:"disclaimer-section quote-section",children:[ qe("p",{className:"disclaimer-quote-text",children:le("communityMotto")}), Re("div",{className:"action-row",children:[ Re("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"star-btn",children:[ qe(gt,{size:18}), qe("span",{children:le("giveStar")})]}), Re("a",{href:kv().url,target:"_blank",rel:"noopener noreferrer",className:"star-btn review-btn",children:[kv().icon, qe("span",{children:kv().label})]})]}), Re("div",{className:"secondary-links",children:[ qe("a",{href:"https://github.com/urzeye/ophel/pulls",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"PR"}), qe("span",{className:"divider",children:"/"}), qe("a",{href:"https://github.com/urzeye/ophel/issues",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"Issue"})]})]})]}), qe("div",{className:"disclaimer-footer",children:qe("button",{className:"disclaimer-agree-btn",onClick:()=>{t({hasAgreedToTerms:true});},children:le("agreeButton")})})]}), qe("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 `})]})},Ev=({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=Re("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&&qe("style",{children:"\n @keyframes gh-loading-spin {\n to { transform: rotate(360deg); }\n }\n "}), Re("div",{className:"gh-loading-content",style:s,children:[ qe("div",{className:"gh-loading-spinner",style:l,"aria-hidden":"true",children:a?null:"⏳"}), qe("div",{className:"gh-loading-text",style:c,children:t||le("loadingHistory")}), qe("div",{className:"gh-loading-hint",style:{color:"var(--gh-text-secondary, #9ca3af)",fontSize:"12px",textAlign:"center",lineHeight:1.5},children:n||le("loadingHint")}),i&&qe("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?gd(d,document.body):d},Av=({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?qe("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:qe("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)=>Re("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:[ qe("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}), qe("div",{style:{flex:1,display:"flex",flexDirection:"column",alignSelf:"center",gap:"2px"},children:qe("span",{style:{whiteSpace:"normal",wordBreak:"break-word",color:"var(--gh-text, #374151)"},children:e.text})})]},t))})}):null};function Mv(e,t,n){const r=le(e,{[t]:"___SC___"}).split("___SC___");return 1===r.length?r[0]:Re("span",{style:{display:"inline"},children:[r[0], qe("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 Iv(e,t,n){const r=e??sr,o=e=>{const o=r[e];if(void 0===o){const r=sr[e];return r?pr(r,t):n}return o?pr(o,t):n},i=(e=>{const n=r[e];if(void 0===n){const n=sr[e];return n?pr(n,t):null}return n?pr(n,t):null})("togglePanelMode");return [{icon:"👻",text:Mv("tip1","modifier",t?"⌘ Cmd":"Ctrl")},{icon:"↔️",text:i?Mv("featureTip-panel-mode-toggle-path","shortcut",i):le("featureTip-panel-mode-toggle-path-dblclick")},{icon:"🔍",text:Mv("tip4","shortcut",o("openGlobalSearch"))},{icon:"🚀",text:Mv("tip3","shortcut",o("showShortcuts"))},{icon:"📋",text:Mv("tip5","shortcut",o("copyLatestReply"))},{icon:"🧭",text:Mv("tip6","shortcut",o("prevHeading")+"/"+o("nextHeading"))}]}const Lv=10;const Nv=({size:e=18,color:t="currentColor",className:n=""})=>qe("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:qe("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 qv=false;const Rv=({anchorEl:e,anchorPoint:t,onClose:n,children:r})=>{const o=$(null),[i,a]=_(null);if(L(()=>{if((()=>{if(qv)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),qv=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=qe("div",{ref:o,className:"conversations-folder-menu",...ms,style:{position:"fixed",top:i?`${i.top}px`:"-9999px",left:i?`${i.left}px`:"-9999px",zIndex:2147483647,pointerEvents:"auto"},children:r});return gd(s,document.body)},Pv=({onClick:e,danger:t,children:n})=>qe("button",{onClick:e,style:t?{color:"var(--gh-text-danger, #ef4444)"}:void 0,children:n}),Dv=({folder:e,anchorEl:t,onClose:n,onRename:r,onDelete:o})=>Re(Rv,{anchorEl:t,onClose:n,children:[ qe(Pv,{onClick:()=>{n(),r();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsRename")}), qe(Nv,{size:13})]})}), qe(Pv,{danger:true,onClick:()=>{n(),o();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsDelete")}), qe(Wt,{size:13})]})})]}),Bv=({conversation:e,anchorEl:t,anchorPoint:n,onClose:r,onOpenInNewTab:o,onRename:i,onTogglePin:a,onSetTags:s,onMoveTo:l,onExport:c,onDelete:d})=>Re(Rv,{anchorEl:t,anchorPoint:n,onClose:r,children:[ qe(Pv,{onClick:()=>{r(),o();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsOpenInNewTab")}), qe(ln,{size:13})]})}), qe(Pv,{onClick:()=>{r(),i();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsRename")}), qe(Nv,{size:13})]})}), qe(Pv,{onClick:()=>{r(),a();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:e.pinned?le("conversationsUnpin"):le("conversationsPin")}), qe(jt,{size:13,filled:e.pinned})]})}), qe(Pv,{onClick:()=>{r(),s();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsSetTags")}), qe($t,{size:13})]})}), qe(Pv,{onClick:()=>{r(),l();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsMoveTo")}), qe(Oe,{size:13})]})}), qe(Pv,{onClick:()=>{r(),c();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("export")}), qe(Ye,{size:13})]})}), qe(Pv,{danger:true,onClick:()=>{r(),d();},children:Re("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ qe("span",{children:le("conversationsDelete")}), qe(Wt,{size:13})]})})]}),$v=({anchorEl:e,anchorPoint:t,onClose:n,onExportMarkdown:r,onExportJSON:o,onExportTXT:i,onSegmentedExport:a})=>Re(Rv,{anchorEl:e,anchorPoint:t,onClose:n,children:[ qe(Pv,{onClick:()=>{n(),r();},children:Re("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ qe(Vt,{size:14}), qe("span",{children:le("exportToMarkdown")})]})}), qe(Pv,{onClick:()=>{n(),o();},children:Re("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ qe(Kt,{size:14}), qe("span",{children:le("exportToJSON")})]})}), qe(Pv,{onClick:()=>{n(),i();},children:Re("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ qe(Zt,{size:14}), qe("span",{children:le("exportToTXT")})]})}),a&&Re(Ne,{children:[ qe("div",{style:{height:"1px",background:"var(--gh-border, #e5e7eb)",margin:"3px 4px"}}), qe(Pv,{onClick:()=>{n(),a();},children:Re("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ qe(Xe,{size:14}), qe("span",{children:le("segmentedExportMenuItem")})]})})]})]});let _v=false;function Ov(e,t){const n=new Set,r=new Map(t.map(e=>[e.index,e.id]));return e.split(",").map(e=>e.trim()).filter(Boolean).forEach(e=>{const o=/^(\d+)\s*-\s*(\d+)$/.exec(e);if(o){return void((e,r)=>{const o=Math.min(e,r),i=Math.max(e,r);t.forEach(e=>{e.indexi||n.add(e.id);});})(Number(o[1]),Number(o[2]))}const i=Number(e),a=Number.isFinite(i)?r.get(i):void 0;a&&n.add(a);}),n}const zv=({draft:e,isExporting:t=false,onCancel:n,onExport:r})=>{const[o,i]=_(()=>new Set(e.segments.map(e=>e.id))),[a,s]=_(""),[l,c]=_(""),[d,u]=_("merged-markdown");L(()=>{!function(){if(_v)return;const e=document.createElement("style");e.id="gh-segmented-export-dialog-styles",e.textContent="\n .gh-segmented-export-dialog {\n width: min(760px, calc(100vw - 28px));\n max-width: 760px;\n height: min(680px, calc(100vh - 36px));\n padding: 0;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n border-radius: 10px;\n }\n .gh-segmented-export-header {\n padding: 16px 18px 12px;\n border-bottom: 1px solid var(--gh-border, #e5e7eb);\n }\n .gh-segmented-export-title-row,\n .gh-segmented-export-toolbar,\n .gh-segmented-export-footer {\n display: flex;\n align-items: center;\n gap: 10px;\n }\n .gh-segmented-export-title-row {\n justify-content: space-between;\n min-width: 0;\n }\n .gh-segmented-export-title {\n font-size: 16px;\n font-weight: 650;\n color: var(--gh-text, #1f2937);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .gh-segmented-export-count {\n flex: 0 0 auto;\n font-size: 12px;\n color: var(--gh-text-secondary, #6b7280);\n }\n .gh-segmented-export-toolbar {\n margin-top: 12px;\n flex-wrap: wrap;\n }\n .gh-segmented-export-input,\n .gh-segmented-export-select {\n height: 34px;\n border: 1px solid var(--gh-input-border, #d1d5db);\n border-radius: 7px;\n background: var(--gh-input-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n font-size: 13px;\n box-sizing: border-box;\n }\n .gh-segmented-export-input {\n padding: 0 10px;\n }\n .gh-segmented-export-search {\n flex: 1 1 220px;\n min-width: 160px;\n }\n .gh-segmented-export-range {\n flex: 0 1 150px;\n min-width: 120px;\n }\n .gh-segmented-export-select {\n flex: 0 0 180px;\n padding: 0 8px;\n }\n .gh-segmented-export-input:focus,\n .gh-segmented-export-select:focus {\n outline: none;\n border-color: var(--gh-primary, #4285f4);\n box-shadow: 0 0 0 2px color-mix(in srgb, var(--gh-primary, #4285f4) 18%, transparent);\n }\n .gh-segmented-export-button {\n height: 34px;\n padding: 0 10px;\n border: 1px solid var(--gh-border, #d1d5db);\n border-radius: 7px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #374151);\n font-size: 12px;\n cursor: pointer;\n white-space: nowrap;\n }\n .gh-segmented-export-button:hover:not(:disabled) {\n background: var(--gh-hover, #f3f4f6);\n }\n .gh-segmented-export-button:disabled {\n opacity: 0.55;\n cursor: not-allowed;\n }\n .gh-segmented-export-list {\n flex: 1 1 auto;\n overflow-x: hidden;\n overflow-y: auto;\n padding: 8px;\n background: color-mix(in srgb, var(--gh-bg, #ffffff) 92%, var(--gh-hover, #f3f4f6));\n scrollbar-color: rgba(107, 114, 128, 0.42) transparent;\n scrollbar-width: thin;\n }\n .gh-segmented-export-list::-webkit-scrollbar {\n width: 8px;\n height: 0;\n }\n .gh-segmented-export-list::-webkit-scrollbar-track {\n background: transparent;\n }\n .gh-segmented-export-list::-webkit-scrollbar-thumb {\n background: rgba(107, 114, 128, 0.34);\n background: color-mix(in srgb, var(--gh-text-tertiary, #9ca3af) 52%, transparent);\n border: 2px solid transparent;\n border-radius: 999px;\n background-clip: content-box;\n }\n .gh-segmented-export-list::-webkit-scrollbar-thumb:hover {\n background: rgba(107, 114, 128, 0.52);\n background: color-mix(in srgb, var(--gh-text-secondary, #6b7280) 64%, transparent);\n background-clip: content-box;\n }\n .gh-segmented-export-row {\n box-sizing: border-box;\n width: 100%;\n max-width: 100%;\n min-width: 0;\n display: grid;\n grid-template-columns: 28px 42px minmax(0, 1fr);\n gap: 8px;\n padding: 10px;\n border: 1px solid transparent;\n border-radius: 8px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n text-align: left;\n cursor: pointer;\n overflow: hidden;\n }\n .gh-segmented-export-row + .gh-segmented-export-row {\n margin-top: 6px;\n }\n .gh-segmented-export-row:hover {\n border-color: var(--gh-border, #e5e7eb);\n }\n .gh-segmented-export-row.gh-segmented-export-selected {\n border-color: color-mix(in srgb, var(--gh-primary, #4285f4) 45%, var(--gh-border, #e5e7eb));\n background: color-mix(in srgb, var(--gh-primary, #4285f4) 8%, var(--gh-bg, #ffffff));\n }\n .gh-segmented-export-checkbox {\n width: 16px;\n height: 16px;\n margin: 2px 0 0;\n accent-color: var(--gh-primary, #4285f4);\n }\n .gh-segmented-export-index {\n font-variant-numeric: tabular-nums;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 12px;\n line-height: 18px;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .gh-segmented-export-segment-main {\n min-width: 0;\n overflow: hidden;\n }\n .gh-segmented-export-segment-title {\n display: block;\n min-width: 0;\n font-size: 13px;\n font-weight: 600;\n line-height: 1.35;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .gh-segmented-export-meta,\n .gh-segmented-export-preview {\n display: block;\n font-size: 12px;\n color: var(--gh-text-secondary, #6b7280);\n line-height: 1.45;\n }\n .gh-segmented-export-meta {\n margin-top: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .gh-segmented-export-preview {\n margin-top: 6px;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n overflow-wrap: anywhere;\n }\n .gh-segmented-export-empty {\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 13px;\n }\n .gh-segmented-export-footer {\n justify-content: space-between;\n flex-wrap: wrap;\n padding: 12px 18px 16px;\n border-top: 1px solid var(--gh-border, #e5e7eb);\n }\n .gh-segmented-export-footer-actions {\n display: flex;\n flex: 1 1 280px;\n flex-wrap: wrap;\n justify-content: flex-end;\n gap: 8px;\n }\n .gh-segmented-export-primary {\n border-color: transparent;\n background: var(--gh-primary, #4285f4);\n color: white;\n }\n .gh-segmented-export-primary:hover:not(:disabled) {\n background: color-mix(in srgb, var(--gh-primary, #4285f4) 86%, black);\n }\n",document.head.appendChild(e),_v=true;}();},[]);const h=D(()=>{const t=a.trim().toLowerCase();return t?e.segments.filter(e=>e.title.toLowerCase().includes(t)||e.preview.toLowerCase().includes(t)):e.segments},[e.segments,a]),g=o.size,p=e=>{i(t=>{const n=new Set(t);return h.forEach(t=>{e?n.add(t.id):n.delete(t.id);}),n});}; return Re(bb,{onClose:n,closeOnOverlayClick:!t,closeOnEscape:!t,dialogClassName:"gh-segmented-export-dialog",dialogStyle:{maxWidth:"760px"},children:[ Re("div",{className:"gh-segmented-export-header",children:[ Re("div",{className:"gh-segmented-export-title-row",children:[ qe("div",{className:"gh-segmented-export-title",children:le("segmentedExportTitle")}), qe("div",{className:"gh-segmented-export-count",children:le("segmentedExportDetected").replace("{count}",String(e.segments.length))})]}), Re("div",{className:"gh-segmented-export-toolbar",children:[ qe("input",{className:"gh-segmented-export-input gh-segmented-export-search",value:a,placeholder:le("segmentedExportSearchPlaceholder"),onChange:e=>s(e.target.value)}), qe("input",{className:"gh-segmented-export-input gh-segmented-export-range",value:l,placeholder:le("segmentedExportRangePlaceholder"),onChange:e=>c(e.target.value)}), qe("button",{className:"gh-segmented-export-button",onClick:()=>{const t=Ov(l,e.segments);i(t);},children:le("segmentedExportApplyRange")}), qe("button",{className:"gh-segmented-export-button",onClick:()=>p(true),children:le("segmentedExportSelectVisible")}), qe("button",{className:"gh-segmented-export-button",onClick:()=>p(false),children:le("segmentedExportClearVisible")}), qe("button",{className:"gh-segmented-export-button",onClick:()=>{i(e=>{const t=new Set(e);return h.forEach(e=>{t.has(e.id)?t.delete(e.id):t.add(e.id);}),t});},children:le("segmentedExportInvertVisible")})]})]}), qe("div",{className:"gh-segmented-export-list",children:0===h.length?qe("div",{className:"gh-segmented-export-empty",children:le("segmentedExportNoMatches")}):h.map(e=>{const t=o.has(e.id); return Re("label",{className:"gh-segmented-export-row"+(t?" gh-segmented-export-selected":""),children:[ qe("input",{className:"gh-segmented-export-checkbox",type:"checkbox",checked:t,onChange:()=>{return t=e.id,void i(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n});var t;}}), qe("span",{className:"gh-segmented-export-index",children:e.index}), Re("span",{className:"gh-segmented-export-segment-main",children:[ qe("span",{className:"gh-segmented-export-segment-title",children:e.title}), qe("span",{className:"gh-segmented-export-meta",children:le("segmentedExportSegmentMeta").replace("{users}",String(e.userMessageCount)).replace("{assistants}",String(e.assistantMessageCount)).replace("{chars}",String(e.characterCount))}), qe("span",{className:"gh-segmented-export-preview",children:e.preview})]})]},e.id)})}), Re("div",{className:"gh-segmented-export-footer",children:[ qe("div",{className:"gh-segmented-export-count",children:le("segmentedExportSelected").replace("{selected}",String(g)).replace("{total}",String(e.segments.length))}), Re("div",{className:"gh-segmented-export-footer-actions",children:[ Re("select",{className:"gh-segmented-export-select",value:d,onChange:e=>u(e.target.value),children:[ qe("option",{value:"zip-markdown",children:le("segmentedExportModeZip")}), qe("option",{value:"merged-markdown",children:le("segmentedExportModeMerged")}), qe("option",{value:"clipboard",children:le("segmentedExportModeClipboard")})]}), qe("button",{className:"gh-segmented-export-button",disabled:t,onClick:n,children:le("cancel")}), qe("button",{className:"gh-segmented-export-button gh-segmented-export-primary",disabled:t||0===g,onClick:()=>r(Array.from(o),d),children:le(t?"exportOverlayPreparing":"segmentedExportExportSelected")})]})]})]})};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 Fv=30,Uv=()=>{const e=le("conversationsInbox");return "conversationsInbox"===e?"Inbox":e},Hv=e=>{if("inbox"===e.id)return Uv();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},Wv=(e,t)=>{if(!t)return e;return e.split(new RegExp(`(${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`,"gi")).map((e,n)=>e.toLowerCase()===t.toLowerCase()?qe("span",{className:"conversations-highlight",children:e},n):e)},jv=({manager:e,onInteractionStateChange:t})=>{const n={[xo]:"ChatGLM",[No]:"Z.ai",[Mo]:"Qianwen",[Io]:"Qwen Studio",[To]:"ima"},{settings:r}=zi(),o=tf(e=>e.conversations),a=tf(e=>e.lastUsedFolderId),s=lf(e=>e.folders),l=hf(e=>e.tags),[c,d]=_([]),[u,h]=_({}),[g,p]=_([]),[m,f]=_("inbox"),[b,y]=_(null),[v,x]=_(false),[w,S]=_(new Set),[C,k]=_(false),[T,A]=_(false),[M,I]=_(""),[N,q]=_(false),[R,P]=_(new Set),[B,O]=_(null),[z,F]=_(false),[U,H]=_(false),[W,j]=_(false),G=de(),Q=e.siteAdapter?.getSiteId?.(),V=!(!Q||!n[Q]),K=Q?n[Q]||Q:"",Z=le("conversationsUnsupportedTitle",{site:K}),Y=le("conversationsUnsupportedDesc"),X=le("conversationsUnsupportedSync",{site:K}),J=V,[ee,te]=_(null),[ne,re]=_(null),[oe,ie]=_(null),[ae,se]=_(false),[ce,ue]=_(null),[he,ge]=_(null),[pe,me]=_(null),[fe,be]=_(null),ye=$(null),ve=$(null),xe=$(null),we=$(null),Se=$(null),Ce=$(null),ke=$(null);L(()=>{const e=xe.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>{j(e.clientWidth<=340);};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);const Te=E(async()=>{d([...e.getFolders()]),h({...e.getAllConversations()}),p([...e.getTags()]),f(e.getLastUsedFolderId());},[e]);L(()=>{Te();},[Te,o,s,a,l]),L(()=>{const t=e.onDataChange(()=>{Te();});return ()=>t()},[e,Te]);const Ee=E(e=>{if(!e&&!N&&0===R.size)return void O(null);const t=new Set,n=new Set,r=new Map,o=e.toLowerCase();c.forEach(n=>{e&&Hv(n).toLowerCase().includes(o)&&t.add(n.id);}),Object.values(u).forEach(t=>{let i=true;if(e&&!t.title.toLowerCase().includes(o)&&(i=false),N&&!t.pinned&&(i=false),R.size>0){const e=t.tagIds?.some(e=>R.has(e));e||(i=false);}i&&(n.add(t.id),r.set(t.id,t.folderId));}),O({folderMatches:t,conversationMatches:n,conversationFolderMap:r,totalCount:n.size});},[c,u,N,R]);L(()=>{Ee(M);},[N,R,Ee,M]),L(()=>{if(!z)return;const e=e=>{const t=e.composedPath(),n=Ce.current&&t.includes(Ce.current),r=ke.current&&t.includes(ke.current);n||r||F(false);},t=setTimeout(()=>{document.addEventListener("click",e,true);},0);return ()=>{clearTimeout(t),document.removeEventListener("click",e,true);}},[z]),L(()=>{const e=!!(ne||ee||oe||z||U||T||ae);t?.(e);},[ne,ee,oe,z,U,T,ae,t]);const Ae=E(t=>t?.id?t.id:w.size>0?Array.from(w)[0]:e.siteAdapter.getSessionId()||null,[e,w]),Me=E(async t=>{const n=Ae(t);if(n)if(e.siteAdapter.getSessionId()===n){se(true);try{const t=await e.prepareSegmentedConversationExport(n);if(!t||0===t.segments.length)return void Gi(le("segmentedExportNoSegments"));ie(t);}finally{se(false);}}else Gi(le("exportNeedOpenFirst"));else Gi(le("exportNeedOpenFirst"));},[Ae,e]),Ie=E(async(t,n)=>{if(oe){se(true);try{await e.exportSegmentedConversation(oe,t,n)&&ie(null);}finally{se(false);}}},[e,oe]),Le=D(()=>{const e=new Map;return g.forEach(t=>e.set(t.id,t)),e},[g]),Pe=D(()=>{const t=e.getSidebarConversationOrder(),n=new Map;for(let e=0;eB.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},[u,B,e]),De=$(Pe);De.current=Pe;const Be=e=>Pe.get(e)||[],[_e,ze]=_({}),Fe=$(new Map),Ue=E(async()=>{if(V)Gi(X);else {k(true);try{const t=!1!==await(e.siteAdapter?.loadAllConversations?.()),n=e.siteAdapter?.getConversationList?.()?.length||0,{newCount:r,updatedCount:o,deletedCount:i}=await e.syncConversations(m,!1,{syncDeleted:t});Te(),Gi(0===n?le("conversationsSyncNoSidebarItems"):le("conversationsSyncResult").replace("{scanned}",String(n)).replace("{added}",String(r)).replace("{updated}",String(o)).replace("{deleted}",String(i)));}finally{k(false);}}},[V,X,e,m,Te]),He=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 Ue();y(n.folderId);const r=(Pe.get(n.folderId)||[]).findIndex(e=>e.id===t);if(r>=0){const e=r+1;ze(t=>({...t,[n.folderId]:Math.max(t[n.folderId]||Fv,e)}));}setTimeout(()=>{const e=xe.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,Ue,Pe]);L(()=>{const e=()=>{window.__ophelPendingLocateConversation=false,He();};return window.__ophelPendingLocateConversation&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateConversation",e),()=>{window.removeEventListener("ophel:locateConversation",e);}},[He]),L(()=>{const e=()=>{Ue();};return window.addEventListener("ophel:refreshConversations",e),()=>{window.removeEventListener("ophel:refreshConversations",e);}},[Ue]);const We=()=>{S(new Set),x(false);},je=M||N||R.size>0,Ge=$(null);L(()=>{b!==Ge.current&&(Ge.current=b,b&&ze(e=>({...e,[b]:Math.max(e[b]??0,Fv)})));},[b]),L(()=>{if(B){const e=new Set(B.conversationFolderMap.values());ze(t=>{const n={...t};for(const r of e)r in n||(n[r]=Fv);return n});}},[B]);const Qe=$(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=De.current.get(t)?.length||0;ze(e=>{const n=e[t]||Fv,o=Math.min(n+Fv,r);return o===n?e:{...e,[t]:o}}),e.unobserve(n.target);}}},{rootMargin:"100px"});Qe.current=e;for(const[,t]of Fe.current)t&&e.observe(t);return ()=>e.disconnect()},[]);const Ve=E(t=>{v?S(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);},[v,e]),Ke=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?ti.openTab(t):Gi(le("operationFailed"));},[]),Ze=e=>{const t=Be(e);return t.length>0&&t.every(e=>w.has(e.id))},Xe=e=>{if(!B)return true;const t=B.folderMatches.has(e.id),n=Array.from(B.conversationFolderMap.values()).includes(e.id);return t||n},Je=D(()=>c.map(e=>{const t=Hv(e),n=`${e.icon?`${e.icon} `:""}${t}`.trim();return {value:e.id,title:n,label:Re(Ne,{children:[e.icon&&qe("span",{className:"conversations-folder-select-icon",children:e.icon}), qe("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}}),[c,G]); return Re(Ne,{children:[ qe(Ev,{isVisible:T,text:`${le("delete")}...`}), Re("div",{ref:xe,className:`conversations-content ${W?"is-narrow":""} ${pe||ce?"is-dragging-any":""}`,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[J&&qe("div",{className:"conversations-unsupported-mask","aria-hidden":"true",children:Re("div",{className:"conversations-unsupported-card",children:[ qe("div",{className:"conversations-unsupported-icon",children:"!"}), qe("div",{className:"conversations-unsupported-title",children:Z}), qe("div",{className:"conversations-unsupported-desc",children:Y})]})}), Re("div",{className:"conversations-toolbar",children:[ qe(Sd,{content:le("conversationsSelectFolder"),triggerStyle:{flex:1,minWidth:0},children:qe(kb,{className:"conversations-folder-select-dropdown",buttonClassName:"conversations-folder-select",menuClassName:"conversations-folder-select-menu",optionClassName:"conversations-folder-select-option",options:Je,value:m,ariaLabel:le("conversationsSelectFolder"),onOpenChange:H,onChange:t=>{f(t),e.setLastUsedFolder(t);}})}), qe(Sd,{content:le("conversationsSync"),children:qe("button",{className:"conversations-toolbar-btn sync",disabled:C||V,onClick:Ue,children:qe(C?kt:Tt,{size:18})})}), qe(Sd,{content:le("conversationsLocate"),children:qe("button",{className:"conversations-toolbar-btn locate",onClick:He,children:qe(ot,{size:18})})}), qe(Sd,{content:le("conversationsBatchMode"),children:qe("button",{className:"conversations-toolbar-btn batch-mode "+(v?"active":""),onClick:()=>{v&&S(new Set),x(!v);},children:qe(St,{size:18})})}), qe(Sd,{content:le("conversationsAddFolder"),children:qe("button",{className:"conversations-toolbar-btn add-folder",onClick:()=>{t?.(true),te({type:"folder"});},children:qe(Ct,{size:18})})})]}), Re("div",{className:"conversations-search-bar",children:[ Re("div",{className:"conversations-search-wrapper",style:{position:"relative"},children:[ qe("div",{className:"conversations-search-input-group",children:qe("input",{ref:we,type:"text",className:"conversations-search-input",placeholder:le("conversationsSearchPlaceholder"),value:M,onChange:e=>{return t=e.target.value,I(t),Se.current&&clearTimeout(Se.current),void(Se.current=setTimeout(()=>Ee(t),150));var t;}})}), qe(Sd,{content:le("conversationsFilterPinned"),children:qe("div",{className:"conversations-pin-filter-btn "+(N?"active":""),style:{userSelect:"none"},onClick:()=>q(!N),children:qe(jt,{size:16})})}), qe(Sd,{content:le("conversationsFilterByTags"),children:qe("div",{ref:ke,className:"conversations-tag-search-btn "+(R.size>0?"active":""),style:{userSelect:"none"},onClick:()=>{const e=!z;e&&t?.(true),F(e);},children:qe($t,{size:16})})}),z&&Re("div",{ref:Ce,className:"conversations-tag-filter-menu",children:[ qe("div",{className:"conversations-tag-filter-list",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:0===g.length?qe("div",{className:"conversations-tag-filter-item",style:{color:"var(--gh-text-tertiary, #9ca3af)",cursor:"default"},children:le("conversationsNoTags")}):g.map(e=>Re("div",{className:"conversations-tag-filter-item "+(R.has(e.id)?"selected":""),onClick:()=>{const t=new Set(R);t.has(e.id)?t.delete(e.id):t.add(e.id),P(t);},children:[ qe("span",{className:"conversations-tag-dot",style:{backgroundColor:e.color}}), qe("span",{children:e.name})]},e.id))}), qe("div",{className:"conversations-tag-filter-footer",children:qe("div",{className:"conversations-tag-filter-item conversations-tag-filter-action",onClick:()=>{F(false),t?.(true),te({type:"tagManager",conv:void 0});},children:le("conversationsManageTags")})})]}), qe(Sd,{content:le("conversationsClearAll"),children:qe("div",{className:"conversations-search-clear "+(je?"":"disabled"),onClick:je?()=>{I(""),q(false),P(new Set),O(null);}:void 0,children:qe($e,{size:14})})})]}),M&&B&&Re("div",{className:"conversations-result-bar visible",children:[B.totalCount," ",le("conversationsSearchResult")]})]}), qe("div",{className:"conversations-folder-list",children:0===c.filter(Xe).length?qe("div",{className:"conversations-empty",children:le(B?"conversationsNoSearchResult":"conversationsEmpty")}):c.filter(Xe).map((n,o)=>{const a=(s=n.id,B?Array.from(B.conversationFolderMap.values()).includes(s):b===s);var s;const l=(e=>Be(e).length)(n.id),d=Hv(n),h=r?.features?.conversations?.folderRainbow??false;let g="transparent";return n.isDefault?g="var(--gh-folder-bg-default)":h?g=`var(--gh-folder-bg-${o%8})`:a&&(g="var(--gh-folder-bg-expanded, rgba(59, 130, 246, 0.08))"),Re(i.Fragment,{children:[ Re("div",{className:["conversations-folder-item",a?"expanded":"",n.isDefault?"default":"",ce===n.id?"is-dragging":"",he===n.id&&ce!==n.id?"is-drag-over":"",fe===n.id?"is-drag-over-conv":""].filter(Boolean).join(" "),"data-folder-id":n.id,style:{background:g},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():(ue(n.id),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",n.id));},onDragEnd:()=>{ue(null),ge(null),ve.current=null;},onClick:()=>(e=>{y(b===e?null:e);})(n.id),onDragEnter:e=>{if(ce){if(n.isDefault||n.id===ce)return;e.preventDefault(),ve.current=n.id,ge(n.id);}else if(pe){const t=u[pe];t&&t.folderId!==n.id&&(e.preventDefault(),ye.current=n.id,be(n.id));}},onDragOver:e=>{if(ce){if(n.isDefault||n.id===ce)return;e.preventDefault(),e.dataTransfer.dropEffect="move",ve.current=n.id,ge(n.id);}else if(pe){const t=u[pe];t&&t.folderId!==n.id&&(e.preventDefault(),e.dataTransfer.dropEffect="move",ye.current=n.id,be(n.id));}},onDragLeave:e=>{const t=e.relatedTarget;if(!t||!e.currentTarget.contains(t))if(ce){const e=n.id;setTimeout(()=>{ve.current===e&&ge(null);},0);}else if(pe){const e=n.id;setTimeout(()=>{ye.current===e&&be(null);},0);}},onDrop:t=>{if(t.preventDefault(),ce){if(n.isDefault||n.id===ce)return;const t=c.filter(Xe).filter(e=>!e.isDefault),r=t.findIndex(e=>e.id===ce),o=t.findIndex(e=>e.id===n.id);if(-1===r||-1===o)return;const i=[...t],[a]=i.splice(r,1);i.splice(o,0,a);const s=c.filter(e=>!e.isDefault).filter(e=>!i.some(t=>t.id===e.id));e.reorderFolders([...i,...s].map(e=>e.id)),Te(),ue(null),ge(null),ve.current=null;}else if(pe){const t=u[pe];t&&t.folderId!==n.id&&(e.moveConversation(pe,n.id),Te()),me(null),be(null),ye.current=null;}},children:[ Re("div",{className:"conversations-folder-info",children:[v&&qe("input",{type:"checkbox",className:"conversations-folder-checkbox",checked:Ze(n.id),ref:e=>{e&&(e.indeterminate=(e=>{const t=Be(e),n=t.filter(e=>w.has(e.id));return n.length>0&&n.length((e,t)=>{const n=Be(e),r=new Set(w);t?n.forEach(e=>r.add(e.id)):n.forEach(e=>r.delete(e.id)),S(r);})(n.id,e.target.checked),onClick:e=>e.stopPropagation()}), qe("span",{className:"conversations-folder-icon",style:{userSelect:"none"},children:n.icon}), qe(Sd,{content:d,children:qe("span",{className:"conversations-folder-name",children:M&&B?.folderMatches.has(n.id)?Wv(d,M):d})})]}), Re("div",{className:"conversations-folder-controls",children:[ Re("span",{className:"conversations-folder-count",children:["(",l,")"]}), qe("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),re({type:"folder",folder:n,anchorEl:e.currentTarget});},children:qe(Rt,{size:20})})]})]}),a&&qe("div",{className:"conversations-list","data-folder-id":n.id,children:(()=>{const e=Be(n.id);if(0===e.length) return qe("div",{className:"conversations-list-empty",children:le("conversationsEmpty")});const r=_e[n.id]||Fv,o=e.slice(0,r),i=e.length>r; return Re(Ne,{children:[o.map(e=>qe(Gv,{conv:e,batchMode:v,isSelected:w.has(e.id),isNarrowLayout:W,searchQuery:M,searchResult:B,tagMap:Le,draggedConvId:pe,onConversationClick:Ve,onSelectionChange:S,onInteractionStateChange:t,onMenuChange:re,onDragStart:e=>{me(e),ye.current=null;},onDragEnd:()=>{me(null),be(null),ye.current=null;}},e.id)),i&&qe("div",{className:"conversations-load-more-sentinel","data-folder-id":n.id,ref:e=>{const t=Fe.current.get(n.id);t&&t!==e&&Qe.current?.unobserve(t),e?(Fe.current.set(n.id,e),Qe.current?.observe(e)):Fe.current.delete(n.id);},style:{height:"1px",margin:0,padding:0}})]})})()})]},n.id)})}),v&&w.size>0&&Re("div",{className:"conversations-batch-bar",children:[ qe("span",{className:"conversations-batch-info",children:le("batchSelected").replace("{n}",String(w.size))}), Re("div",{className:"conversations-batch-btns",children:[ qe(Sd,{content:le("exportToClipboard"),children:qe("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:async()=>{const t=Array.from(w)[0];await e.exportConversation(t,"clipboard");},children:qe(Nt,{size:16})})}), qe(Sd,{content:le("batchExport"),children:qe("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:e=>{t?.(true),re({type:"export",anchorEl:e.currentTarget});},children:qe(Ye,{size:16})})}), qe(Sd,{content:le("batchMove"),children:qe("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),te({type:"folderSelect",convIds:Array.from(w)});},children:qe(Oe,{size:16})})}), qe(Sd,{content:le("batchDelete"),children:qe("button",{className:"conversations-batch-btn danger",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),te({type:"confirm",title:le("batchDelete"),message:le("confirmDeleteSelectedConvs",{count:String(w.size)}),danger:true,onConfirm:async()=>{if(!T){te(null),A(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversations(Array.from(w));if(0===t.localDeletedCount)return void Gi(le("deleteError"));t.remoteAttemptedCount>0&&t.remoteFailedCount>0&&Gi(`已删除 ${t.localDeletedCount} 个,本地成功,云端失败 ${t.remoteFailedCount} 个`),We(),await Te();}finally{A(false);}}}});},children:qe(Wt,{size:16})})}), qe(Sd,{content:le("batchExit"),children:qe("button",{className:"conversations-batch-btn cancel",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:We,children:qe($e,{size:16})})})]})]})]}),"confirm"===ee?.type&&qe(pv,{title:ee.title,message:ee.message,danger:ee.danger,onConfirm:ee.onConfirm,onCancel:()=>te(null)}),"folder"===ee?.type&&qe(mv,{folder:ee.folder,onConfirm:async(t,n)=>{let r=null;if(ee.folder)await e.updateFolder(ee.folder.id,{name:t,icon:n});else {const o=await e.createFolder(t,n);o&&(r=o.id);}Te(),ee.returnToSelect?te({type:"folderSelect",conv:ee.returnToSelect.conv,convIds:ee.returnToSelect.convIds,activeFolderId:r||void 0}):te(null);},onCancel:()=>te(null)}),"rename"===ee?.type&&qe(fv,{title:le("conversationsRename"),currentValue:ee.conv.title,onConfirm:async t=>{await e.renameConversation(ee.conv.id,t),Te(),te(null);},onCancel:()=>te(null)}),"folderSelect"===ee?.type&&qe(bv,{folders:c,excludeFolderId:ee.conv?.folderId,activeFolderId:ee.activeFolderId,onSelect:async t=>{if(ee.conv)await e.moveConversation(ee.conv.id,t);else if(ee.convIds){for(const n of ee.convIds)await e.moveConversation(n,t);We();}Te(),te(null);},onCancel:()=>te(null),onCreateFolder:()=>te({type:"folder",returnToSelect:{conv:ee.conv,convIds:ee.convIds}})}),"tagManager"===ee?.type&&qe(yv,{tags:g,conv:ee.conv,onCancel:()=>te(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:()=>Te()}),"folder"===ne?.type&&qe(Dv,{folder:ne.folder,anchorEl:ne.anchorEl,onClose:()=>re(null),onRename:()=>{re(null),te({type:"folder",folder:ne.folder});},onDelete:()=>{re(null);const t=Hv(ne.folder),n=Uv(),r=le("conversationsDeleteConfirm",{folder:t,inbox:n});te({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(ne.folder.id),Te(),te(null);}});}}),"conversation"===ne?.type&&qe(Bv,{conversation:ne.conv,anchorEl:ne.anchorEl,anchorPoint:ne.anchorPoint,onClose:()=>re(null),onOpenInNewTab:()=>Ke(ne.conv),onRename:()=>{re(null),te({type:"rename",conv:ne.conv});},onTogglePin:async()=>{re(null),await e.togglePin(ne.conv.id),Te();},onSetTags:()=>{re(null),te({type:"tagManager",conv:ne.conv});},onMoveTo:()=>{re(null),te({type:"folderSelect",conv:ne.conv});},onExport:()=>{const e=ne.conv,t=ne.anchorEl,n=ne.anchorPoint;re({type:"export-conv",conv:e,anchorEl:t,anchorPoint:n});},onDelete:()=>{re(null),te({type:"confirm",title:le("conversationsDelete"),message:le("conversationsDeleteConvMsg",{title:ne.conv.title}),danger:true,onConfirm:async()=>{if(!T){te(null),A(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversation(ne.conv.id);if(!t.localDeleted)return void Gi(le("deleteError"));t.remoteAttempted&&!t.remoteSuccess&&Gi(le("deleteConvRemoteError")),await Te();}finally{A(false);}}}});}}),"export"===ne?.type&&qe($v,{anchorEl:ne.anchorEl,onClose:()=>re(null),onExportMarkdown:async()=>{re(null);const t=w.size>0?Array.from(w)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"markdown");},onExportJSON:async()=>{re(null);const t=w.size>0?Array.from(w)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"json");},onExportTXT:async()=>{re(null);const t=w.size>0?Array.from(w)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"txt");},onSegmentedExport:()=>{Me();}}),"export-conv"===ne?.type&&qe($v,{anchorEl:ne.anchorEl,anchorPoint:ne.anchorPoint,onClose:()=>re(null),onExportMarkdown:async()=>{re(null),await e.exportConversation(ne.conv.id,"markdown");},onExportJSON:async()=>{re(null),await e.exportConversation(ne.conv.id,"json");},onExportTXT:async()=>{re(null),await e.exportConversation(ne.conv.id,"txt");},onSegmentedExport:()=>{Me(ne.conv);}}),oe&&qe(zv,{draft:oe,isExporting:ae,onCancel:()=>{ae||ie(null);},onExport:Ie})]})},Gv=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 Re("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&&qe("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});}}), qe("div",{className:"conversations-item-main",children:Re("div",{className:"conversations-item-headline",children:[ qe(Sd,{content:e.title,triggerStyle:{flex:1,minWidth:0,overflow:"hidden",display:"block"},children:Re("span",{className:"conversations-item-title",style:{userSelect:"none"},children:[e.pinned&&qe(jt,{size:12,color:"var(--gh-primary, #3b82f6)",style:{display:"inline-block",marginRight:"4px",verticalAlign:"middle"}}),o&&i?.conversationMatches.has(e.id)?Wv(e.title||"无标题",o):e.title||"无标题"]})}),p.length>0&&Re("div",{className:"conversations-tag-list",children:[b.map(e=>qe("span",{className:"conversations-tag",style:{backgroundColor:e.color},children:e.name},e.id)),y>0&&qe(Sd,{content:qe("div",{className:"conversations-hidden-tags-tooltip",children:f.map(e=>Re("div",{className:"conversations-hidden-tag-item",children:[ qe("span",{className:"conversations-hidden-tag-dot",style:{backgroundColor:e.color}}), qe("span",{children:e.name})]},e.id))}),delay:120,triggerStyle:{display:"inline-flex"},children:Re("span",{className:"conversations-tag conversations-tag-more",children:["+",y]})})]})]})}), qe("div",{className:"conversations-item-meta",children:qe("button",{className:"conversations-item-menu-btn",title:le("more"),onClick:t=>{t.stopPropagation(),d?.(true),u({type:"conversation",conv:e,anchorEl:t.currentTarget});},children:qe(Rt,{size:20})})})]})});function Qv(e){return e.replace(/(^|\n)\s*>+\s?/g,"$1")}function Vv(e,t){const n=function(e){return Qv(e).replace(/^\s{0,3}#{1,6}\s+/,"").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\\([\\`*_[\]{}()#+\-.!|>])/g,"$1").replace(/[`*_~]/g,"").replace(/⁣/g,"").replace(/\s+/g," ").trim()}(Qv(e.replace(/\r\n?/g,"\n")).replace(/\n+/g," "));return !t||n.length<=t?n:`${n.slice(0,t).trim()}...`}function Kv(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=Vv(n[2]);a&&t.push({level:i,text:a});}return t}function Zv(e){return "#".repeat(Math.min(6,Math.max(1,e)))}function Yv(e,t){return 0===e.length||t<1?[]:e.flatMap(e=>e.level>t?[]:[`${Zv(e.level)} ${e.text}`])}function Xv(e,t){return `${Zv(1)} Q${t}. ${e}`}function Jv(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=Vv(a.content,120);e&&e.replace(/[\s⁣]/g,"").length>0&&(i+=1,o.push(Xv(e,i)));continue}const e=Kv(a.content);o.push(...Yv(e,n));}return 0===o.length?{text:"",count:0}:{text:o.join("\n\n"),count:o.length}}function ex(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 tx=e=>{let t=0;for(const n of e)t+=1,n.children.length>0&&(t+=tx(n.children));return t},nx=e=>"conversation"===e.kind?le("outlineSourceConversation"):"document"===e.kind?le("outlineSourceDocument"):e.label,rx=(e,t,n,r,o,i)=>{const a={},s=new WeakMap,l=new WeakSet,c={},d=new Map,u=e=>{const t=d.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(u(r)){n=true;break}return d.set(e.index,n),n},h=(e,d,g,p,m,f)=>{a[e.index]=d,s.set(e,g);const b=u(e);let y;if(i)if(b||f){const t=!r||e.isMatch||e.hasMatchedDescendant;y=!p&&t;}else y=false;else {const i=e.relativeLevel===n,a=e.relativeLevel<=t||m;if(i)y=!r||(e.isMatch||e.hasMatchedDescendant);else {const t=!r||e.isMatch||e.hasMatchedDescendant||m;y=r&&!o?t&&!p:r&&o?t&&a&&!p:a&&!p;}p&&(y=false);}e.forceVisible&&(y=true),c[e.index]=y,y&&l.add(e);const v=e.collapsed||p,x=e.forceExpanded||m,w=f||e.isBookmarked&&!(e=>!(!e.children||0===e.children.length)&&e.children.some(u))(e);e.children&&e.children.length>0&&e.children.forEach(t=>{h(t,e.index,e,v,x,w);});};return e.forEach(e=>h(e,null,null,false,false,false)),{parentMap:a,parentNodeMap:s,visibleMap:c,visibleNodeSet:l}},ox=(e,t)=>t||0!==e?t?e:Math.max(1,e):6,ix=Math.ceil(60),ax=(e,t)=>e.node.isUserQuery?{top:0===t?0:2,bottom:2}:{top:0,bottom:2},sx=(e,t,n)=>{const r=e.rowOffsets.length;if(0===r)return {start:0,end:0};const o=Math.max(n,420),i=((e,t)=>{if(0===e.length)return 0;let n=0,r=e.length-1,o=0;for(;n<=r;){const i=Math.floor((n+r)/2);e[i]<=t?(o=i,n=i+1):r=i-1;}return o})(e.rowOffsets,Math.max(0,t)),a=t+o;let s=i;for(;s{const s=e.children&&e.children.length>0,l=s&&!e.collapsed,[c,d]=_(false),[u,h]=_(false),g=["outline-item",`outline-level-${e.relativeLevel}`,e.isUserQuery?"user-query-node":"",e.isGhost?"ghost-node":""].filter(Boolean).join(" "); return qe(Sd,{content:e.wordCount&&e.wordCount>0?Re("div",{children:[e.text, Re("div",{style:{fontSize:"12px",opacity:.8,marginTop:"2px"},children:["(",ex(e.wordCount,de())," ",le("words"),")"]})]}):e.text,disabled:u,triggerStyle:{width:"100%",display:"block"},delay:500,children:Re("div",{className:g,"data-index":e.index,"data-level":e.relativeLevel,ref:t=>o(e.index,t),onClick:()=>n(e),children:[ qe("span",{className:"outline-item-toggle "+(s?l?"expanded":"":"invisible"),onClick:n=>{s&&(n.stopPropagation(),t(e));},children:qe(Dt,{size:16,style:{transform:"rotate(-90deg)"}})}),e.isUserQuery&&Re("span",{className:"user-query-badge",children:[ qe("span",{className:"user-query-badge-icon",children:"💬"}), qe("span",{className:"user-query-badge-number",children:e.queryIndex})]}), qe("span",{className:"outline-item-text "+(e.isGhost?"ghost-text":""),children:(()=>{if(i&&e.isMatch)try{const t=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(${t})`,"gi"),r=e.text.split(n); return qe(Ne,{children:r.map((e,t)=>e.toLowerCase()===i.toLowerCase()?qe("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})()}), qe("span",{className:"outline-item-bookmark-wrapper "+(e.isBookmarked?"active":""),children:qe(Sd,{content:e.isBookmarked?le("removeBookmark"):le("addBookmark"),children:qe("span",{className:"outline-item-bookmark-btn "+(e.isBookmarked?"active":""),onClick:t=>r(t,e),onMouseEnter:()=>h(true),onMouseLeave:()=>h(false),children:qe(bt,{size:14,filled:e.isBookmarked,color:e.isBookmarked?"#f59e0b":"currentColor"})})})}), qe(Sd,{content:le("copy"),children:qe("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&&a){const t=a(e.element);t&&(n=t);}else {const t=e.element.textContent;t&&(n=t.trim());}try{await navigator.clipboard.writeText(n),d(!0),setTimeout(()=>d(!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),d(!0),setTimeout(()=>d(!1),1500);}catch(o){console.error("[DEBUG] Fallback copy also failed:",o);}}},onMouseEnter:()=>h(true),onMouseLeave:()=>h(false),children:c? qe(tn,{size:14,color:"#10b981"}): qe(Nt,{size:14})})})]})})},cx=({items:e,metrics:t,scrollTop:n,viewportHeight:r,onToggle:o,onClick:i,onToggleBookmark:a,setItemRef:s,searchQuery:l,extractUserQueryText:c})=>{const d=$(null),u=$(new Set),h=sx(t,n,r),g=e.slice(h.start,h.end),p={"--gh-outline-item-height":"38px",height:t.totalHeight,position:"relative"};return L(()=>{if(!(()=>{if("undefined"!=typeof document){const e=document.documentElement.dataset.ophelDebugOutlineVirtualHeights;if("true"===e||"1"===e)return true}try{return "undefined"!=typeof window&&"1"===window.localStorage?.getItem("ophel.debugOutlineVirtualHeights")}catch{return false}})())return;const e=d.current;if(!e)return;const t=window.requestAnimationFrame(()=>{e.querySelectorAll(".outline-virtual-row").forEach(e=>{const t=e.querySelector(".outline-item");if(!t)return;const n=t.dataset.index||"unknown",r=t.getBoundingClientRect().height,o=e.getBoundingClientRect().height,i=Number(e.dataset.expectedRowHeight||38),a=t.scrollHeight-t.clientHeight,s=Math.abs(r-38),l=Math.abs(o-i);if(s<=1&&l<=1&&a<=1)return;const c=[n,r.toFixed(2),o.toFixed(2),i,a].join(":");u.current.has(c)||(u.current.add(c),console.warn("[OutlineTab] Virtual outline row height drift",{nodeIndex:n,nodeKind:e.dataset.nodeKind,itemHeight:r,expectedItemHeight:38,rowHeight:o,expectedRowHeight:i,itemOverflow:a}));});});return ()=>window.cancelAnimationFrame(t)},[h.start,h.end,t.totalHeight]),qe("div",{ref:d,className:"outline-list outline-list-virtual",style:p,children:g.map((e,n)=>{const r=h.start+n,d=ax(e,r); return qe("div",{className:"outline-virtual-row","data-depth":e.depth,"data-node-kind":e.node.isUserQuery?"user-query":"heading","data-expected-row-height":t.rowHeights[r],style:{position:"absolute",top:t.rowOffsets[r],left:0,right:0,height:t.rowHeights[r],paddingTop:d.top,paddingBottom:d.bottom,boxSizing:"border-box"},children:qe(lx,{node:e.node,onToggle:o,onClick:i,onToggleBookmark:a,setItemRef:s,searchQuery:l,extractUserQueryText:c})},e.node.index)})})},dx=({manager:e,conversationManager:t,onJumpBefore:n,isCodexOpen:r=false})=>{const{settings:o}=zi(),a=o,s=i.useMemo(()=>mr(),[]),l=le("shortcutNotSet"),c=i.useMemo(()=>Iv(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,q]=_(d.searchLevelManual),[R,P]=_(d.matchCount),[B,O]=_(d.bookmarkMode),[z,F]=_(d.sources),[U,H]=_(d.activeSourceId),[W,j]=_(false),[G,Q]=_(false),[V,K]=_(0),[Z,Y]=_(0),X=$(null),J=$(null),ee=$(0),te=$(false),ne=$(null),re=$(null),oe=$(null),ie=$(new Map),ae=$({rowOffsets:[],rowHeights:[],totalHeight:0,itemIndexByNodeIndex:new Map}),se=$(0),ce=$(null),de=$(null),ue=$(0),he=$(false),ge=$(null),pe=$(null),me=$({scrollTop:0,viewportHeight:0,scrollState:"bottom",rangeStart:0,rangeEnd:0}),fe=$({parentMap:{},parentNodeMap:new WeakMap,visibleMap:{},visibleNodeSet:new WeakSet,hasData:false});L(()=>(e.setActive(true),()=>{e.setActive(false);}),[e]),L(()=>{const e=()=>{J.current&&(J.current.focus(),J.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=tx(t.tree),r=ee.current;"latest"===(o?.features?.outline?.followMode||"current")&&n>r&&(te.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),q(t.searchLevelManual),P(t.matchCount),O(t.bookmarkMode),F(t.sources),H(t.activeSourceId),ee.current=n;};return t(),e.subscribe(t)},[e,o?.features?.outline?.followMode]),L(()=>{if(te.current&&X.current){const e=X.current;requestAnimationFrame(()=>{e.scrollTo({top:e.scrollHeight,behavior:"smooth"});}),te.current=false;}},[u]);const be=E((e=false)=>{const t=X.current;if(!t)return;const n=t.scrollTop,r=t.clientHeight,o=t.scrollTop+t.clientHeight>=t.scrollHeight-10?"top":"bottom",i=sx(ae.current,n,r),a=me.current,s=i.start!==a.rangeStart||i.end!==a.rangeEnd,l=r!==a.viewportHeight,c=o!==a.scrollState;me.current={scrollTop:n,viewportHeight:r,scrollState:o,rangeStart:i.start,rangeEnd:i.end},(e||c)&&x(o),(e||s||l)&&(K(n),Y(r));},[]),ye=E(()=>{null===pe.current&&(pe.current=requestAnimationFrame(()=>{pe.current=null,be();}));},[be]),ve=E((e,t="nearest",n="instant")=>{const r=X.current,o=ae.current,i=o.itemIndexByNodeIndex.get(e);if(!r||void 0===i)return false;const a=o.rowOffsets[i],s=a+o.rowHeights[i],l=r.scrollTop,c=l+r.clientHeight;let d=l;if("start"===t)d=a;else if("center"===t)d=a-(r.clientHeight-o.rowHeights[i])/2;else if("end"===t)d=s-r.clientHeight;else if(ac))return be(true),true;d=s-r.clientHeight;}const u=Math.max(0,r.scrollHeight-r.clientHeight),h=Math.max(0,Math.min(d,u));return Math.abs(h-r.scrollTop)>1&&(r.scrollTo({top:h,behavior:n}),be(true)),true},[be]),xe=E((...e)=>{if(0===e.length)return;const t=t=>{t.classList.remove(...e);};ie.current.forEach(t);const n=e.map(e=>`.outline-item.${e}`).join(", ");X.current?.querySelectorAll(n).forEach(t);},[]),we=E(e=>{xe(e);},[xe]),Se=E(e=>{const t=null!==e&&ie.current.get(e)||null;ie.current.forEach(e=>{e!==t&&e.classList.remove("sync-highlight","sync-highlight-visible");}),X.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"));},[]),Ce=E((e,t=null)=>{ne.current=e,re.current=t;},[]),ke=E(e=>{Se(e),oe.current=e;},[Se]),Te=E(t=>{const n=de.current;if(!n||n.index!==t||ce.current)return false;const r=ie.current.get(t);if(!r)return false;r.classList.add("highlight");const o=n.requestId,i=setTimeout(()=>{r.classList.remove("highlight"),de.current?.requestId===o&&(de.current=null),e.clearForceVisible(),ce.current=null;},3e3);return ce.current={element:r,timer:i},true},[e]),Ee=E((e,t)=>{const n=ie.current;t?(n.set(e,t),e!==oe.current&&t.classList.remove("sync-highlight","sync-highlight-visible"),e===oe.current&&Se(e),Te(e)):n.delete(e);},[Te,Se]),Ae=E(t=>{ue.current+=1,de.current=null;const n=ce.current;n&&(clearTimeout(n.timer),ce.current=null),we("highlight"),t?.clearForceVisible&&e.clearForceVisible();},[e,we]),Me=E(e=>{if(null===e)return null;const{parentMap:t,visibleMap:n,hasData:r}=fe.current;if(!r)return e;let o=e;for(;null!=o;){if(n[o])return o;o=t[o];}return null},[]),Ie=E(e=>{if(!e)return null;const{parentNodeMap:t,visibleNodeSet:n,hasData:r}=fe.current;if(!r)return e.index;let o=e;for(;o;){if(n.has(o))return o.index;o=t.get(o);}return null},[]),Le=E(e=>{if(!e)return false;const{parentNodeMap:t,hasData:n}=fe.current;return !n||t.has(e)},[]),Ne=D(()=>rx(u,T,M,g,N,B),[u,T,M,g,N,B]),{parentMap:Pe,parentNodeMap:De,visibleMap:Be,visibleNodeSet:_e}=Ne,Oe=D(()=>((e,t)=>{const n=[],r=(e,o)=>{for(const i of e)(t[i.index]??1)&&(n.push({node:i,depth:o}),i.children.length>0&&r(i.children,o+1));};return r(e,0),n})(u,Be),[u,Be]),ze=D(()=>(e=>{const t=[],n=[],r=new Map;let o=0;return e.forEach((e,i)=>{const a=ax(e,i),s=38+a.top+a.bottom;t.push(o),n.push(s),r.set(e.node.index,i),o+=s;}),{rowOffsets:t,rowHeights:n,totalHeight:o,itemIndexByNodeIndex:r}})(Oe),[Oe]),Fe=D(()=>z.filter(e=>e.available),[z]),Ue=D(()=>{const e=t=>{for(const n of t){if(Be[n.index])return true;if(n.children&&n.children.length>0&&e(n.children))return true}return false};return e(u)},[u,Be]);fe.current={parentMap:Pe,parentNodeMap:De,visibleMap:Be,visibleNodeSet:_e,hasData:u.length>0},ae.current=ze,L(()=>{const e=re.current,t=e&&Le(e)?Ie(e):Me(ne.current);ke(t);},[Pe,Be,u.length,Le,Ie,Me,ke]),L(()=>{if("current"!==(o?.features?.outline?.followMode||"current"))return Ce(null),void ke(null);let t,n=null,r=0,i=null,a=null,s=null;const l=new Map,c=()=>{e.markScrollPositionsStale(),g();},d=t=>{try{(t=>{if(l.has(t))return;const n=new MutationObserver(()=>{e.markScrollPositionsStale(),g();});n.observe(t,{childList:!0,subtree:!0}),l.set(t,n);})(t);}catch(n){console.warn("[OutlineTab] Failed to attach MutationObserver:",n);}},u=()=>{null!==s&&(cancelAnimationFrame(s),s=null);},h=()=>{if(!n)return;const t=e.findMountedActiveNode(n),r=t?.index??null;if(null===r)return null!==ne.current&&Ce(null),null!==oe.current&&ke(null),void u();r===ne.current&&t===re.current||Ce(r,t);const o=Ie(t),i=o!==oe.current;i&&ke(o),null===o?u():i&&(e=>{null!==s&&u(),s=requestAnimationFrame(()=>{if(s=null,he.current)return;const t=X.current;if(!t)return;const n=ie.current.get(e)||null;if(!n)return void ve(e,"center");const r=t.getBoundingClientRect(),o=n.getBoundingClientRect();(o.topr.bottom)&&ve(e,"center");});})(o);},g=()=>{null===a&&(a=requestAnimationFrame(()=>{a=null,h();}));},p=()=>{const o=e.getScrollContainer();o?(n=o,n.addEventListener("scroll",g,{passive:true}),window.addEventListener("resize",c,{passive:true}),d(o),"undefined"!=typeof ResizeObserver&&(i=new ResizeObserver(()=>{e.markScrollPositionsStale(),g();}),i.observe(n)),h()):r<20?(r++,t=setTimeout(p,300)):console.warn("[OutlineTab] Failed to find scroll container after retries");};return p(),()=>{n&&n.removeEventListener("scroll",g),window.removeEventListener("resize",c),null!==a&&(cancelAnimationFrame(a),a=null),null!==s&&u(),l.forEach(e=>e.disconnect()),l.clear(),i&&(i.disconnect(),i=null),t&&clearTimeout(t);}},[e,u.length,o?.features?.outline?.followMode,Ie,ve,Ce,ke]),L(()=>{const e=X.current;if(!e)return;e.addEventListener("scroll",ye,{passive:true});let t=null;return "undefined"!=typeof ResizeObserver&&(t=new ResizeObserver(ye),t.observe(e)),be(true),()=>{e.removeEventListener("scroll",ye),null!==pe.current&&(cancelAnimationFrame(pe.current),pe.current=null),t?.disconnect();}},[ye,be]),L(()=>{const e=X.current;if(!e)return;const t=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop>t&&(e.scrollTop=t),be(true);},[be,ze.totalHeight]),L(()=>{const e=X.current;if(!e)return;const t=()=>{he.current=true,ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{he.current=false;},1500);};return e.addEventListener("wheel",t,{passive:true}),()=>{e.removeEventListener("wheel",t),ge.current&&clearTimeout(ge.current);}},[]);const He=E(t=>{e.toggleNode(t);},[e]),We=E(async t=>{const r=++se.current;Ae({clearForceVisible:true}),ke(Me(ne.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===se.current)if(o&&o.isConnected){if(n&&!i&&await n(),r!==se.current)return;if(e.scrollToOutlineTarget(o),Ce(t.index,t),ke(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"}),Ce(t.index,t),ke(Me(t.index)),Gi(le("bookmarkContentMissing"),3e3));}},[Ae,Me,e,n,Ce,ke]),je=E(async()=>{if(!W){j(true);try{let e;if("conversation"===U){const n=await t.collectCurrentConversationExportMessages();if(!n||0===n.length)return void Gi(le("outlineEmpty"));e=Jv(n,{includeUserQueries:b,maxHeadingLevel:ox(w,b)});}else e=function(e,t){const n=[];let r=0;const o=e=>{if(!t.isIncluded||t.isIncluded(e)){const o=Vv(e.text,e.isUserQuery?120:void 0);o&&(e.isUserQuery?t.includeUserQueries&&(r+=1,n.push(Xv(o,r))):n.push(`${Zv(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=>Be[e.index??-1]??!0});if(!e.text)return void Gi(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),Q(!0),Gi(le("outlineFullCopySuccess").replace("{count}",String(e.count))),window.setTimeout(()=>Q(!1),1500);}catch(vT){console.error("[OutlineTab] Failed to copy outline:",vT),Gi(le("copyFailed"));}finally{j(false);}}},[U,t,w,W,b,u,Be]),Qe=E(t=>e.extractUserQueryText(t),[e]),Ve=E(t=>{e.setSearchQuery(t.target.value);},[e]),Ke=E(()=>{e.setSearchQuery("");},[e]),Ze=E(()=>{m?e.collapseAll():e.expandAll();},[e,m]),Ye=E((t,n)=>{t.stopPropagation(),e.toggleBookmark(n);},[e]),Xe=E(()=>{e.toggleBookmarkMode();},[e]),Je=E(()=>{e.toggleGroupMode();},[e]),et=E(()=>{const e=X.current;e&&("bottom"===v?e.scrollTo({top:e.scrollHeight,behavior:"smooth"}):e.scrollTo({top:0,behavior:"smooth"}));},[v]),tt=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,s=e.findMountedActiveItemIndex(t);let l=null!==s&&r.find(e=>e.index===s)||null;if(!l)for(const e of r){if(!e.element||!e.element.isConnected)continue;const t=e.element.getBoundingClientRect();if(t.top>=i&&t.topi){l=e;break}}if(!l){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{c===ue.current&&(ve(l.index,"center"),requestAnimationFrame(()=>{c===ue.current&&(Te(l.index)||(td(t+1),50):de.current?.requestId===c&&(de.current=null,e.clearForceVisible())));}));};setTimeout(()=>d(0),50);},[u,g,e,Te,Ae,ve]);L(()=>()=>{Ae({clearForceVisible:true});},[Ae]);const st=E(t=>{e.setLevel(t);},[e]);return L(()=>{const e=()=>{window.__ophelPendingLocateOutline=false,tt();};return window.__ophelPendingLocateOutline&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateOutline",e),()=>{window.removeEventListener("ophel:locateOutline",e);}},[tt]),Re("div",{className:"gh-outline-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ Re("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:[ Re("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[ Re("div",{style:{display:"flex",gap:"2px"},children:[ qe(Sd,{content:le("outlineShowUserQueries"),children:qe("button",{onClick:Je,className:"outline-toolbar-btn "+(b?"active-subtle":""),children:qe(en,{size:15})})}), qe(Sd,{content:le("bookmarkMode"),children:qe("button",{onClick:Xe,className:"outline-toolbar-btn "+(B?"active-subtle":""),children:qe(bt,{size:16,filled:B,color:"currentColor"})})}), qe(Sd,{content:le(B?"bookmarkModeDisabled":m?"outlineCollapseAll":"outlineExpandAll"),children:qe("button",{onClick:B?void 0:Ze,disabled:B,className:"outline-toolbar-btn",children:qe(m?rt:nt,{size:18})})}), qe(Sd,{content:le(W?"outlineCopyFullRunning":"outlineCopyFull"),children:qe("button",{onClick:je,disabled:W,className:"outline-toolbar-btn "+(W?"is-busy":""),children:G?qe(tn,{size:14,color:"#10b981"}):qe(qt,{size:16})})}), qe(Sd,{content:le("outlineLocateCurrent"),children:qe("button",{onClick:tt,className:"outline-toolbar-btn",children:qe(ot,{size:16})})}), qe(Sd,{content:le("bottom"===v?"outlineScrollBottom":"outlineScrollTop"),children:qe("button",{onClick:et,className:"outline-toolbar-btn",children:qe("bottom"===v?at:it,{size:16})})})]}), Re("div",{className:"outline-search-wrapper",style:{flex:1,position:"relative",display:"flex",alignItems:"center"},children:[ qe("input",{ref:J,type:"text",className:"outline-search-input",placeholder:le("outlineSearch"),value:g,onChange:Ve,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&&qe("button",{className:"outline-search-clear",onClick:Ke,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:qe($e,{size:14})})]})]}), qe("div",{className:"outline-level-slider-container",style:{padding:"0 4px"},children:Re("div",{className:"outline-level-dots",style:{display:"flex",justifyContent:"space-between",position:"relative",padding:"6px 0",alignItems:"center"},children:[ qe("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"}}), qe("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 qe(Sd,{content:t,children:qe("div",{className:`outline-level-dot ${n?"active":""} ${B?"disabled":""}`,"data-level":e,onClick:B?void 0:()=>st(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&&Re("div",{className:"outline-result-bar",style:{textAlign:"center",padding:"6px 8px",margin:"0 8px 0 8px",color:"var(--gh-border-active)",fontSize:"13px",background:R>0?"var(--gh-folder-bg-default)":"transparent",borderRadius:"4px",border:0===R?"1px dashed var(--gh-border, #e5e7eb)":"none",flexShrink:0},children:[R," ",le("outlineSearchResult")]}),Fe.length>1&&!g&&qe("div",{className:"outline-source-switch","aria-label":le("outlineSourceSwitchLabel"),children:Fe.map(t=>qe("button",{type:"button",className:"outline-source-switch-option "+(U===t.id?"active":""),onClick:()=>e.setActiveSource(t.id),children:qe("span",{children:nx(t)})},t.id))}), qe("div",{ref:X,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||!Ue),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?Re("div",{className:"outline-empty-state",children:[ qe("div",{className:"outline-empty-state-icon","aria-hidden":"true",children:qe(Ge,{size:20,color:"currentColor"})}), qe("div",{className:"outline-empty-state-title",children:le("outlineEmpty")}), Re("div",{className:"outline-empty-state-desc",children:[ qe("span",{className:"outline-empty-state-desc-line",children:d}),h&&qe("span",{className:"outline-empty-state-desc-line",children:h})]}), qe("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!r&&qe(Av,{isOpen:true,onClose:()=>{},tips:c,isStatic:true})})]}):qe(cx,{items:Oe,metrics:ze,scrollTop:V,viewportHeight:Z,onToggle:He,onClick:We,onToggleBookmark:Ye,setItemRef:Ee,searchQuery:g,extractUserQueryText:Qe}):Re("div",{className:"outline-empty-state",children:[ qe("div",{className:"outline-empty-state-icon",style:{background:"rgba(245, 158, 11, 0.1)",color:"#f59e0b"},"aria-hidden":"true",children:qe(bt,{size:20,filled:true,color:"#f59e0b"})}), qe("div",{className:"outline-empty-state-title",children:le("outlineNoBookmarks")}), qe("div",{className:"outline-empty-state-desc",children:le("outlineAddBookmarkHint")}), qe("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!r&&qe(Av,{isOpen:true,onClose:()=>{},tips:c,isStatic:true})})]})})()})]})},ux=[{id:"run",label:"运行",labelEn:"Run",category:"common",svg:''},{id:"translate",label:"翻译",labelEn:"Translate",category:"common",svg:''},{id:"summary",label:"总结",labelEn:"Summary",category:"common",svg:''},{id:"expand",label:"扩写",labelEn:"Expand",category:"common",svg:''},{id:"polish",label:"润色",labelEn:"Polish",category:"common",svg:''},{id:"explain",label:"解释",labelEn:"Explain",category:"common",svg:''},{id:"question",label:"提问",labelEn:"Question",category:"common",svg:''},{id:"check",label:"检查",labelEn:"Check",category:"common",svg:''},{id:"fix",label:"修正",labelEn:"Fix",category:"common",svg:''},{id:"optimize",label:"优化",labelEn:"Optimize",category:"common",svg:''},{id:"compare",label:"对比",labelEn:"Compare",category:"common",svg:''},{id:"report",label:"报告",labelEn:"Report",category:"work",svg:''},{id:"meeting",label:"会议",labelEn:"Meeting",category:"work",svg:''},{id:"email",label:"邮件",labelEn:"Email",category:"work",svg:''},{id:"schedule",label:"日程",labelEn:"Schedule",category:"work",svg:''},{id:"presentation",label:"演示",labelEn:"Presentation",category:"work",svg:''},{id:"contract",label:"合同",labelEn:"Contract",category:"work",svg:''},{id:"finance",label:"财务",labelEn:"Finance",category:"work",svg:''},{id:"plan",label:"计划",labelEn:"Plan",category:"work",svg:''},{id:"archive",label:"归档",labelEn:"Archive",category:"work",svg:''},{id:"stamp",label:"审批",labelEn:"Approval",category:"work",svg:''},{id:"book",label:"阅读",labelEn:"Reading",category:"learning",svg:''},{id:"note",label:"笔记",labelEn:"Note",category:"learning",svg:''},{id:"research",label:"研究",labelEn:"Research",category:"learning",svg:''},{id:"experiment",label:"实验",labelEn:"Experiment",category:"learning",svg:''},{id:"thesis",label:"论文",labelEn:"Thesis",category:"learning",svg:''},{id:"formula",label:"公式",labelEn:"Formula",category:"learning",svg:''},{id:"quiz",label:"测验",labelEn:"Quiz",category:"learning",svg:''},{id:"homework",label:"作业",labelEn:"Homework",category:"learning",svg:''},{id:"reference",label:"参考",labelEn:"Reference",category:"learning",svg:''},{id:"tutorial",label:"教程",labelEn:"Tutorial",category:"learning",svg:''},{id:"idea",label:"创意",labelEn:"Idea",category:"creative",svg:''},{id:"design",label:"设计",labelEn:"Design",category:"creative",svg:''},{id:"paint",label:"绘画",labelEn:"Paint",category:"creative",svg:''},{id:"image",label:"图片",labelEn:"Image",category:"creative",svg:''},{id:"video",label:"视频",labelEn:"Video",category:"creative",svg:''},{id:"chart",label:"图表",labelEn:"Chart",category:"analysis",svg:''},{id:"data",label:"数据",labelEn:"Data",category:"analysis",svg:''},{id:"calculate",label:"计算",labelEn:"Calculate",category:"analysis",svg:''},{id:"statistics",label:"统计",labelEn:"Statistics",category:"analysis",svg:''}];function hx({value:e,onChange:t,onClose:n}){ return Re("div",{className:"gh-chain-icon-picker",children:[ qe("style",{children:'\n.gh-chain-icon-picker,\n.gh-chain-icon-picker * {\n box-sizing: border-box;\n}\n\n.gh-chain-icon-picker {\n display: flex;\n flex-direction: column;\n width: 650px;\n max-width: 90vw;\n height: 520px;\n max-height: 80vh;\n background: var(--gh-bg, #ffffff);\n border-radius: 12px;\n overflow: hidden;\n color: var(--gh-text, #1f2937);\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n box-shadow: 0 20px 60px rgba(15, 23, 42, 0.28);\n}\n\n.gh-chain-icon-picker-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 12px;\n padding: 16px 20px;\n border-bottom: 1px solid var(--gh-border, #e5e7eb);\n flex-shrink: 0;\n}\n\n.gh-chain-icon-picker-title {\n color: var(--gh-text, #1f2937);\n font-size: 16px;\n font-weight: 650;\n line-height: 1.4;\n}\n\n.gh-chain-icon-picker-close {\n padding: 8px 16px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 6px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n font: inherit;\n font-size: 14px;\n font-weight: 500;\n line-height: 1.2;\n cursor: pointer;\n transition:\n background 0.15s ease,\n border-color 0.15s ease,\n color 0.15s ease;\n}\n\n.gh-chain-icon-picker-close:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-primary, #4285f4);\n color: var(--gh-primary, #4285f4);\n}\n\n.gh-chain-icon-picker-grid {\n flex: 1;\n min-height: 0;\n padding: 20px;\n overflow-y: auto;\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(58px, 1fr));\n gap: 12px;\n align-content: start;\n}\n\n.gh-chain-icon-picker-grid::-webkit-scrollbar {\n width: 8px;\n}\n\n.gh-chain-icon-picker-grid::-webkit-scrollbar-thumb {\n background: var(--gh-border, #e5e7eb);\n border-radius: 4px;\n}\n\n.gh-chain-icon-picker-grid::-webkit-scrollbar-thumb:hover {\n background: var(--gh-text-secondary, #6b7280);\n}\n\n.gh-chain-icon-picker-item {\n appearance: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n aspect-ratio: 1;\n min-width: 0;\n min-height: 58px;\n margin: 0;\n padding: 14px;\n border: 1.5px solid var(--gh-border, #e5e7eb);\n border-radius: 8px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text-secondary, #6b7280);\n font: inherit;\n line-height: 1;\n cursor: pointer;\n transition:\n transform 0.15s ease,\n box-shadow 0.15s ease,\n background 0.15s ease,\n border-color 0.15s ease,\n color 0.15s ease;\n}\n\n.gh-chain-icon-picker-item:hover {\n border-color: var(--gh-primary, #4285f4);\n background: rgba(66, 133, 244, 0.06);\n color: var(--gh-primary, #4285f4);\n transform: translateY(-1px);\n box-shadow: 0 6px 16px rgba(66, 133, 244, 0.18);\n}\n\n.gh-chain-icon-picker-item.active {\n border-color: var(--gh-primary, #4285f4);\n background: rgba(66, 133, 244, 0.1);\n color: var(--gh-primary, #4285f4);\n box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.18);\n}\n\n.gh-chain-icon-picker-icon {\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: currentColor;\n}\n\n.gh-chain-icon-picker-icon svg {\n width: 100%;\n height: 100%;\n display: block;\n fill: none;\n stroke: currentColor;\n}\n\n@media (max-width: 520px) {\n .gh-chain-icon-picker {\n width: calc(100vw - 24px);\n height: min(520px, calc(100vh - 48px));\n }\n\n .gh-chain-icon-picker-grid {\n grid-template-columns: repeat(auto-fill, minmax(52px, 1fr));\n gap: 10px;\n padding: 16px;\n }\n\n .gh-chain-icon-picker-item {\n min-height: 52px;\n padding: 12px;\n }\n\n .gh-chain-icon-picker-icon {\n width: 26px;\n height: 26px;\n }\n}\n'}), Re("div",{className:"gh-chain-icon-picker-header",children:[ qe("div",{className:"gh-chain-icon-picker-title",children:le("chainIconSelect")}), qe("button",{type:"button",onClick:n,className:"gh-chain-icon-picker-close",children:le("chainIconClose")})]}), qe("div",{className:"gh-chain-icon-picker-grid",children:ux.map(n=>{const r=`chainIconPreset${n.id.replace(/(^|[-_])([a-z])/g,(e,t,n)=>n.toUpperCase())}`;const o=le(r),i=o===r?n.labelEn||n.label:o; return qe("button",{type:"button",className:"gh-chain-icon-picker-item"+(e===n.svg?" active":""),onClick:()=>t(n.id,n.svg),"aria-label":i,"aria-pressed":e===n.svg,title:i,children:qe(Ob,{className:"gh-chain-icon-picker-icon",svg:n.svg})},n.id)})})]})}const gx=e=>e.replace(/\r\n?/g,"\n"),px=e=>gx(e).split("\n").map(e=>e.trim()).filter(Boolean),mx=e=>{if(e)return {source:e.source,promptId:e.prompt?.id,promptTitle:e.prompt?.title,quoteRef:e.variables?.quoteRef}},fx=e=>"object"==typeof e&&null!==e,bx=e=>!!fx(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),yx=({manager:e,adapter:t,onPromptSelect:n,selectedPromptId:r})=>{const o=zi(e=>e.settings.features?.prompts?.doubleClickToSend??false),i=zi(e=>e.settings.features?.prompts?.submitShortcut??"enter"),a=zi(e=>e.settings.features?.prompts?.promptQueue??false),s=zi(e=>e.settings.features?.prompts?.quickQuoteEnabled??true),l=zi(e=>e.updateDeepSetting),[c,d]=_([]),[u,h]=_([]),[g,p]=_(Ro),[m,f]=_(""),[b,y]=_("prompts"),v=wy(e=>e.chains),x=wy(e=>e.addChain),w=wy(e=>e.updateChain),S=wy(e=>e.deleteChain),C=wy(e=>e.duplicateChain),k=wy(e=>e.updateOrder),[T,A]=_(false),[M,I]=_(null),[N,q]=_({show:false,draft:null,showExecutionPreview:false,draggedStepId:null}),[R,P]=_(false),[D,B]=_(false),[O,z]=_({show:false,title:"",message:"",onConfirm:()=>{}}),[F,U]=_({show:false,title:"",defaultValue:"",onConfirm:()=>{}}),[H,W]=_(null),j=$(null),G=$(null),[Q,V]=_(null),K=$(null),Z=$(null),[Y,X]=_({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),[J,ee]=_({show:false,prompts:[]}),[te,ne]=_(false),re=$(null),[oe,ie]=_(false),[ae,se]=_({show:false,prompt:null}),ce=$(null),de=$(null),ue=$(null),[he,ge]=_(null),[pe,me]=_(null),fe=$(null),be=$(null),ye=E(()=>{const t=e.getPrompts(),n=e.getCategories();d(t),h(n),p(e=>{if(e===Ro)return e;if(!n.includes(e))return Ro;return t.some(t=>t.category===e)?e:Ro});},[e]),ve=E((t,n=false)=>{const r=e.getPrompts().find(e=>e.id===t);if(!r)return false;const o=Fb(r.content);return 0!==o.length&&(X({show:true,prompt:r,variables:o,submitAfterInsert:n,enqueueAfterResolve:false,enqueueSplitByLine:false}),true)},[e]),xe=E(t=>{const r=e.getPrompts().find(e=>e.id===t);return !!r&&(y("prompts"),p(Ro),f(""),n?.(null),ge(r.id),true)},[e,n]);L(()=>{const e=window,t=t=>{const r=t.detail,o=r?.promptId;if(!o)return;ve(o,Boolean(r?.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);};window.addEventListener("ophel:openPromptVariableDialog",t);const r=e.__ophelPendingPromptVariableDialog;if(r?.promptId){ve(r.promptId,Boolean(r.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);}return ()=>{window.removeEventListener("ophel:openPromptVariableDialog",t);}},[n,ve]),L(()=>{const e=window,t=t=>{const n=t.detail,r=n?.promptId;if(!r)return;xe(r)&&(e.__ophelPendingLocatePrompt=null);};window.addEventListener("ophel:locatePrompt",t);const n=e.__ophelPendingLocatePrompt;if(n?.promptId){xe(n.promptId)&&(e.__ophelPendingLocatePrompt=null);}return ()=>{window.removeEventListener("ophel:locatePrompt",t);}},[xe]),L(()=>{ye();},[ye]),L(()=>()=>{null!==ce.current&&window.clearTimeout(ce.current),null!==de.current&&window.clearTimeout(de.current);},[]),L(()=>{oe&&fe.current&&Ad(fe.current,{size:14,color:"#6b7280"});},[oe,M?.content]),L(()=>{ae.show&&be.current&&Ad(be.current,{size:14,color:"#6b7280"});},[ae.show,ae.prompt]);const we=(e,t,n)=>{z({show:true,title:e,message:t,onConfirm:n});},Se=()=>({id:`step_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,mode:"prompt",promptId:c[0]?.id||"",inlineContent:"",runMode:"enqueue",splitMode:"none"}),Ce=e=>{q({show:true,draft:e?{...e,steps:e.steps.map(e=>({...e}))}:{title:"",description:"",iconSvg:ux[0]?.svg||"",showInSelectionPopover:true,steps:c[0]?[Se()]:[],lastUsedAt:void 0},showExecutionPreview:false,draggedStepId:null});},ke=E(()=>{q({show:false,draft:null,showExecutionPreview:false,draggedStepId:null});},[]),Te=e=>{q(t=>t.draft?{...t,draft:{...t.draft,...e}}:t);},Ee=E(()=>{l("features","prompts","promptQueue",true),Gi(le("chainQueueEnabledToast"),1800);},[l]),Ae=E(()=>{l("features","prompts","quickQuoteEnabled",true),Gi(le("chainQuickQuoteEnabledToast"),1800);},[l]),Me=E(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:"prompt-queue"}}));},[]),Ie=E(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:"prompt-quick-quote-enabled"}}));},[]),Le=()=>{l("features","prompts","promptQueue",true),Gi(le("chainQueueEnabledToast"),1800),Ce();},Pe=(e,t)=>{q(n=>n.draft?{...n,draft:{...n.draft,steps:n.draft.steps.map(n=>n.id===e?{...n,...t}:n)}}:n);},De=()=>{q(e=>e.draft?{...e,draft:{...e.draft,steps:[...e.draft.steps,Se()]}}:e);},Be=()=>{q(e=>({...e,draggedStepId:null}));},_e=()=>{const e=N.draft;if(!e)return;const t=e.title.trim(),n=e.steps.map(e=>"inline"===e.mode?e.inlineContent?.trim()?{...e,promptId:"",inlineContent:e.inlineContent}:null:e.promptId?{...e,mode:"prompt",inlineContent:""}:null).filter(e=>null!==e);if(!t)return void Gi(le("chainTitleRequired"),2200);if(0===n.length)return void Gi(le("chainStepRequired"),2200);const r={title:t,description:e.description?.trim()||"",iconSvg:e.iconSvg?.trim()||"",showInSelectionPopover:false!==e.showInSelectionPopover,steps:n,lastUsedAt:e.lastUsedAt};e.id?(w(e.id,r),Gi(le("chainUpdated"),1800)):(x(r),Gi(le("chainAdded"),1800)),ke();},Oe=e=>c.find(t=>t.id===e)?.title||le("chainMissingPrompt"),ze=e=>"inline"===e.mode?e.inlineContent||"":Oe(e.promptId),Fe=v.filter(e=>{const t=m.trim().toLowerCase();if(!t)return true;const n=e.steps.map(ze).join(" ");return `${e.title} ${e.description||""} ${n}`.toLowerCase().includes(t)}),He=async(e,t=false)=>{const n=Fb(e.content);if(n.length>0)X({show:true,prompt:e,variables:n,submitAfterInsert:t,enqueueAfterResolve:false,enqueueSplitByLine:false});else {if(t)return void(await je(e,e.content));await We(e,e.content);}},We=async(t,r)=>{await e.insertPrompt(r)?(e.updateLastUsed(t.id),n?.(t),Gi(`${le("inserted")}: ${t.title}`)):Gi(le("insertFailed"));},je=async(r,o)=>{const a=await(async({adapter:e,manager:t,content:n,submitShortcut:r,context:o})=>{const i=n.trim();if(!i)return {status:"insert-failed"};const a=o?.variables?.quoteRef;_f(i,a);const s=Of(i,a),l=zi.getState().settings.features?.prompts?.promptQueue??false;return e?.isGenerating()&&l?(gb.getState().enqueue(s,mx(o)),{status:"queued",count:1}):await t.insertPrompt(s)?await t.submitPrompt(r)?{status:"sent"}:{status:"send-failed"}:{status:"insert-failed"}})({adapter:t,manager:e,content:o,submitShortcut:i,context:{source:"prompt-library",prompt:r}});if("insert-failed"!==a.status){if(e.updateLastUsed(r.id),"send-failed"===a.status)return Gi(le("promptSendFailed")),void n?.(r);n?.(null),"queued"!==a.status?Gi(`${le("promptSent")}: ${r.title}`):Gi(le("promptQueued",{count:String(a.count)}),2500);}else Gi(le("insertFailed"));},Ge=(t,n,r=false)=>{const o=(({content:e,splitByLine:t=false,context:n})=>{if(!zi.getState().settings.features?.prompts?.promptQueue)return {status:"disabled"};const r=t?px(e):[e.trim()].filter(Boolean);if(0===r.length)return {status:"empty"};const o=mx(n),i=gb.getState().enqueueMany(r.map(e=>({content:Of(e,o?.quoteRef),metadata:o})));return 0===i.length?{status:"empty"}:{status:"queued",count:i.length}})({content:n,splitByLine:r,context:{source:"prompt-library",prompt:t}});"disabled"!==o.status?"empty"!==o.status?(e.updateLastUsed(t.id),Gi(le("promptQueued",{count:String(o.count)}),2500)):Gi(le("promptEnqueueEmpty"),2500):Gi(le("promptQueueEnableHint"),3e3);},Qe=(e,t=false)=>{if(!a)return void Gi(le("promptQueueEnableHint"),3e3);const n=Fb(e.content);n.length>0?X({show:true,prompt:e,variables:n,submitAfterInsert:false,enqueueAfterResolve:true,enqueueSplitByLine:t}):Ge(e,e.content,t);},Ve=()=>{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:fx(e)?Array.isArray(e.prompts)?e.prompts:fx(e.data)&&Array.isArray(e.data.prompts)?e.data.prompts:fx(e.state)&&Array.isArray(e.state.prompts)?e.state.prompts:null:null;return t&&t.every(bx)?t:null})(JSON.parse(e));if(!n)return console.error("[Ophel] prompt import failed: unsupported prompt file format"),void Gi(le("promptImportFailed"));ee({show:!0,prompts:n});}catch(vT){console.error("[Ophel] prompt import failed:",vT),Gi(le("promptImportFailed"));}},e.click();},Ke=()=>{const t=J.prompts;e.setPrompts(t),ye(),ee({show:false,prompts:[]}),Gi(le("promptImportSuccess").replace("{count}",t.length.toString()));},Xe=()=>{const t=J.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});}),ye(),ee({show:false,prompts:[]});const a=`已合并:更新 ${o.length} 个,新增 ${i.length} 个`;Gi(le("promptMergeSuccess")?.replace("{updated}",o.length.toString()).replace("{added}",i.length.toString())||a);},Je=async()=>{if(!M?.title||!M?.content)return void Gi(le("fillTitleContent"));const t=M.category||le("uncategorized");let n=false;if(M.id){const r=c.find(e=>e.id===M.id),o=r?.category;if(o&&o!==t&&g===o){0===c.filter(e=>e.category===o&&e.id!==M.id).length&&(n=true);}await e.updatePrompt(M.id,{title:M.title,content:M.content,category:t}),Gi(le("promptUpdated")),n&&p(t);}else await e.addPrompt({title:M.title,content:M.content,category:t}),Gi(le("promptAdded"));et(),ye();},et=E(()=>{A(false),I(null);},[]),tt=E(()=>{B(false);},[]),nt=E(()=>{z(e=>({...e,show:false}));},[]),rt=E(()=>{U(e=>({...e,show:false}));},[]),ot=E(()=>{se({show:false,prompt:null});},[]),it=E(()=>{ee({show:false,prompts:[]});},[]),at=E(()=>{X({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false});},[]),st=E(()=>{me(null);},[]),lt=e=>{if(e)I({...e});else {const e=g===Ro||g===Po?u[0]||le("uncategorized"):g;I({title:"",content:"",category:e});}A(true);},ct=(t,n)=>{var r;n.stopPropagation(),n.preventDefault(),r=le("newCategoryName"),U({show:true,title:r,defaultValue:t,onConfirm:async n=>{n&&n.trim()&&n!==t&&(await e.renameCategory(t,n.trim()),Gi(le("categoryRenamedTo").replace("{name}",n.trim())),g===t&&p(n.trim()),ye());}});},dt=E(()=>{const e=[G.current,j.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");}));}),G.current=null;},[]),ut=()=>{j.current&&j.current.classList.remove("dragging"),dt(),W(null),j.current=null;},ht=E(()=>{const e=[Z.current,K.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");}));}),Z.current=null;},[]),gt=()=>{K.current&&K.current.classList.remove("dragging"),ht(),V(null),K.current=null;},pt=(()=>{let t;if(g===Po){if(t=e.getPrompts().filter(e=>e.lastUsedAt).sort((e,t)=>(t.lastUsedAt||0)-(e.lastUsedAt||0)).slice(0,10),m){const e=m.toLowerCase();t=t.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e));}}else t=e.filterPrompts(m,g);return g!==Po&&(t=t.sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:0)),t})();L(()=>{if(!(F.show||O.show||D||T||N.show||ae.show||J.show||Y.show))return;const e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.(),F.show?rt():O.show?nt():Y.show?at():D?tt():T?et():N.show?ke():ae.show?ot():J.show&&it());};return document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);}},[tt,nt,ke,et,it,ot,rt,at,N.show,O.show,J.show,D,T,ae.show,F.show,Y.show]),L(()=>{if(!he)return;const e=ue.current;if(!e)return;const t="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(he):he.replace(/["\\]/g,"\\$&"),n=e.querySelector(`.prompt-item[data-prompt-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),null!==de.current&&window.clearTimeout(de.current),de.current=window.setTimeout(()=>{ge(e=>e===he?null:e),de.current=null;},2200));},[b,he,c,m,g]);const mt=e=>{const t=new Set,n=[];return e.steps.forEach(e=>{let r="";if("inline"===e.mode&&e.inlineContent)r=e.inlineContent;else {const t=c.find(t=>t.id===e.promptId);if(!t)return;r=t.content;}Fb(r).forEach(e=>{"selection"===e.raw||"quote"===e.raw||t.has(e.raw)||(t.add(e.raw),n.push(e));});}),n},ft=e=>e.steps.map(e=>{if("inline"===e.mode&&e.inlineContent){const t=e.inlineContent.trim().replace(/\s+/g," ");return t.length>30?`${t.slice(0,30)}...`:t}return Oe(e.promptId)}),bt=e=>{const t={selection:"Selected text from conversation",quote:"> Selected text from conversation"};return mt(e).forEach(e=>{t[e.raw]=`{{${e.raw}}}`;}),e.steps.map(e=>{let n="";if("inline"===e.mode&&e.inlineContent)n=e.inlineContent;else {const t=c.find(t=>t.id===e.promptId);n=t?.content||"";}return n?Ub(n,t).trim():""})},yt=(e,t="enable")=>{if(a)return null;const n="enableAndCreate"===t; return Re("div",{className:`gh-chain-queue-gate ${e}`,children:[ Re("div",{className:"gh-chain-queue-gate-copy",children:[ qe("div",{className:"gh-chain-queue-gate-title",children:le("chainQueueRequiredTitle")}), qe("div",{className:"gh-chain-queue-gate-description",children:le("chainQueueRequiredDescription")})]}), Re("div",{className:"gh-chain-queue-gate-actions",children:[ qe(xb,{variant:"primary",size:"sm",onClick:n?Le:Ee,children:le(n?"chainQueueEnableAndCreate":"chainQueueEnable")}), qe(xb,{variant:"ghost",size:"sm",onClick:Me,children:le("chainQueueViewSettings")})]})]})},vt=e=>s?null:Re("div",{className:`gh-chain-queue-gate ${e}`,children:[ Re("div",{className:"gh-chain-queue-gate-copy",children:[ qe("div",{className:"gh-chain-queue-gate-title",children:le("chainQuickQuoteRequiredTitle")}), qe("div",{className:"gh-chain-queue-gate-description",children:le("chainQuickQuoteRequiredDescription")})]}), Re("div",{className:"gh-chain-queue-gate-actions",children:[ qe(xb,{variant:"primary",size:"sm",onClick:Ae,children:le("chainQuickQuoteEnable")}), qe(xb,{variant:"ghost",size:"sm",onClick:Ie,children:le("chainQuickQuoteViewSettings")})]})]}); return Re("div",{className:"gh-prompts-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ Re("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",display:"flex",gap:"6px",alignItems:"center"},children:[ Re("div",{className:"gh-prompt-library-switch",role:"tablist",children:[ qe("button",{type:"button",className:"gh-prompt-library-switch-btn","data-active":"prompts"===b,onClick:()=>y("prompts"),children:le("promptsViewPrompts")}), qe("button",{type:"button",className:"gh-prompt-library-switch-btn","data-active":"chains"===b,onClick:()=>y("chains"),children:le("promptsViewChains")})]}), qe("input",{type:"text",className:"prompt-search-input",placeholder:le("chains"===b?"chainSearchPlaceholder":"searchPlaceholder"),value:m,onChange:e=>f(e.target.value),style:{flex:"1 1 auto",minWidth:"120px",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)"}}),"prompts"===b&&Re("div",{style:{position:"relative"},children:[ qe(Sd,{content:le("promptImport")+" / "+le("promptExport"),children:qe("button",{ref:re,onClick:()=>ne(!te),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:qe(Ze,{size:16})})}),te&&Re(Ne,{children:[ qe("div",{style:{position:"fixed",inset:0,zIndex:99},onClick:()=>ne(false)}), Re("div",{style:{position:"absolute",top:"calc(100% + 4px)",right:0,zIndex:100,minWidth:"140px",background:"var(--gh-bg, #ffffff)",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.12)",overflow:"hidden"},children:[ Re("button",{onClick:()=>{ne(false),Ve();},style:{width:"100%",padding:"8px 12px",border:"none",background:"transparent",textAlign:"left",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:"var(--gh-text, #1f2937)"},onMouseEnter:e=>e.currentTarget.style.background="var(--gh-hover, #f3f4f6)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:[ qe(Ze,{size:14}),le("promptImport")]}), Re("button",{onClick:()=>{ne(false),(()=>{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=`${nv}-prompts-${(new Date).toISOString().split("T")[0]}.json`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o),Gi(le("promptExportSuccess"));})();},style:{width:"100%",padding:"8px 12px",border:"none",background:"transparent",textAlign:"left",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:"var(--gh-text, #1f2937)"},onMouseEnter:e=>e.currentTarget.style.background="var(--gh-hover, #f3f4f6)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:[ qe(Ye,{size:14}),le("promptExport")]})]})]})]})]}),"prompts"===b&&Re("div",{style:{display:"flex",alignItems:"center",background:"var(--gh-bg, white)",borderBottom:"1px solid var(--gh-border, #e5e7eb)",userSelect:"none"},children:[ Re("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:[ qe("span",{onClick:()=>p(Ro),style:{padding:"4px 10px",background:g===Ro?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"12px",fontSize:"12px",color:g===Ro?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:g===Ro?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:le("allCategory")}),u.map(e=>{const t=(e=>{let t=0;for(let n=0;np(e),style:{padding:"4px 10px",background:g===e?"var(--gh-primary, #4285f4)":`var(--gh-category-${t})`,borderRadius:"12px",fontSize:"12px",color:g===e?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:g===e?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})},e)})]}), Re("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"6px 8px",flexShrink:0,borderLeft:"1px solid var(--gh-border, #e5e7eb)"},children:[ qe(Sd,{content:le("promptRecentUsed"),children:qe("span",{onClick:()=>p(Po),style:{padding:"3px 6px",display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1,background:g===Po?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"10px",color:g===Po?"white":"#4b5563",cursor:"pointer",border:g===Po?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:qe(Xt,{size:14})})}),u.length>0&&qe(Sd,{content:le("manageCategory"),children:qe("button",{onClick:()=>B(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:qe(Ue,{size:13})})})]})]}), qe("div",{ref:ue,style:{flex:1,overflowY:"auto",padding:"8px",scrollbarWidth:"none"},children:"chains"===b?0===c.length?Re("div",{className:"gh-chain-empty",children:[ qe("div",{className:"gh-chain-empty-title",children:le("chainNoPrompts")}), qe("div",{className:"gh-chain-empty-description",children:le("chainNoPromptsDescription")})]}):0===Fe.length?Re(Ne,{children:[yt("list",0===v.length?"enableAndCreate":"enable"), Re("div",{className:"gh-chain-empty",children:[ qe("div",{className:"gh-chain-empty-title",children:le("chainEmpty")}), qe("div",{className:"gh-chain-empty-description",children:le("chainEmptyDescription")}), Re(xb,{variant:"primary",size:"sm",onClick:()=>Ce(),style:{marginTop:"14px"},children:["+ ",le("chainAdd")]})]})]}):Re(Ne,{children:[yt("list"),vt("list"),Fe.map(e=>{const t=false!==e.showInSelectionPopover,n=ft(e),r=n.length>0?n.join(" → "):le("chainNoSteps"); return Re("div",{className:"gh-chain-card"+(Q===e.id?" dragging":""),"data-disabled":!t,onClick:()=>Ce(e),draggable:true,onDragStart:t=>((e,t,n)=>{e.target.closest('button, input, textarea, select, [role="button"], [data-no-row-drag="true"]')?e.preventDefault():(V(t),K.current=n,Z.current=n.getRootNode(),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",t),n.classList.add("dragging"));})(t,e.id,t.currentTarget),onDragOver:t=>((e,t)=>{if(e.preventDefault(),e.dataTransfer.dropEffect="move",!Q||Q===t)return;const n=e.currentTarget,r=n.getBoundingClientRect(),o=r.top+r.height/2,i=n.getRootNode();Z.current=i,ht(),e.clientY((e,t)=>{if(e.preventDefault(),!Q||Q===t)return void gt();const n=v.findIndex(e=>e.id===Q),r=v.findIndex(e=>e.id===t);if(-1===n||-1===r)return void gt();const o=[...v],[i]=o.splice(n,1),a=e.currentTarget.getBoundingClientRect(),s=e.clientYe.id===t);ne.id)),Gi(le("orderUpdated")),gt();})(t,e.id),children:[ Re("div",{className:"gh-chain-card-main",children:[ Re("div",{className:"gh-chain-icon","data-enabled":t,children:[(o=e.iconSvg,qe(Ob,{className:"gh-chain-icon-svg",svg:o,fallback:qe("span",{className:"gh-chain-icon-fallback",children:"C"})})), qe("span",{className:"gh-chain-icon-status-dot","data-enabled":t})]}), Re("div",{className:"gh-chain-body",children:[ qe("div",{className:"gh-chain-title-row",children:qe("span",{className:"gh-chain-title",children:e.title})}), qe(Sd,{content:r,children:Re("div",{className:"gh-chain-flow",children:[ qe("span",{className:"gh-chain-meta-badge",children:e.steps.length}), qe("span",{className:"gh-chain-flow-text",children:r})]})})]})]}), Re("div",{className:"gh-chain-card-actions",children:[ qe(Sd,{content:le(t?"chainShownInPopover":"chainHiddenInPopover"),children:qe("button",{className:"prompt-action-btn"+(t?" active":""),onClick:n=>{n.stopPropagation(),w(e.id,{showInSelectionPopover:!t});},children:qe(tn,{size:15})})}), qe(Sd,{content:le("copy"),children:qe("button",{className:"prompt-action-btn",onClick:t=>{t.stopPropagation(),C(e.id)&&Gi(le("chainDuplicated"),1800);},children:qe(Nt,{size:15})})}), qe(Sd,{content:le("delete"),children:qe("button",{className:"prompt-action-btn danger",onClick:t=>{t.stopPropagation(),we(le("confirmDelete"),le("chainDeleteConfirm"),()=>{S(e.id),Gi(le("deleted"),1800);});},children:qe(Wt,{size:15})})})]})]},e.id);var o;})]}):0===pt.length?qe("div",{style:{textAlign:"center",padding:"40px 20px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"14px"},children:"暂无提示词"}):pt.map(t=>{const n=r===t.id,i=he===t.id,a=n||i; return Re("div",{"data-prompt-id":t.id,className:`prompt-item ${a?"selected":""} ${i?"located":""} ${H===t.id?"dragging":""}`,onClick:()=>{return e=t,ge(null),void(o?(null!==ce.current&&(window.clearTimeout(ce.current),ce.current=null),ce.current=window.setTimeout(()=>{ce.current=null,He(e);},340)):He(e));var e;},onDoubleClick:()=>{return e=t,null!==ce.current&&(window.clearTimeout(ce.current),ce.current=null),void(o&&He(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():(W(t),j.current=n,G.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",!H||H===t)return;const n=e.currentTarget,r=n.getBoundingClientRect(),o=r.top+r.height/2,i=n.getRootNode();G.current=i,dt(),e.clientY(async(t,n)=>{if(t.preventDefault(),!H||H===n)return void ut();const r=e.getPrompts(),o=r.findIndex(e=>e.id===H),i=r.findIndex(e=>e.id===n);if(-1===o||-1===i)return void ut();const a=[...r],[s]=a.splice(o,1),l=t.currentTarget.getBoundingClientRect(),c=t.clientYe.id===n);oe.id)),Gi(le("orderUpdated")),ye(),ut();})(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:[ Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[ qe("div",{style:{fontWeight:600,fontSize:"14px",color:"var(--gh-text, #1f2937)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:"8px"},children:t.title}), qe("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")})]}), qe("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}), Re("div",{className:"prompt-item-actions",style:{position:"absolute",top:"8px",right:"8px",gap:"2px"},children:[ qe(Sd,{content:t.pinned?le("promptUnpin"):le("promptPin"),children:qe("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),e.togglePin(t),ye();})(t.id,n),className:"prompt-action-btn"+(t.pinned?" active":""),children:qe(jt,{size:16,filled:t.pinned})})}), qe(Sd,{content:le("promptMarkdownPreview"),children:qe("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),se({show:true,prompt:t});},className:"prompt-action-btn",children:qe(Gt,{size:16})})}), qe(Sd,{content:le("copy"),children:qe("button",{onClick:e=>(async(e,t)=>{t.stopPropagation(),t.preventDefault();try{await navigator.clipboard.writeText(e),Gi(le("copied"));}catch{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Gi(le("copied"));}})(t.content,e),className:"prompt-action-btn",children:qe(Nt,{size:16})})}), qe(Sd,{content:le("more"),children:qe("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),me({prompt:t,anchorEl:e.currentTarget});},className:"prompt-action-btn",children:qe(Rt,{size:16})})}), qe(Sd,{content:le("edit"),children:qe("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),lt(t);},className:"prompt-action-btn",children:qe(Ht,{size:16})})}), qe(Sd,{content:le("delete"),children:qe("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),we(le("confirmDelete"),"确定删除该提示词?",async()=>{await e.deletePrompt(t),Gi(le("deleted")),ye();});})(t.id,n),className:"prompt-action-btn danger",children:qe(Wt,{size:16})})})]})]},t.id)})}), qe("div",{style:{padding:"12px"},children:Re("button",{onClick:()=>{"chains"!==b?lt():Ce();},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:[ qe("span",{children:"+"}), qe("span",{children:le("chains"===b?"chainAdd":"addPrompt")})]})}),T?gd( qe("div",{className:"prompt-modal gh-interactive",...ms,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:Re("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:[ qe("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:le(M?.id?"editPrompt":"addNewPrompt")}), Re("div",{style:{marginBottom:"16px"},children:[ qe("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:le("title")}), qe("input",{type:"text",value:M?.title||"",onChange:e=>I({...M,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)"}})]}), Re("div",{style:{marginBottom:"16px"},children:[ qe("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:le("category")}), qe("input",{type:"text",value:M?.category||"",onChange:e=>I({...M,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)"}}),u.length>0&&qe("div",{style:{marginTop:"6px",display:"flex",gap:"4px",flexWrap:"wrap",userSelect:"none"},children:u.map(e=>qe("span",{onClick:()=>I({...M,category:e}),style:{padding:"2px 8px",fontSize:"11px",background:M?.category===e?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:M?.category===e?"var(--gh-text-on-primary, white)":"var(--gh-text-secondary, #6b7280)",borderRadius:"10px",cursor:"pointer",transition:"all 0.15s"},children:e},e))})]}), qe("div",{style:{marginBottom:"16px"},children:Re("div",{children:[ Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[ qe("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)"},children:le("content")}), qe("button",{onClick:()=>ie(!oe),style:{padding:"2px 8px",fontSize:"12px",background:oe?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:oe?"white":"var(--gh-text-secondary, #6b7280)",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"4px",cursor:"pointer"},children:le("promptMarkdownPreview")})]}), qe("textarea",{value:M?.content||"",onChange:e=>I({...M,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:oe?"none":"block"}}),oe&&Re(Ne,{children:[ qe("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:fe,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{Ed(t,{size:14});});}},dangerouslySetInnerHTML:{__html:gu(tc(M?.content||""))}}), qe("style",{children:nc()})]})]})}), Re("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end",marginTop:"24px"},children:[ qe(xb,{variant:"ghost",onClick:et,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("cancel")}), qe(xb,{variant:"primary",onClick:Je,children:le(M?.id?"save":"add")})]})]})}),document.body):null,D?gd( qe("div",{className:"prompt-modal gh-interactive",...ms,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:Re("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:[ qe("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:le("categoryManage")}), qe("div",{style:{maxHeight:"300px",overflowY:"auto"},children:0===u.length?qe("div",{style:{textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)",padding:"20px"},children:le("categoryEmpty")}):u.map(t=>{const n=c.filter(e=>e.category===t).length; return Re("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ Re("div",{children:[ qe("div",{style:{fontWeight:500,color:"var(--gh-text, #374151)"},children:t}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-tertiary, #9ca3af)"},children:[n," ",le("promptCountSuffix")]})]}), Re("div",{style:{display:"flex",gap:"8px"},children:[ qe(Sd,{content:le("rename"),children:qe(xb,{size:"sm",onClick:e=>ct(t,e),style:{color:"var(--gh-primary, #4285f4)"},children:le("rename")})}), qe(Sd,{content:le("delete"),children:qe(xb,{size:"sm",onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),we(le("confirmDeleteCategory"),le("confirmDeleteCategoryMsg").replace("{name}",t),async()=>{await e.deleteCategory(t),Gi(le("categoryDeletedMsg").replace("{name}",t)),g===t&&p(Ro),ye();});})(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)})}), qe("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:qe(xb,{variant:"ghost",onClick:tt,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("close")})})]})}),document.body):null,ae.show&&ae.prompt?gd( qe("div",{className:"prompt-preview-modal gh-interactive",...ms,onClick:e=>{e.target===e.currentTarget&&ot();},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:Re("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:[ Re("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("div",{children:[ qe("div",{style:{fontSize:"16px",fontWeight:600,color:"var(--gh-text, #1f2937)"},children:ae.prompt.title}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:ae.prompt.category})]}), qe("button",{onClick:ot,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:qe($e,{size:16})})]}), qe("div",{className:"gh-markdown-preview",style:{flex:1,padding:"20px",overflowY:"auto"},ref:be,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{Ed(t,{size:14});});}},dangerouslySetInnerHTML:{__html:gu(tc(ae.prompt.content))}}), qe("style",{children:nc()})]})}),document.body):null,J.show?gd( qe("div",{className:"import-dialog gh-interactive",...ms,onClick:e=>{e.target===e.currentTarget&&it();},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:Re("div",{style:{width:"90%",maxWidth:"400px",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",padding:"24px"},children:[ qe("div",{style:{fontSize:"16px",fontWeight:600,marginBottom:"12px",color:"var(--gh-text)"},children:le("promptImportTitle")}), Re("div",{style:{fontSize:"14px",color:"var(--gh-text-secondary)",marginBottom:"20px",lineHeight:1.6},children:[le("promptImportMessage2").replace("{count}",J.prompts.length.toString()), Re("ul",{style:{margin:"8px 0 0 0",paddingLeft:"20px"},children:[ qe("li",{children:le("promptImportOverwriteDesc")}), qe("li",{children:le("promptImportMergeDesc")})]})]}), Re("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end"},children:[ qe(xb,{variant:"ghost",onClick:it,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("cancel")}), qe(xb,{variant:"ghost",onClick:Xe,style:{background:"var(--gh-primary-light, #e3f2fd)",color:"var(--gh-primary, #4285f4)"},children:le("promptMerge")}), qe(xb,{variant:"primary",onClick:Ke,children:le("promptOverwrite")})]})]})}),document.body):null,(()=>{if(!N.show||!N.draft)return null;const e=N.draft,t=mt(e);return gd( Re(Ne,{children:[ qe("style",{children:'\n.gh-chain-editor {\n width: min(680px, 92vw);\n max-height: 86vh;\n padding: 0 !important;\n border-radius: 12px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n box-shadow: var(--gh-shadow-lg, 0 20px 50px rgba(0, 0, 0, 0.3));\n display: flex;\n flex-direction: column;\n overflow: hidden;\n animation: slideUp 0.25s ease-out;\n}\n\n.gh-chain-editor-header,\n.gh-chain-editor-footer {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n padding: 16px 18px;\n border-bottom: 1px solid var(--gh-border, #e5e7eb);\n}\n\n.gh-chain-editor-footer {\n justify-content: flex-end;\n border-top: 1px solid var(--gh-border, #e5e7eb);\n border-bottom: none;\n}\n\n.gh-chain-editor-title {\n color: var(--gh-text, #1f2937);\n font-size: 16px;\n font-weight: 650;\n}\n\n.gh-chain-editor-subtitle,\n.gh-chain-section-subtitle,\n.gh-chain-field-help {\n color: var(--gh-text-tertiary, #9ca3af);\n font-size: 12px;\n line-height: 1.45;\n}\n\n.gh-chain-editor-close {\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: var(--gh-hover, #f3f4f6);\n color: var(--gh-text-secondary, #6b7280);\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n}\n\n.gh-chain-editor-scroll {\n min-height: 0;\n flex: 1;\n overflow-y: auto;\n padding: 16px 18px;\n overscroll-behavior: contain;\n scrollbar-gutter: stable;\n scrollbar-width: thin;\n scrollbar-color: color-mix(in srgb, var(--gh-text-tertiary, #9ca3af) 64%, transparent)\n transparent;\n}\n\n.gh-chain-editor-scroll::-webkit-scrollbar {\n width: 10px;\n}\n\n.gh-chain-editor-scroll::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.gh-chain-editor-scroll::-webkit-scrollbar-thumb {\n min-height: 42px;\n border: 3px solid transparent;\n border-radius: 999px;\n background: color-mix(in srgb, var(--gh-text-tertiary, #9ca3af) 56%, transparent);\n background-clip: content-box;\n}\n\n.gh-chain-editor-scroll::-webkit-scrollbar-thumb:hover {\n background: color-mix(in srgb, var(--gh-text-secondary, #6b7280) 72%, transparent);\n background-clip: content-box;\n}\n\n.gh-chain-form-grid {\n display: grid;\n grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n gap: 12px;\n}\n\n.gh-chain-field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n margin-bottom: 14px;\n color: var(--gh-text, #374151);\n font-size: 13px;\n font-weight: 600;\n}\n\n.gh-chain-field input,\n.gh-chain-field textarea,\n.gh-chain-step-row select {\n width: 100%;\n box-sizing: border-box;\n border: 1px solid var(--gh-input-border, #d1d5db);\n border-radius: 7px;\n background: var(--gh-input-bg, var(--gh-bg, #ffffff));\n color: var(--gh-text, #1f2937);\n font: inherit;\n font-size: 13px;\n outline: none;\n}\n\n.gh-chain-field input,\n.gh-chain-step-row select {\n height: 34px;\n padding: 0 10px;\n}\n\n.gh-chain-field textarea {\n min-height: 74px;\n padding: 8px 10px;\n resize: vertical;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 12px;\n line-height: 1.45;\n}\n\n.gh-chain-field input:focus,\n.gh-chain-field textarea:focus,\n.gh-chain-step-row select:focus {\n border-color: var(--gh-primary, #4285f4);\n box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.12);\n}\n\n.gh-chain-icon-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n}\n\n.gh-chain-visibility-toggle {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n min-width: 0;\n max-width: 100%;\n padding: 5px 8px 5px 6px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 999px;\n background: var(--gh-bg-secondary, #f9fafb);\n color: var(--gh-text, #374151);\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n}\n\n.gh-chain-visibility-toggle input {\n position: absolute;\n opacity: 0;\n pointer-events: none;\n}\n\n.gh-chain-visibility-switch {\n position: relative;\n width: 28px;\n height: 16px;\n flex: 0 0 28px;\n border-radius: 999px;\n background: var(--gh-border, #d1d5db);\n transition: background 0.16s;\n}\n\n.gh-chain-visibility-switch::after {\n content: "";\n position: absolute;\n top: 2px;\n left: 2px;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: #ffffff;\n box-shadow: 0 1px 2px rgba(15, 23, 42, 0.18);\n transition: transform 0.16s;\n}\n\n.gh-chain-visibility-toggle input:checked + .gh-chain-visibility-switch {\n background: var(--gh-primary, #4285f4);\n}\n\n.gh-chain-visibility-toggle input:checked + .gh-chain-visibility-switch::after {\n transform: translateX(12px);\n}\n\n.gh-chain-visibility-toggle-text {\n min-width: 0;\n line-height: 1.25;\n}\n\n.gh-chain-icon-control-row {\n display: flex;\n align-items: center;\n gap: 10px;\n}\n\n.gh-chain-icon-preview {\n min-width: 0;\n flex: 1;\n display: flex;\n align-items: center;\n gap: 10px;\n min-height: 44px;\n padding: 10px 14px;\n box-sizing: border-box;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 8px;\n background: var(--gh-bg-secondary, #f9fafb);\n color: var(--gh-text-secondary, #6b7280);\n font-size: 14px;\n font-weight: 500;\n}\n\n.gh-chain-icon-preview.empty {\n color: var(--gh-text-tertiary, #9ca3af);\n font-weight: 400;\n}\n\n.gh-chain-icon-preview-svg {\n width: 22px;\n height: 22px;\n flex: 0 0 22px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n}\n\n.gh-chain-icon-preview-svg svg {\n width: 22px;\n height: 22px;\n}\n\n.gh-chain-icon-select-btn {\n min-height: 44px;\n padding: 0 18px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 8px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-primary, #3b82f6);\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n white-space: nowrap;\n transition:\n background 0.16s,\n border-color 0.16s;\n}\n\n.gh-chain-icon-select-btn:hover {\n border-color: var(--gh-primary, #3b82f6);\n background: var(--gh-primary-light, #eff6ff);\n}\n\n.gh-chain-editor-section {\n margin-top: 14px;\n padding-top: 14px;\n border-top: 1px solid var(--gh-border, #e5e7eb);\n}\n\n.gh-chain-queue-gate {\n display: flex;\n align-items: stretch;\n flex-direction: column;\n justify-content: flex-start;\n gap: 10px;\n margin: 0 0 12px;\n padding: 12px;\n border: 1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 22%, var(--gh-border, #e5e7eb));\n border-radius: 8px;\n background: color-mix(in srgb, var(--gh-primary, #4285f4) 7%, var(--gh-bg, #ffffff));\n}\n\n.gh-chain-queue-gate.editor {\n margin-bottom: 14px;\n}\n\n.gh-chain-queue-gate-copy {\n min-width: 0;\n width: 100%;\n}\n\n.gh-chain-queue-gate-title {\n color: var(--gh-text, #111827);\n font-size: 13px;\n font-weight: 700;\n line-height: 1.3;\n}\n\n.gh-chain-queue-gate-description {\n margin-top: 3px;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 12px;\n line-height: 1.4;\n}\n\n.gh-chain-queue-gate-actions {\n display: inline-flex;\n align-items: center;\n justify-content: flex-start;\n gap: 8px;\n flex-wrap: wrap;\n}\n\n.gh-chain-section-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n margin-bottom: 10px;\n}\n\n.gh-chain-section-title {\n color: var(--gh-text, #1f2937);\n font-size: 13px;\n font-weight: 650;\n}\n\n.gh-chain-step-list {\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n\n.gh-chain-step-row {\n display: flex;\n flex-direction: column;\n gap: 0;\n padding: 14px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 10px;\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);\n transition: all 0.2s ease;\n}\n\n.gh-chain-step-row:hover {\n border-color: var(--gh-border-hover, #d1d5db);\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n}\n\n.gh-chain-step-row.dragging {\n opacity: 0.5;\n cursor: grabbing;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n}\n\n.gh-chain-step-header-row {\n display: flex;\n align-items: center;\n gap: 10px;\n margin-bottom: 12px;\n}\n\n.gh-chain-step-drag-handle {\n width: 16px;\n height: 20px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n color: var(--gh-text-tertiary, #c5c8cc);\n cursor: grab;\n flex-shrink: 0;\n transition: color 0.15s;\n}\n\n.gh-chain-step-drag-handle:hover {\n color: var(--gh-text-secondary, #6b7280);\n}\n\n.gh-chain-step-row.dragging .gh-chain-step-drag-handle {\n cursor: grabbing;\n}\n\n.gh-chain-step-index {\n width: 22px;\n height: 22px;\n border-radius: 6px;\n background: var(--gh-primary, #4285f4);\n color: #ffffff;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n font-size: 11px;\n font-weight: 700;\n flex-shrink: 0;\n}\n\n.gh-chain-step-mode-switch {\n display: flex;\n padding: 2px;\n border-radius: 7px;\n background: var(--gh-bg-secondary, #f3f4f6);\n border: 1px solid var(--gh-border, #e5e7eb);\n gap: 0;\n flex: 0 0 auto;\n}\n\n.gh-chain-step-mode-btn {\n padding: 4px 10px;\n border: none;\n border-radius: 5px;\n background: transparent;\n color: var(--gh-text-tertiary, #9ca3af);\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.15s ease;\n white-space: nowrap;\n line-height: 1.4;\n}\n\n.gh-chain-step-mode-btn:hover {\n color: var(--gh-text-secondary, #6b7280);\n}\n\n.gh-chain-step-mode-btn.active {\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n font-weight: 600;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);\n}\n\n.gh-chain-step-delete-btn {\n width: 28px;\n height: 28px;\n margin-left: auto;\n flex-shrink: 0;\n border-radius: 7px;\n border: none;\n background: transparent;\n color: var(--gh-text-tertiary, #d1d5db);\n opacity: 0;\n transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n position: relative;\n}\n\n.gh-chain-step-row:hover .gh-chain-step-delete-btn {\n opacity: 1;\n}\n\n.gh-chain-step-delete-btn:hover {\n background: rgba(254, 226, 226, 1);\n color: var(--gh-text-danger, #ef4444);\n transform: scale(1.05);\n}\n\n.gh-chain-step-delete-btn:active {\n transform: scale(0.95);\n background: rgba(254, 202, 202, 1);\n}\n\n.gh-chain-step-delete-btn svg {\n width: 16px;\n height: 16px;\n stroke-width: 2.5;\n}\n\n.gh-chain-step-input-row {\n width: 100%;\n}\n\n.gh-chain-step-inline-input {\n width: 100%;\n box-sizing: border-box;\n min-height: 80px;\n padding: 10px 12px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 8px;\n background: var(--gh-bg-secondary, #f9fafb);\n color: var(--gh-text, #1f2937);\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 12px;\n line-height: 1.55;\n resize: vertical;\n outline: none;\n transition: all 0.15s;\n}\n\n.gh-chain-step-inline-input:focus {\n border-color: var(--gh-primary, #4285f4);\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.08);\n}\n\n.gh-chain-step-inline-input::placeholder {\n color: var(--gh-text-tertiary, #9ca3af);\n}\n\n.gh-chain-step-prompt-select {\n width: 100%;\n height: 36px;\n padding: 0 10px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 8px;\n background: var(--gh-bg-secondary, #f9fafb);\n color: var(--gh-text, #1f2937);\n font-size: 13px;\n outline: none;\n transition: all 0.15s;\n cursor: pointer;\n}\n\n.gh-chain-step-prompt-select:focus {\n border-color: var(--gh-primary, #4285f4);\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.08);\n}\n\n.gh-chain-step-actions {\n display: flex;\n gap: 2px;\n}\n\n.gh-chain-step-empty {\n padding: 20px;\n border: 1.5px dashed var(--gh-border, #d1d5db);\n border-radius: 10px;\n color: var(--gh-text-tertiary, #9ca3af);\n font-size: 13px;\n text-align: center;\n}\n\n.gh-chain-variable-preview {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n margin-top: 8px;\n}\n\n.gh-chain-variable-chip,\n.gh-chain-variable-muted {\n padding: 4px 7px;\n border-radius: 999px;\n font-size: 12px;\n line-height: 1.25;\n}\n\n.gh-chain-variable-chip {\n border: 1px solid rgba(66, 133, 244, 0.25);\n background: rgba(66, 133, 244, 0.08);\n color: var(--gh-primary, #4285f4);\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n}\n\n.gh-chain-variable-chip.custom {\n border-color: var(--gh-border, #e5e7eb);\n background: var(--gh-bg-secondary, #f9fafb);\n color: var(--gh-text-secondary, #6b7280);\n}\n\n.gh-chain-variable-muted {\n color: var(--gh-text-tertiary, #9ca3af);\n}\n\n.gh-chain-preview-section {\n position: relative;\n}\n\n.gh-chain-preview-toggle {\n padding: 5px 12px;\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 6px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text-secondary, #6b7280);\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.15s;\n}\n\n.gh-chain-preview-toggle:hover {\n background: var(--gh-hover, #f3f4f6);\n color: var(--gh-text, #1f2937);\n}\n\n.gh-chain-preview-nav-float {\n position: sticky;\n top: 0;\n z-index: 10;\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 8px 12px;\n margin: 12px 0 0;\n border-radius: 8px;\n background: var(--gh-bg, rgba(255, 255, 255, 0.92));\n backdrop-filter: blur(8px);\n border: 1px solid var(--gh-border, #e5e7eb);\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n flex-wrap: wrap;\n}\n\n.gh-chain-preview-nav-label {\n color: var(--gh-text-tertiary, #9ca3af);\n font-size: 11px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-right: 4px;\n flex-shrink: 0;\n}\n\n.gh-chain-preview-nav-btn {\n min-width: 28px;\n height: 26px;\n padding: 0 8px;\n border: 1px solid transparent;\n border-radius: 6px;\n background: transparent;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: all 0.15s;\n gap: 4px;\n max-width: 140px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.gh-chain-preview-nav-btn:hover {\n background: rgba(66, 133, 244, 0.08);\n color: var(--gh-primary, #4285f4);\n}\n\n.gh-chain-preview-nav-btn .nav-btn-num {\n flex-shrink: 0;\n width: 18px;\n height: 18px;\n border-radius: 4px;\n background: var(--gh-bg-secondary, #f3f4f6);\n display: inline-flex;\n align-items: center;\n justify-content: center;\n font-size: 10px;\n font-weight: 700;\n}\n\n.gh-chain-preview-nav-btn .nav-btn-title {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-weight: 500;\n}\n\n.gh-chain-preview-nav-btn:hover .nav-btn-num {\n background: rgba(66, 133, 244, 0.15);\n color: var(--gh-primary, #4285f4);\n}\n\n.gh-chain-preview-content {\n display: flex;\n flex-direction: column;\n gap: 12px;\n margin-top: 8px;\n padding-bottom: 4px;\n}\n\n.gh-chain-preview-step {\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 10px;\n overflow: hidden;\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);\n transition: box-shadow 0.15s;\n}\n\n.gh-chain-preview-step:hover {\n box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);\n}\n\n.gh-chain-preview-step-header {\n padding: 10px 14px;\n background: var(--gh-bg-secondary, #f9fafb);\n border-bottom: 1px solid var(--gh-border, #e5e7eb);\n display: flex;\n align-items: center;\n gap: 10px;\n}\n\n.gh-chain-preview-step-number {\n width: 22px;\n height: 22px;\n border-radius: 6px;\n background: var(--gh-primary, #4285f4);\n color: #ffffff;\n font-size: 11px;\n font-weight: 700;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n}\n\n.gh-chain-preview-step-title {\n color: var(--gh-text, #1f2937);\n font-size: 13px;\n font-weight: 600;\n flex: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.gh-chain-preview-step-body {\n padding: 14px;\n color: var(--gh-text, #1f2937);\n font-size: 13px;\n line-height: 1.6;\n word-break: break-word;\n max-height: 360px;\n overflow-y: auto;\n}\n\n.gh-chain-preview-step-body p {\n margin: 0 0 0.75em;\n}\n\n.gh-chain-preview-step-body p:last-child {\n margin-bottom: 0;\n}\n\n.gh-chain-preview-step-body code {\n padding: 2px 5px;\n border-radius: 4px;\n background: var(--gh-bg-secondary, #f3f4f6);\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 0.88em;\n}\n\n.gh-chain-preview-step-body pre {\n margin: 0.75em 0;\n padding: 12px;\n border-radius: 8px;\n background: var(--gh-bg-secondary, #f3f4f6);\n overflow-x: auto;\n}\n\n.gh-chain-preview-step-body pre code {\n padding: 0;\n background: none;\n}\n\n.gh-chain-preview-step-body blockquote {\n margin: 0.75em 0;\n padding: 8px 14px;\n border-left: 3px solid var(--gh-primary, #4285f4);\n background: rgba(66, 133, 244, 0.04);\n border-radius: 0 6px 6px 0;\n color: var(--gh-text-secondary, #6b7280);\n}\n\n.gh-chain-preview-empty {\n color: var(--gh-text-tertiary, #9ca3af);\n font-style: italic;\n}\n\n.prompt-action-btn:disabled {\n opacity: 0.35;\n cursor: not-allowed;\n}\n\n@media (max-width: 520px) {\n .gh-chain-form-grid {\n grid-template-columns: 1fr;\n }\n\n .gh-chain-icon-header,\n .gh-chain-icon-control-row {\n align-items: stretch;\n flex-direction: column;\n }\n\n .gh-chain-visibility-toggle,\n .gh-chain-icon-select-btn {\n width: 100%;\n justify-content: center;\n }\n\n .gh-chain-step-header-row {\n flex-wrap: wrap;\n }\n\n .gh-chain-step-mode-switch {\n order: 10;\n width: 100%;\n margin-top: 4px;\n }\n\n .gh-chain-preview-nav-float {\n position: static;\n backdrop-filter: none;\n }\n}\n'}), qe("div",{className:"prompt-modal gh-interactive",...ms,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:2147483646,animation:"fadeIn 0.2s"},children:Re("div",{className:"prompt-modal-content gh-chain-editor",onClick:e=>e.stopPropagation(),children:[ Re("div",{className:"gh-chain-editor-header",children:[ Re("div",{children:[ qe("div",{className:"gh-chain-editor-title",children:e.id?le("chainEditorEditTitle"):le("chainEditorNewTitle")}), qe("div",{className:"gh-chain-editor-subtitle",children:le("chainEditorSubtitle")})]}), qe("button",{className:"gh-chain-editor-close",onClick:ke,children:qe($e,{size:18})})]}), Re("div",{className:"gh-chain-editor-scroll",children:[yt("editor"),vt("editor"), Re("div",{className:"gh-chain-form-grid",children:[ Re("label",{className:"gh-chain-field",children:[ qe("span",{children:le("chainName")}), qe("input",{type:"text",value:e.title,onChange:e=>Te({title:e.target.value}),placeholder:le("chainNamePlaceholder")})]}), Re("label",{className:"gh-chain-field",children:[ qe("span",{children:le("chainDescription")}), qe("input",{type:"text",value:e.description||"",onChange:e=>Te({description:e.target.value}),placeholder:le("chainDescriptionPlaceholder")})]})]}), Re("div",{className:"gh-chain-field",children:[ Re("div",{className:"gh-chain-icon-header",children:[ qe("span",{children:le("chainIconSvg")}), Re("label",{className:"gh-chain-visibility-toggle",children:[ qe("input",{type:"checkbox",checked:false!==e.showInSelectionPopover,onChange:e=>Te({showInSelectionPopover:e.target.checked})}), qe("span",{className:"gh-chain-visibility-switch","aria-hidden":"true"}), qe("span",{className:"gh-chain-visibility-toggle-text",children:le("chainShowInPopover")})]})]}), Re("div",{className:"gh-chain-icon-control-row",children:[e.iconSvg?Re("div",{className:"gh-chain-icon-preview",children:[ qe(Ob,{className:"gh-chain-icon-preview-svg",svg:e.iconSvg}), qe("span",{children:le("chainIconSelected")})]}):qe("div",{className:"gh-chain-icon-preview empty",children:le("chainIconNotSelected")}), qe("button",{type:"button",onClick:()=>P(true),className:"gh-chain-icon-select-btn",children:le("chainIconSelect")})]})]}), Re("div",{className:"gh-chain-editor-section",children:[ Re("div",{className:"gh-chain-section-header",children:[ Re("div",{children:[ qe("div",{className:"gh-chain-section-title",children:le("chainSteps")}), qe("div",{className:"gh-chain-section-subtitle",children:le("chainStepsHelp")})]}), qe(xb,{variant:"ghost",size:"sm",onClick:De,children:le("chainAddStep")})]}), qe("div",{className:"gh-chain-step-list",children:0===e.steps.length?qe("div",{className:"gh-chain-step-empty",children:le("chainNoSteps")}):e.steps.map((e,t)=>Re("div",{className:"gh-chain-step-row"+(N.draggedStepId===e.id?" dragging":""),draggable:true,onDragStart:()=>{return t=e.id,void q(e=>({...e,draggedStepId:t}));var t;},onDragOver:t=>((e,t)=>{e.preventDefault();const n=N.draggedStepId;n&&n!==t&&q(e=>{if(!e.draft)return e;const r=[...e.draft.steps],o=r.findIndex(e=>e.id===n),i=r.findIndex(e=>e.id===t);if(-1===o||-1===i)return e;const[a]=r.splice(o,1);return r.splice(i,0,a),{...e,draft:{...e.draft,steps:r}}});})(t,e.id),onDragEnd:Be,children:[ Re("div",{className:"gh-chain-step-header-row",children:[ qe("div",{className:"gh-chain-step-drag-handle",title:le("drag"),children:Re("svg",{viewBox:"0 0 16 16",width:"16",height:"16",fill:"currentColor",children:[ qe("circle",{cx:"6",cy:"4",r:"1.2"}), qe("circle",{cx:"10",cy:"4",r:"1.2"}), qe("circle",{cx:"6",cy:"8",r:"1.2"}), qe("circle",{cx:"10",cy:"8",r:"1.2"}), qe("circle",{cx:"6",cy:"12",r:"1.2"}), qe("circle",{cx:"10",cy:"12",r:"1.2"})]})}), qe("div",{className:"gh-chain-step-index",children:t+1}), Re("div",{className:"gh-chain-step-mode-switch",children:[ qe("button",{type:"button",className:"gh-chain-step-mode-btn"+("inline"!==e.mode?" active":""),onClick:()=>Pe(e.id,{mode:"prompt",inlineContent:""}),children:le("chainStepModePrompt")}), qe("button",{type:"button",className:"gh-chain-step-mode-btn"+("inline"===e.mode?" active":""),onClick:()=>Pe(e.id,{mode:"inline",promptId:""}),children:le("chainStepModeInline")})]}), qe(Sd,{content:le("delete"),children:qe("button",{className:"gh-chain-step-delete-btn",onClick:t=>{var n;t.stopPropagation(),n=e.id,q(e=>e.draft?{...e,draft:{...e.draft,steps:e.draft.steps.filter(e=>e.id!==n)}}:e);},children:qe(Wt,{size:14})})})]}), qe("div",{className:"gh-chain-step-input-row",children:"inline"===e.mode?qe("textarea",{className:"gh-chain-step-inline-input",value:e.inlineContent||"",onChange:t=>Pe(e.id,{inlineContent:t.target.value}),placeholder:le("chainStepInlinePlaceholder"),rows:4}):Re("select",{className:"gh-chain-step-prompt-select",value:e.promptId,onChange:t=>Pe(e.id,{promptId:t.target.value}),children:[ qe("option",{value:"",children:le("chainSelectPrompt")}),c.map(e=>qe("option",{value:e.id,children:e.title},e.id))]})})]},e.id))})]}), Re("div",{className:"gh-chain-editor-section",children:[ qe("div",{className:"gh-chain-section-title",children:le("chainVariablesPreview")}), Re("div",{className:"gh-chain-variable-preview",children:[ qe("span",{className:"gh-chain-variable-chip",children:"{{selection}}"}), qe("span",{className:"gh-chain-variable-chip",children:"{{quote}}"}),0===t.length?qe("span",{className:"gh-chain-variable-muted",children:le("chainVariablesNone")}):t.map(e=>qe("span",{className:"gh-chain-variable-chip custom",children:`{{${e.raw}}}`},e.raw))]})]}),e.steps.length>0&&Re("div",{className:"gh-chain-editor-section gh-chain-preview-section",children:[ Re("div",{className:"gh-chain-section-header",style:{marginBottom:0},children:[ qe("div",{className:"gh-chain-section-title",children:le("chainExecutionPreview")}), qe("button",{type:"button",className:"gh-chain-preview-toggle",onClick:()=>q(e=>({...e,showExecutionPreview:!e.showExecutionPreview})),children:N.showExecutionPreview?le("collapse"):le("expand")})]}),N.showExecutionPreview&&Re(Ne,{children:[ Re("div",{className:"gh-chain-preview-nav-float",children:[ qe("span",{className:"gh-chain-preview-nav-label",children:le("chainSteps")}),e.steps.map((t,n)=>{const r=ft(e)[n]||`Step ${n+1}`; return qe(Sd,{content:r,children:Re("button",{type:"button",className:"gh-chain-preview-nav-btn",onClick:()=>{document.getElementById(`chain-preview-step-${n}`)?.scrollIntoView({behavior:"smooth",block:"nearest"});},children:[ qe("span",{className:"nav-btn-num",children:n+1}), qe("span",{className:"nav-btn-title",children:r})]})},t.id)})]}), qe("div",{className:"gh-chain-preview-content",children:bt(e).map((t,n)=>Re("div",{id:`chain-preview-step-${n}`,className:"gh-chain-preview-step",children:[ Re("div",{className:"gh-chain-preview-step-header",children:[ qe("span",{className:"gh-chain-preview-step-number",children:n+1}), qe("span",{className:"gh-chain-preview-step-title",children:ft(e)[n]||le("chainStep")})]}), qe("div",{className:"gh-chain-preview-step-body",dangerouslySetInnerHTML:{__html:gu(t?tc(t):`${le("chainStepContentEmpty")}`)}})]},n))})]})]})]}), Re("div",{className:"gh-chain-editor-footer",children:[ qe(xb,{variant:"ghost",onClick:ke,style:{background:"var(--gh-hover, #f3f4f6)"},children:le("cancel")}), qe(xb,{variant:"primary",onClick:_e,children:e.id?le("save"):le("add")})]})]})})]}),document.body)})(),O.show&&qe(yb,{title:O.title,message:O.message,danger:true,closeOnOverlayClick:false,onConfirm:()=>{nt(),O.onConfirm();},onCancel:nt}),F.show&&qe(vb,{title:F.title,defaultValue:F.defaultValue,closeOnOverlayClick:false,onConfirm:e=>{rt(),F.onConfirm(e);},onCancel:rt}),Y.show&&qe(Wb,{variables:Y.variables,onConfirm:async e=>{const{prompt:t,submitAfterInsert:n,enqueueAfterResolve:r,enqueueSplitByLine:o}=Y;if(!t)return;const i=Ub(t.content,e);X({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e());});}),n?await je(t,i):r?Ge(t,i,o):await We(t,i);},onCancel:at}),pe&&Re(Rv,{anchorEl:pe.anchorEl,onClose:st,children:[ qe(Pv,{onClick:()=>{Qe(pe.prompt),st();},children:Re("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe(dn,{size:14}), qe("span",{children:le("promptAddToQueue")})]})}), qe(Pv,{onClick:()=>{Qe(pe.prompt,true),st();},children:Re("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe(un,{size:14}), qe("span",{children:le("promptSplitLinesToQueue")})]})})]}),R&&N.draft&&gd( qe("div",{className:"prompt-modal gh-interactive",...ms,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:2147483647},onClick:()=>P(false),children:qe("div",{onClick:e=>e.stopPropagation(),children:qe(hx,{value:N.draft.iconSvg,onChange:(e,t)=>{Te({iconSvg:t}),P(false);},onClose:()=>P(false)})})}),document.body), qe("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 "})]})},vx=({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}=zi(),T=S||gi,A=T.features?.order||gi.features.order,M=l?.getSiteId()||"_default",I=pi(T,M),N=d||("dark"===I.mode?"dark":"light"),q="light"===N?I.lightStyleId||"google-gradient":I.darkStyleId||"classic-dark",R="dark"===N?"brand":"currentColor",B=Array.isArray(T.theme?.customStyles)?T.theme.customStyles.find(e=>e.id===q):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,Lv)}),[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+Lv>r&&(i=r-o.height-Lv),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,Lv):o.top;s+o.width+0>t&&(s=t-o.width-0),l+o.height+Lv>r&&(l=r-o.height-Lv),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 Q=T.panel?.defaultPosition??"right",V=T.panel?.defaultEdgeDistance??40,K="edge-snap"===(T.panel?.panelMode??"edge-snap"),Z=T.panel?.width??320,Y=T.panel?.height??85,X=D(()=>{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"===Q?{left:`${V}px`,right:"auto"}:{right:`${V}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=D(()=>Iv(T.shortcuts?.keybindings,mr(),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]:fr,[we,Se]=_(fr),[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(br);},t=()=>{Se(yr);},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?vs(e):void 0},[t,z]);const Te=null!==O(Xy,Jy),[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 ou({adapter:l||null,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{Be(`${le("loadingHistory")} ${e}`);}});Yy(t.previousScrollTop),n&&(clearTimeout(n),n=null),Ie(!1),Be(""),t.success&&!t.silent&&Gi(le("historyLoaded"),2e3);}finally{clearInterval(t),n&&clearTimeout(n);}},[l]),Fe=E(()=>{$e.current=true;},[]),He=E(async()=>{const{previousScrollTop:e}=await Qd(l||null);Yy(e);},[l]),Ge=E(async()=>{const e=Zy();if(null===e)return;Ae(e=>e+1);const t=(await Zd(l||null)).scrollTop;await Vd(l||null,e),Yy(t);},[l]),Ve=E(async()=>{const e=await Zd(l||null);Yy(e.scrollTop);},[l]);if(!t)return null;const Ze=A.filter(e=>e!==vr&&((e!==fr||false!==T.features?.prompts?.enabled)&&((e!==yr||false!==T.features?.conversations?.enabled)&&(e!==br||false!==T.features?.outline?.enabled)))); return Re(Ne,{children:[ qe(Ev,{isVisible:Me,text:Le,onStop:Fe}), Re("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?qe("style",{children:B.css}):null, Re("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:[ Re("div",{style:{position:"relative"},onMouseEnter:fe,onMouseLeave:be,children:[ Re("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:[ Re("div",{style:{position:"relative",display:"flex",alignItems:"center"},children:[ qe(Jt,{size:18,color:R}),!oe&&qe("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"}})]}), qe("span",{style:{fontSize:"18px",fontWeight:600,userSelect:"none"},children:le("panelTitle")})]}), qe(Av,{isOpen:ee,onClose:ve,tips:ge,onMouseEnter:fe,onMouseLeave:be})]}), Re("div",{className:"gh-panel-controls","data-no-header-press-hint":"true",style:{display:"flex",gap:"1px",alignItems:"center"},children:[ qe(Sd,{content:"edge-snap"===(T.panel?.panelMode??"edge-snap")?le("pinPanel"):le("snapToEdge"),children:qe("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")?qe(rn,{size:14}):qe(nn,{size:14})})}),c&&qe(Sd,{content:le("toggleTheme"),children:qe("button",{onClick:e=>{c?.(w(e.currentTarget));},className:"gh-header-icon-btn",children:qe("dark"===d?Pe:De,{size:14})})}),T.tab?.openInNewTab&&qe(Sd,{content:le("newTabTooltip"),children:qe("button",{onClick:()=>window.open(window.location.origin,"_blank"),className:"gh-header-icon-btn",children:qe(ze,{size:14})})}), qe(Sd,{content:le("tabSettings"),children:qe("button",{"data-tip-target":"settings-btn",onClick:()=>{y?.();},className:"gh-header-icon-btn",children:qe(Ue,{size:14})})}), qe(Sd,{content:le("collapse"),children:qe("button",{onClick:e,"aria-label":le("collapse"),className:"gh-header-icon-btn",children:qe(We,{size:14})})})]})]}), Re("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:[ qe("span",{style:{fontSize:"14px",flexShrink:0,marginTop:"1px"},children:"👻"}), qe("span",{style:{lineHeight:"1.5"},children:le("tip1",{modifier:mr()?"⌘ Cmd":"Ctrl"})})]}), qe("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===br?t=je:e===fr?t=Qe:e===yr&&(t=Ke),Re("button",{"data-tip-target":e===br?"outline-tab":e===yr?"conversations-tab":e===fr?"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:[ qe("span",{style:{display:"flex",alignItems:"center"},children:t&&qe(t,{size:16})}), qe("span",{children:le(`tab${e.charAt(0).toUpperCase()+e.slice(1)}`)})]},e)})}), Re("div",{className:"gh-panel-content",style:{flex:1,overflowY:"auto",padding:"0",scrollbarWidth:"none",msOverflowStyle:"none"},children:[we===fr&&qe(yx,{manager:i,adapter:l,selectedPromptId:u,onPromptSelect:h}),we===yr&&qe(jv,{manager:a,onInteractionStateChange:b}),we===br&&qe(dx,{manager:s,conversationManager:a,onJumpBefore:Ve,isCodexOpen:ee})]}), Re("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:[ qe(Sd,{content:le("scrollTop"),triggerStyle:{flex:1,maxWidth:"120px"},children:Re("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:[ qe(it,{size:14}), qe("span",{children:le("scrollTop")})]})}), qe(Sd,{content:le(Te?"jumpToAnchor":"noAnchor"),triggerStyle:{flex:"0 0 32px"},children:qe("button",{className:"gh-interactive scroll-nav-btn anchor-btn",onClick:Ge,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:qe("span",{className:"anchor-tap-wrapper"+(Ee>0?" is-tapping":""),onAnimationEnd:()=>Ae(0),style:{display:"flex",alignItems:"center",justifyContent:"center"},children:qe("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)"},children:qe(_e,{size:14})})},Ee)})}), qe(Sd,{content:le("scrollBottom"),triggerStyle:{flex:1,maxWidth:"120px"},children:Re("button",{className:"gh-interactive scroll-nav-btn",onClick:He,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:[ qe(at,{size:14}), qe("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:8px;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:min(440px,calc(100vh - 32px));border-radius:14px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 18px 48px #0f172a29,0 3px 12px #0f172a14;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;min-height:48px;padding:10px 14px 9px;border-bottom:1px solid var(--gh-border-light, #f3f4f6);background:linear-gradient(180deg,var(--gh-bg, #ffffff) 0%,var(--gh-bg-secondary, #fafafa) 100%)}.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:30px;height:30px;border:none;border-radius:8px;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:10px;max-height:196px;background:var(--gh-bg, #ffffff);scrollbar-width:thin;scrollbar-color:transparent transparent}.gh-queue-list:hover{scrollbar-color:rgba(148,163,184,.45) transparent}.gh-queue-list::-webkit-scrollbar{width:7px}.gh-queue-list::-webkit-scrollbar-track{background:transparent}.gh-queue-list::-webkit-scrollbar-thumb{border:2px solid transparent;border-radius:999px;background:transparent;background-clip:padding-box}.gh-queue-list:hover::-webkit-scrollbar-thumb{background-color:#94a3b87a}.gh-queue-list:hover::-webkit-scrollbar-thumb:hover{background-color:#64748b9e}.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:grid;grid-template-columns:26px minmax(0,1fr) auto;align-items:start;gap:9px;padding:9px 10px 9px 9px;border:1px solid transparent;border-radius:8px;margin-bottom:6px;background:var(--gh-bg-secondary, #f8fafc);transition:background .15s,border-color .15s,box-shadow .15s}.gh-queue-item:hover{background:var(--gh-bg, #ffffff);border-color:var(--gh-border-light, #e5e7eb);box-shadow:0 1px 4px #0f172a0f}.gh-queue-item-index{width:22px;height:22px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-border, #d7dde6);border-radius:7px;background:var(--gh-bg, #ffffff);color:var(--gh-text-secondary, #64748b);font-size:11px;font-weight:700;line-height:1;margin-top:0}.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-main{display:flex;flex:1;min-width:0;flex-direction:column;gap:3px;align-items:flex-start;text-align:left}.gh-queue-item-chain{color:var(--gh-text-secondary, #64748b);font-size:11px;font-weight:700;line-height:1.25;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-item-actions{display:flex;align-items:center;gap:5px;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:28px;height:28px;border:none;border-radius:7px;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;transition:all .15s}.gh-queue-item-remove svg,.gh-queue-item-force-send svg,.gh-queue-item-edit svg{width:16px;height:16px}.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-color:#4285f447;background:var(--gh-bg-accent, #eef2ff);background:color-mix(in srgb,var(--gh-bg-accent, #eef2ff) 52%,var(--gh-bg, #ffffff));box-shadow:inset 0 0 0 1px #4285f414}.gh-queue-item[data-status=sending] .gh-queue-item-index{border-color:#4285f461;background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-item[data-status=sent]{opacity:.5}.gh-queue-item[data-status=failed]{border-color:#dc262638;background:var(--gh-bg-danger, #fef2f2)}.gh-queue-item[data-status=failed] .gh-queue-item-index{border-color:#dc262647;color:var(--gh-text-danger, #dc2626)}.gh-queue-input-area{padding:12px 14px 10px;border-top:1px solid var(--gh-border-light, #f3f4f6);background:var(--gh-bg, #ffffff)}.gh-queue-input-wrapper{display:flex;align-items:flex-end;gap:8px}.gh-queue-input{flex:1;min-height:36px;max-height:120px;padding:9px 12px;border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;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);box-shadow:0 0 0 3px #4285f41a}.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:8px;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;min-height:28px;padding:3px 14px 10px;font-size:11px;color:var(--gh-text-tertiary, #9ca3af);background:var(--gh-bg, #ffffff)}.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 xx=({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,q]=_(null),R=gb(e=>e.items),P=gb(),D=nb(e=>e.prompts),B=$(null),O=$(null),z=$(null),F=R.filter(e=>"pending"===e.status).length,U=R.filter(e=>"pending"===e.status||"sending"===e.status).length,H=R.filter(e=>"pending"===e.status||"sending"===e.status).length,W=zi(e=>e.settings.features?.prompts?.submitShortcut??"enter"),j=zi(e=>e.settings?.shortcuts),G=j?.keybindings?.togglePromptQueue,Q=i.useMemo(()=>"ctrlEnter"===W?"Ctrl+Enter":"Enter",[W]),V=i.useMemo(()=>{if(null===G)return "";const e=navigator.userAgent.toLowerCase().includes("mac");if(G){const t=hr(G);return t?pr(t,e):""}return e?"⌥J":"Alt+J"},[G]),K=i.useMemo(()=>{const e=v.trim().toLowerCase();return [...e?D.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e)||t.category?.toLowerCase().includes(e)):D].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:(t.lastUsedAt||0)-(e.lastUsedAt||0))},[v,D]),Z=i.useMemo(()=>{const e=new Set(C);return D.filter(t=>e.has(t.id)&&0===Fb(t.content).length)},[D,C]),Y=i.useMemo(()=>Z.flatMap(e=>"line"===w?px(e.content):[e.content.trim()].filter(Boolean)),[w,Z]),X=i.useMemo(()=>((e,t,n)=>{const r=gx(e),o=gx((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?px(e):o?r.split(o):[]).map(e=>e.trim()).filter(Boolean)})(u,m,b),[b,u,m]),J="library"===g?Y:X,ee=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},[]),te=E(()=>{const t=e.getTextareaElement();if(!t)return void q(null);const n=ee(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);q({bottom:r,right:a,width:o});},[e,ee]);L(()=>{te();let t=null,n=null;const r=()=>{if(n=e.getTextareaElement(),n){const e=ee(n);t=new ResizeObserver(()=>{te();}),t.observe(n),t.observe(e),n.parentElement&&t.observe(n.parentElement);}};r();const o=setInterval(()=>{te(),t||n||r();},2e3);return window.addEventListener("resize",te),()=>{clearInterval(o),window.removeEventListener("resize",te),t&&t.disconnect();}},[te,e,ee]),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 vs(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 ne=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]);L(()=>{const e=B.current;if(!e||!n)return;const t=e=>{if("Enter"===e.key&&!e.shiftKey){const t="ctrlEnter"===W,n=e.ctrlKey;(t?n:!n)&&(e.preventDefault(),e.stopPropagation(),ne());}"Escape"===e.key&&(e.stopPropagation(),r(false));};return e.addEventListener("keydown",t,true),()=>{e.removeEventListener("keydown",t,true);}},[n,W,ne]);const re=E(e=>{P.remove(e);},[P]),oe=E(async e=>{P.remove(e.id);await t.sendImmediately(e.content,W,e.metadata)||(P.enqueue(e.content,e.metadata),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 Gi(le("queueBatchDelimiterRequired"),2500);if(0===J.length)return void Gi(le("queueBatchImportEmpty"),2500);const n=P.enqueueMany(J);0!==n.length?(t.isRunning()||t.start(),e.isGenerating()||await t.processNextNow(),Gi(le("queueBatchImportSuccess",{count:String(n.length)}),2500),ae()):Gi(le("queueBatchImportEmpty"),2500);},[e,b,J,g,m,t,ae,P]),de=E((e,t)=>{A(e),I(zf(t));},[]),ue=E(e=>{if(M.trim()){const t=P.items.find(t=>t.id===e),n=t?.metadata?.quoteMarkerKind;P.updateContent(e,Of(M.trim(),t?.metadata?.quoteRef,n?{kind:n}:void 0));}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?Re(Ne,{children:[gd( Re("div",{className:"gh-queue-panel",style:be,ref:z,children:[ Re("div",{className:"gh-queue-header",children:[ Re("div",{className:"gh-queue-header-title",children:[ qe("span",{children:qe(Ve,{size:18,color:"currentColor"})}), qe("span",{children:le("queueTitle")}),F>0&&qe("span",{className:"gh-queue-capsule-badge",children:F})]}), Re("div",{className:"gh-queue-header-actions",children:[ qe(Sd,{content:le("queueBatchImport"),children:qe("button",{className:"gh-queue-header-btn",onClick:()=>d(true),children:qe(Ze,{size:16,color:"currentColor"})})}),H>0&&qe(Sd,{content:le("queueClearAll"),children:qe("button",{className:"gh-queue-header-btn",onClick:ie,children:qe(Bt,{size:16,color:"currentColor"})})}), qe(Sd,{content:le("collapse"),children:qe("button",{className:"gh-queue-header-btn",onClick:()=>r(false),children:Re("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), qe("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]})]}), qe("div",{className:"gh-queue-list",children:0===R.filter(e=>"pending"===e.status||"sending"===e.status).length?Re("div",{className:"gh-queue-empty",children:["队列为空,输入内容后按 ",Q," 发送或排队"]}):R.filter(e=>"pending"===e.status||"sending"===e.status).map((e,t)=>Re("div",{className:"gh-queue-item","data-status":e.status,children:[ qe("span",{className:"gh-queue-item-index",children:t+1}),T===e.id?Re("div",{className:"gh-queue-item-edit-area",children:[ qe("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}), Re("div",{className:"gh-queue-item-edit-actions-row",children:[ qe("button",{className:"gh-queue-item-edit-btn-save",onClick:()=>ue(e.id),title:le("queueEditSave"),children:qe("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:qe("polyline",{points:"20 6 9 17 4 12"})})}), qe("button",{className:"gh-queue-item-edit-btn-cancel",onClick:he,title:le("queueEditCancel"),children:Re("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), qe("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}):Re(Ne,{children:[ Re("span",{className:"gh-queue-item-main",children:[e.metadata?.chainTitle&&qe("span",{className:"gh-queue-item-chain",children:le("quickQuoteChainQueueSource",{title:e.metadata.chainTitle,index:String(e.metadata.stepIndex||t+1),total:String(e.metadata.stepTotal||1)})}), qe("span",{className:"gh-queue-item-content",children:zf(e.content)})]}), Re("div",{className:"gh-queue-item-actions",children:["pending"===e.status&&qe("button",{className:"gh-queue-item-edit",onClick:()=>de(e.id,e.content),title:le("queueEdit"),children:Re("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), qe("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&&qe("button",{className:"gh-queue-item-force-send",onClick:()=>oe(e),title:le("queueForceSend"),children:Re("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), qe("polyline",{points:"5 12 12 5 19 12"})]})}), qe("button",{className:"gh-queue-item-remove",onClick:()=>re(e.id),title:le("queueRemove"),children:Re("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), qe("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]},e.id))}), qe("div",{className:"gh-queue-input-area",children:Re("div",{className:"gh-queue-input-wrapper",children:[ qe("textarea",{ref:B,className:"gh-queue-input",value:s,onChange:pe,placeholder:o?`AI 生成中,${Q} 加入队列...`:`输入提示词,${Q} 直接发送...`,rows:1}), qe("button",{className:"gh-queue-send-btn",onClick:ne,disabled:!s.trim(),title:Q,children:Re("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), qe("polyline",{points:"5 12 12 5 19 12"})]})})]})}), Re("div",{className:"gh-queue-status",children:[ qe("span",{className:"gh-queue-status-dot","data-generating":o?"true":"false"}), qe("span",{children:le(o?"queueStatusBusy":"queueStatusIdle")}), Re("span",{className:"gh-queue-disable-hint",title:le("queueSettingDesc"),children:["(",le("queueDisableHint"),")"]}),V&&qe("span",{className:"gh-queue-shortcut-hint",children:V})]})]}),me),c&&Re(bb,{onClose:ae,closeOnOverlayClick:false,closeOnEscape:false,dialogClassName:"gh-queue-batch-dialog",dialogStyle:{maxWidth:560,width:"min(560px, calc(100vw - 32px))"},children:[ qe("div",{className:"gh-dialog-title",children:le("queueBatchImportTitle")}), qe("div",{className:"gh-dialog-message",children:le("queueBatchImportDesc")}), Re("div",{className:"gh-queue-batch-tabs",children:[ qe("button",{className:"gh-queue-batch-tab","data-active":"library"===g,onClick:()=>p("library"),children:le("queueBatchLibraryTab")}), qe("button",{className:"gh-queue-batch-tab","data-active":"text"===g,onClick:()=>p("text"),children:le("queueBatchTextTab")})]}),"text"===g&&Re(Ne,{children:[ Re("div",{className:"gh-queue-batch-section",children:[ qe("div",{className:"gh-queue-batch-label",children:le("queueBatchSplitModeLabel")}), Re("div",{className:"gh-queue-batch-mode-group",children:[ qe("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===m,onClick:()=>f("line"),children:le("queueBatchSplitModeLine")}), qe("button",{className:"gh-queue-batch-mode-btn","data-active":"delimiter"===m,onClick:()=>f("delimiter"),children:le("queueBatchSplitModeDelimiter")})]})]}),"delimiter"===m&&Re("div",{className:"gh-queue-batch-section",children:[ qe("div",{className:"gh-queue-batch-label",children:le("queueBatchDelimiterLabel")}), qe("input",{className:"gh-dialog-input gh-queue-batch-delimiter-input",value:b,onChange:e=>y(e.target.value),placeholder:le("queueBatchDelimiterPlaceholder")})]}), Re("div",{className:"gh-queue-batch-section",children:[ qe("div",{className:"gh-queue-batch-label",children:le("queueBatchInputLabel")}), qe("textarea",{ref:O,className:"gh-queue-batch-textarea",value:u,onChange:e=>h(e.target.value),placeholder:le("queueBatchInputPlaceholder")})]})]}),"library"===g&&Re(Ne,{children:[ Re("div",{className:"gh-queue-batch-section",children:[ qe("div",{className:"gh-queue-batch-label",children:le("queueBatchLibraryModeLabel")}), Re("div",{className:"gh-queue-batch-mode-group",children:[ qe("button",{className:"gh-queue-batch-mode-btn","data-active":"single"===w,onClick:()=>S("single"),children:le("queueBatchLibraryModeSingle")}), qe("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===w,onClick:()=>S("line"),children:le("queueBatchSplitModeLine")})]})]}), Re("div",{className:"gh-queue-batch-section",children:[ qe("div",{className:"gh-queue-batch-label",children:le("queueBatchLibrarySearchLabel")}), qe("input",{className:"gh-dialog-input gh-queue-batch-library-search",value:v,onChange:e=>x(e.target.value),placeholder:le("queueBatchLibrarySearchPlaceholder")}), qe("div",{className:"gh-queue-batch-library-list",children:0===K.length?qe("div",{className:"gh-queue-batch-library-empty",children:le("queueBatchLibraryEmpty")}):K.slice(0,80).map(e=>{const t=Fb(e.content).length>0; return Re("label",{className:"gh-queue-batch-library-item","data-disabled":t?"true":"false",title:t?le("queueBatchLibraryVariablePrompt"):void 0,children:[ qe("input",{type:"checkbox",disabled:t,checked:!t&&C.includes(e.id),onChange:()=>{t||se(e.id);}}), Re("span",{className:"gh-queue-batch-library-main",children:[ qe("span",{className:"gh-queue-batch-library-title",children:e.title}), qe("span",{className:"gh-queue-batch-library-content",children:t?le("queueBatchLibraryVariablePrompt"):e.content})]}), qe("span",{className:"gh-queue-batch-library-category",children:e.category||le("uncategorized")})]},e.id)})})]})]}), Re("div",{className:"gh-queue-batch-preview",children:[ Re("div",{className:"gh-queue-batch-preview-header",children:[ qe("span",{children:le("queueBatchPreviewTitle")}), qe("span",{children:le("queueBatchPreviewCount",{count:String(J.length)})})]}), qe("div",{className:"gh-queue-batch-preview-body",children:0===J.length?qe("div",{className:"gh-queue-batch-preview-empty",children:le("queueBatchPreviewEmpty")}):Re(Ne,{children:[ qe("ol",{className:"gh-queue-batch-preview-list",children:J.slice(0,5).map((e,t)=>qe("li",{className:"gh-queue-batch-preview-item",children:e},`${t}-${e.slice(0,20)}`))}),J.length>5&&qe("div",{className:"gh-queue-batch-preview-more",children:le("queueBatchPreviewMore",{count:String(J.length-5)})})]})})]}), Re("div",{className:"gh-dialog-buttons",children:[ qe("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:ae,children:le("cancel")}), qe("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:()=>{ce();},disabled:0===J.length||"text"===g&&"delimiter"===m&&!b.trim(),children:le("queueBatchImportAction")})]})]})]}):gd( qe(Sd,{content:V||le("queueQuickAsk"),children:Re("div",{className:"gh-queue-capsule",style:fe,onClick:()=>r(true),children:[ qe("span",{className:"gh-queue-capsule-icon",children:qe(Ve,{size:18,color:"currentColor"})}), qe("span",{children:U>0?le("queueInQueue",{count:String(U)}):le("queueQuickAsk")})]})}),me)},wx=e=>/^(?:https?:|data:|blob:)/i.test(e.trim())?e:"undefined"!=typeof chrome&&chrome.runtime?.getURL?chrome.runtime.getURL(e):e,Sx=({version:e,date:t,markdown:n,language:r,media:o=[],fullChangelogUrl:i,onClose:a,onOpenFullChangelog:s})=>{const l=N(),c=$(null),[d,u]=_(null),h=D(()=>gu(tc(n,false,{linkGithubReferences:true})),[n]);L(()=>{c.current?.focus();const e=e=>{if("Escape"===e.key){if(d)return void u(null);a();}};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[d,a]);const g=d?wx(d.src):""; return Re("div",{className:"gh-release-notes-overlay gh-interactive",role:"presentation",...ms,onClick:a,children:[ Re("section",{className:"gh-release-notes-modal",role:"dialog","aria-modal":"true","aria-labelledby":l,onClick:e=>e.stopPropagation(),children:[ Re("header",{className:"gh-release-notes-header",children:[ Re("div",{className:"gh-release-notes-kicker",children:[ qe(Jt,{size:16,color:"brand"}), qe("span",{children:le("releaseNotesKicker")})]}), qe("button",{ref:c,type:"button",className:"gh-release-notes-close","aria-label":le("close"),onClick:a,children:qe($e,{size:16})}), qe("h2",{id:l,className:"gh-release-notes-title",children:le("releaseNotesTitle",{version:e})}),t?qe("div",{className:"gh-release-notes-meta",children:le("releaseNotesPublishedOn",{date:t})}):null]}), Re("div",{className:"gh-release-notes-body",children:[o.length>0?qe("div",{className:"gh-release-notes-media-grid",children:o.map(e=>{const t=wx(e.src),n=((e,t)=>e?.[lv(t)])(e.caption,r); return Re("button",{type:"button",className:"gh-release-notes-media",onClick:()=>u(e),children:[ qe("img",{src:t,alt:cv(e.alt,r)}),n?qe("span",{children:n}):null]},e.id)})}):null, qe("div",{className:"gh-release-notes-markdown",dangerouslySetInnerHTML:{__html:h}}), qe("style",{children:nc()})]}), Re("footer",{className:"gh-release-notes-footer",children:[ Re("button",{type:"button",className:"gh-release-notes-secondary",title:i,onClick:s,children:[ qe(Fe,{size:14}), qe("span",{children:le("releaseNotesViewFull")})]}), Re("button",{type:"button",className:"gh-release-notes-primary",onClick:a,children:[ qe(tn,{size:14}), qe("span",{children:le("releaseNotesGotIt")})]})]})]}),d?qe("div",{className:"gh-release-notes-lightbox",role:"dialog","aria-modal":"true","aria-label":cv(d.alt,r),onClick:e=>{e.stopPropagation(),u(null);},children:qe("img",{src:g,alt:cv(d.alt,r)})}):null]})},Cx=()=>({width:window.innerWidth,height:window.innerHeight}),kx=(e,t)=>e&&t?e.xRatio===t.xRatio&&e.yRatio===t.yRatio:e===t,Tx=3e3,Ex=({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,onSegmentedExport:f,onModelLockToggle:b,isModelLocked:y,onOpenSettings:v,isScrolling: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}=zi(),k=S||gi,T=Xm(),A=k.quickButtons||gi.quickButtons,M=D(()=>A.collapsed||[],[A.collapsed]),I=k.panel?.defaultPosition??"right",N="left"===I?{left:"16px",right:"auto"}:{right:"16px",left:"auto"},q=Math.min(Math.max(A.opacity??1,.4),1),R=A.position??null,B=A.proximityRadius??150,z=T?.getSiteId()||"_default",F=pi(k,z),U="dark"===(a||("dark"===F.mode?"dark":"light"))?"brand":"currentColor",H=$(null),[W,j]=_(false),[G,Q]=_(Cx),V=$(G),K=$(G),[Z,Y]=_({width:0,height:0}),X=E(e=>{V.current=e,Q(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(Xy,Jy),[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!==B&&(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);B>0&&i<=B&&Me(Tx);}));},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(Tx),()=>{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,B]);const Le=!(ke||Se||W||e||te||re);$(Le).current=Le;const Be=D(()=>{if(te||re||W)return false;if(Le)return false;if(A.hideWhenPanelOpen&&e)return true;const t=e&&"edge-snap"!==(k.panel?.panelMode??"edge-snap");for(const n of M){if("manualAnchor"===n.id)continue;const r=Yr[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,M,k.panel?.panelMode,A.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(),kx(ae.current,t)||(ae.current=t,C("quickButtons","position",t||void 0));},[We,C]);L(()=>{const e=!kx(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]),Qe=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]),Ve=E((e,t,n,r=se.current)=>{const o=Qe(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,Qe]),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=Cx(),a=K.current,s=a.width!==i.width||a.height!==i.height;if(K.current=i,V.current.width===i.width&&V.current.height===i.height||X(i),!ie.current){const e=ue.current??t.top,r=Qe(0,e,i,n).y;return void(ue.current!==r&&(ue.current=r,de(r)))}if(me.current||o||s)return;const l=Ve(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();}},[Qe,X,Ve]);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 ou({adapter:T,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{Ue(`${le("loadingHistory")} ${e}`);}});Yy(t.previousScrollTop),_e(t.isFlutterMode),n&&(window.clearTimeout(n),n=null),ze(!1),Ue(""),t.success&&!t.silent&&Gi(le("historyLoaded"),2e3);}finally{clearInterval(t),n&&window.clearTimeout(n);}},[T]),Ye=E(()=>{He.current=true;},[]),Xe=E(async()=>{const{previousScrollTop:e,container:t}=await Qd(T);Yy(e),_e(Xd(t));},[T]),Je=E(async()=>{const e=Zy();if(null===e)return;we(e=>e+1);const t=(await Zd(T)).scrollTop;await Vd(T,e),Yy(t);},[T]),et=E(async()=>{const e=await Zd(T);Yy(e.scrollTop),_e(e.isFlutterMode);},[T]),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"===I?"side-right":"side-left",ot={scrollTop:Ze,scrollBottom:Xe,panel:t,anchor:Je,theme:e=>{e?.stopPropagation();const t=e?.currentTarget;t?o?.(w(t)):o?.();},floatingToolbar:e=>{e?.stopPropagation(),j(e=>!e);},globalSearch:e=>{e?.stopPropagation(),j(false),g?.();},zenMode:e=>{e?.stopPropagation();const t=T?.getSiteId()||"_default",n=yi(S||gi,t),r=!n.enabled;if(C("layout","zenMode",{...S?.layout?.zenMode??{},[t]:{...n,enabled:r}}),r){const e=S?.layout?.cleanMode?.[t]??{enabled:true};C("layout","cleanMode",{...S?.layout?.cleanMode??{},[t]:{...e,enabled:true}});}},settings:e=>{e?.stopPropagation(),j(false),v?.();}},it=(t,o,i)=>{const s=o.isPanelOnly,l=!i,c="floatingToolbar"===t,d="zenMode"===t,u=d&&Boolean(S?.layout?.zenMode?.[z]?.enabled),h=c?W:u,g=e&&"edge-snap"!==(S?.panel?.panelMode??"edge-snap");if(l||s&&e||o.hideWhenPanelOpen&&g)return null;let p;if("theme"===t)p=qe("dark"===a?Pe:De,{size:20});else if(u)p=qe(Qt,{size:18,color:"currentColor"});else if(o.IconComponent){const e=o.IconComponent;p=qe(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 qe(Sd,{content:y,children:qe("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===B});},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?qe("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=Yr.manualAnchor,n=t?.IconComponent; return qe(i.Fragment,{children:qe(Sd,{content:le("setAnchor"),children:qe("button",{className:"quick-prompt-btn manual-anchor-btn set-btn gh-interactive",onClick:et,children:n?qe(n,{size:18}):"📍"})})},"manualAnchor")},st=(e,t)=>qe("div",{className:"divider "},t),lt={[Do]:()=>s?.(),[Bo]:()=>f?.(),[$o]:()=>m?.(),[_o]:()=>l?.(),[Oo]:()=>c?.(),[zo]:()=>d?.(!p),[Fo]:()=>b?.(),[Uo]:()=>h?.(),[Ho]:()=>u?.()},ct=e=>e===zo?p||false:e===Fo&&y||false;L(()=>{if(!H.current)return;let e=null,t=null;const n=()=>{e&&(clearTimeout(e),e=null),0===B?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);}},[Qe,B]),L(()=>{let e=null,t=null,n=false;const r=()=>{const e=Cx();if(X(e),ie.current||null===ue.current)return;const t=Qe(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);}},[Qe,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 Re(Ne,{children:[ qe(Ev,{isVisible:Oe,text:Fe,onStop:Ye}), Re("div",{ref:H,className:`quick-btn-group gh-interactive ${e?"":"collapsed"} ${te?"dragging":""} ${re?"pressing":""} ${x?"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=Cx(),n=pe.current||{x:0,y:0},r=e.clientX-n.x,o=e.clientY-n.y,i=Ve(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`:N.left,right:tt?"auto":N.right,transform:tt||null!==ce?"none":"translateY(-50%)",opacity:Be?0:q,pointerEvents:Be?"none":void 0},children:[ qe("div",{className:"quick-btn-drag-handle",style:{"--quick-btn-press-duration":"220ms"},"aria-hidden":"true"}),(()=>{if(Le)return [it("panel",Yr.panel,true)];const t=[],n=new Set(["scrollTop","scrollBottom","anchor","manualAnchor"]),r=M.map(t=>{if("manualAnchor"===t.id)return null;const r=Yr[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"!==(S?.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=A.toolsMenu??Wo.map(e=>e.id),o=new Set(r);for(const i of Wo){if(!(i.isSystem||o.has(i.id)))continue;i.isDanger&&!t&&(e.push(qe("div",{className:"menu-divider"},`divider-before-${i.id}`)),t=true),i.isSystem&&!n&&(e.push(qe("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( qe(Sd,{content:le(i.labelKey),children:qe("button",{className:a,onClick:()=>{lt[i.id]?.(),j(false);},children:qe(r,{size:18})})},i.id));}return e})()})]})]})},Ax="50%",Mx=({title:e,onClear:t,adapter:n})=>{const[r,o]=_(120),[i,a]=_(Ax),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===Ax?e:Ax),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?Re("div",{className:"selected-prompt-bar gh-interactive",style:{position:"fixed",bottom:`${r}px`,left:i,transform:"translateX(-50%)",zIndex:999998},children:[ qe("span",{className:"selected-prompt-label",children:le("currentPrompt")}), qe(Sd,{content:e,children:qe("span",{className:"selected-prompt-text",children:e})}), qe(Sd,{content:le("clear"),children:qe("button",{className:"clear-prompt-btn",type:"button","aria-label":le("clear"),onClick:t,children:qe($e,{size:14})})})]}):null};function Ix(){const e=D(()=>kv(),[]),t=D(()=>ei(),[]); return Re("div",{className:"sidebar-community-links",children:[ qe(Sd,{content:le("rateAndReview"),children:qe("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})})}),t&&qe(Sd,{content:le("scriptCat"),children:qe("a",{href:Cv,target:"_blank",rel:"noopener noreferrer","aria-label":le("scriptCat"),className:"sidebar-social-btn scriptcat-btn",children:qe(Ft,{size:18})})}), qe(Sd,{content:le("giveStar"),children:qe("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer","aria-label":le("giveStar"),className:"sidebar-social-btn github-btn",children:qe(gt,{size:18})})}), qe(Sd,{content:le("kofiSupport"),children:qe("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer","aria-label":le("kofiSupport"),className:"sidebar-social-btn kofi-btn",children:qe(an,{size:18})})}), qe(Sd,{content:le("discordCommunity"),children:qe("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer","aria-label":le("discordCommunity"),className:"sidebar-social-btn discord-btn",children:qe(on,{size:18})})})]})}const Lx={"zh-CN":"简体中文","zh-TW":"繁體中文",en:"English",es:"Español",pt:"Português",ru:"Русский",ja:"日本語",de:"Deutsch",fr:"Français",ko:"한국어"},Nx=({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 gd( Re("div",{className:"lang-menu-portal",style:{position:"relative",zIndex:2147483647},children:[ qe("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:2e6,background:"transparent"},onClick:e=>{e.stopPropagation(),r();}}), qe("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(Lx).map(([t,r])=>Re("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:[ qe("span",{children:r}),e===t&&qe("span",{children:"✓"})]},t))}), qe("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)},qx=({siteId:e="_default"})=>{const{settings:t,setSettings:n}=zi(),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]),Re("div",{className:"settings-sidebar-footer",children:[!r&&Re("div",{ref:f,className:`settings-theme-segmented ${"compact"===b?"is-compact":""} ${"icon"===b?"is-icon":""}`,children:[ qe(Sd,{content:le("themeLight"),triggerStyle:{flex:1},children:Re("button",{className:"settings-theme-segment "+("light"===c?"active":""),onClick:e=>d("light",e),children:[ qe("span",{className:"segment-icon",children:qe(Pe,{size:16})}), qe("span",{className:"segment-label",children:le("themeLight")})]})}), qe(Sd,{content:le("themeDark"),triggerStyle:{flex:1},children:Re("button",{className:"settings-theme-segment "+("dark"===c?"active":""),onClick:e=>d("dark",e),children:[ qe("span",{className:"segment-icon",children:qe(De,{size:16})}), qe("span",{className:"segment-label",children:le("themeDark")})]})}), qe(Sd,{content:le("themeSystem"),triggerStyle:{flex:1},children:Re("button",{className:"settings-theme-segment "+("system"===c?"active":""),onClick:e=>d("system",e),children:[ qe("span",{className:"segment-icon",children:qe(Be,{size:16})}), qe("span",{className:"segment-label",children:le("themeSystem")})]})})]}), Re("div",{className:"settings-lang-inline",children:[ qe("button",{className:"lang-icon",onClick:e=>{e.stopPropagation(),p(!g);},children:qe(It,{size:16})}), qe("div",{className:"lang-links-container",children:C.map((e,t)=>Re(i.Fragment,{children:[ qe("button",{className:"lang-link "+(h===e?"active":""),onClick:()=>u(e),children:x[e]||e}),t{e.stopPropagation(),p(!g);},children:qe(Mt,{size:18})})}),g&&qe(Nx,{currentLang:h,themeMode:a,onSelect:e=>{u(e),p(false);},onClose:()=>p(false),triggerRef:m})]}), qe("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 Rx(){return globalThis.__OPHEL_SITE_ICONS__||{}}const Px=new Proxy({},{get:(e,t)=>{if("string"==typeof t)return Rx()[t]},has:(e,t)=>"string"==typeof t&&t in Rx(),ownKeys:()=>Reflect.ownKeys(Rx()),getOwnPropertyDescriptor:(e,t)=>{if("string"==typeof t&&t in Rx())return {enumerable:true,configurable:true}}}),Dx=({title:e,description:t,children:n,className:r="",style:o,settingId:i})=>Re("div",{className:`settings-card ${r}`,style:o,"data-setting-id":i,children:[e&&qe("div",{className:"settings-card-title",children:e}),t&&qe("div",{className:"settings-card-desc",children:t}),n]}),Bx=({label:e,description:t,children:n,disabled:r=false,onDisabledClick:o,style:i,settingId:a})=>{const s=r&&!!o; return Re("div",{className:`settings-row ${r?"disabled":""} ${s?"disabled-clickable":""}`,"data-setting-id":a,style:i,onClick:()=>{s&&o?.();},children:[ Re("div",{className:"settings-row-info",children:[ qe("div",{className:"settings-row-label",children:e}),t&&qe("div",{className:"settings-row-desc",children:t})]}),n&&qe("div",{className:"settings-row-control",children:n})]})},$x=({label:e,description:t,checked:n,onChange:r,disabled:o=false,onDisabledClick:i,settingId:a})=>qe(Bx,{label:e,description:t,disabled:o,onDisabledClick:i,settingId:a,children:qe(mb,{checked:n,onChange:r,disabled:o})}),_x=({tabs:e,activeTab:t,onTabChange:n})=>qe("div",{className:"settings-tab-group",children:e.map(e=>qe("button",{className:"settings-tab-item "+(t===e.id?"active":""),onClick:()=>n(e.id),children:e.label},e.id))}),Ox=({title:e,Icon:t})=>Re("h1",{className:"settings-page-title",style:{display:"flex",alignItems:"center"},children:[t&&qe(t,{size:28,className:"settings-page-title-icon",style:{marginRight:8,color:"var(--gh-primary, #4285f4)"}}),e]}),zx=({onOpenReleaseNotes:e})=>{const t=String(qo.length); return Re("div",{children:[ qe(Ox,{title:le("navAbout"),Icon:ht}), qe("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",marginBottom:32},children:Re("div",{className:"about-slogan-badge",children:[ qe("span",{style:{marginRight:6},children:"✨"}),le("aboutPageDesc"), qe("span",{style:{marginLeft:6},children:"✨"})]})}), Re("div",{className:"about-hero-card",children:[ qe("img",{src:iv,alt:rv,className:"about-hero-logo",onError:e=>{e.target.style.display="none";}}), Re("div",{className:"about-hero-content",children:[ Re("div",{className:"about-hero-heading",children:[ Re("div",{className:"about-hero-title",children:[rv, Re("span",{className:"about-hero-version",children:["v",ov]})]}),e?Re("button",{type:"button",className:"about-release-notes-btn",onClick:e,children:[ qe(Jt,{size:14,color:"currentColor"}), qe("span",{children:le("releaseNotesOpen")})]}):null]}), qe("div",{className:"about-hero-desc",children:le("aboutDescription",{appName:rv})})]})]}), qe("div",{className:"about-section-title",children:le("rateAndReview")}), Re("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:[ Re("a",{href:vv,target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4285F4"},children:[ Re("div",{className:"about-link-header",children:[ qe(_t,{size:24,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600},children:le("chromeStore")})]}), qe("button",{className:"about-link-btn",children:le("reviewBtn")})]}), Re("a",{href:xv,target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#0078D7"},children:[ Re("div",{className:"about-link-header",children:[ qe(Ut,{size:24}), qe("span",{style:{fontWeight:600},children:le("edgeAddons")})]}), qe("button",{className:"about-link-btn",children:le("reviewBtn")})]}), Re("a",{href:wv,target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#FF7139"},children:[ Re("div",{className:"about-link-header",children:[ qe(Ot,{size:24,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600},children:le("firefoxAddons")})]}), qe("button",{className:"about-link-btn",children:le("reviewBtn")})]}), Re("a",{href:Sv,target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4b5563"},children:[ Re("div",{className:"about-link-header",children:[ qe(zt,{size:24,color:"currentColor"}), qe("span",{style:{fontWeight:600,color:"var(--gh-text)"},children:le("greasyFork")})]}), qe("button",{className:"about-link-btn",children:le("reviewBtn")})]}), Re("a",{href:Cv,target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#1296db"},children:[ Re("div",{className:"about-link-header",children:[ qe(Ft,{size:24,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600,color:"var(--gh-text)"},children:le("scriptCat")})]}), qe("button",{className:"about-link-btn",children:le("reviewBtn")})]})]}), qe("div",{className:"about-section-title",children:le("communityAndSupport")}), Re("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",marginBottom:16,fontStyle:"italic",textAlign:"center"},children:['"',le("communityMotto"),'"']}), Re("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))"},children:[ Re("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#111827"},children:[ Re("div",{className:"about-link-header",children:[ qe(gt,{size:22}), qe("span",{style:{fontWeight:600},children:le("githubRepository")})]}), qe("div",{className:"about-link-desc",children:le("githubDesc")}), qe("button",{className:"about-link-btn about-star-btn",children:Re("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ qe(bt,{size:15,color:"currentColor",filled:true}),le("giveStar")]})})]}), Re("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer",className:"about-link-card kofi-card",style:{"--card-color":"#FF5E5B"},children:[ Re("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ qe(an,{size:22,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600},children:le("kofiSupport")})]}), qe("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:le("kofiDesc")}), qe("button",{className:"about-link-btn",children:Re("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ qe(an,{size:14,color:"currentColor"}),le("kofiBtn")]})})]}), Re("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#3B82F6"},children:[ Re("div",{className:"about-link-header",children:[ qe(pt,{size:22,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600,color:"var(--card-color)"},children:le("projectWebsite")})]}), qe("div",{className:"about-link-desc",children:le("websiteDesc")}), qe("button",{className:"about-link-btn",children:Re("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ qe(pt,{size:14,color:"currentColor"}),le("visitWebsite")]})})]}), Re("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer",className:"about-link-card discord-card",style:{"--card-color":"#5865F2"},children:[ Re("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ qe(on,{size:22,color:"var(--card-color)"}), qe("span",{style:{fontWeight:600},children:le("discordCommunity")})]}), qe("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:le("discordDesc")}), qe("button",{className:"about-link-btn",children:Re("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ qe(on,{size:14,color:"currentColor"}),le("joinDiscord")]})})]})]}), qe("div",{className:"about-section-title",children:le("aboutSupportedPlatforms")}), Re("div",{className:"about-platforms-card",children:[ Re("div",{className:"about-platforms-header",children:[ qe("div",{className:"about-platforms-desc",children:le("aboutSupportedPlatformsDesc",{count:t})}), qe("span",{className:"about-platforms-count",children:t})]}), qe("div",{className:"about-platforms-grid",children:qo.map(e=>Re("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"about-platform-chip",title:e.url,children:[Px[e.name]?qe("img",{src:Px[e.name],alt:e.name,className:"about-platform-chip-icon"}):qe("span",{className:"about-platform-chip-emoji","aria-hidden":"true",children:e.icon}), qe("span",{children:e.name})]},e.id))})]}), qe("div",{className:"about-section-title",children:le("techStack")}), Re("div",{className:"about-tech-grid",children:[ qe(Fx,{name:"Plasmo",version:"v0.89.0",desc:le("tsPlasmoDesc")}), qe(Fx,{name:"React",version:"v18.2.0",desc:le("tsReactDesc")}), qe(Fx,{name:"TypeScript",version:"v5.3.3",desc:le("tsTypescriptDesc")}), qe(Fx,{name:"Zustand",version:"v5.0.3",desc:le("tsZustandDesc")}), qe(Fx,{name:"Vite",version:"v5.0.0",desc:le("tsViteDesc")})]}), qe("div",{className:"about-section-title",children:le("credits")}), Re("div",{className:"about-simple-card",children:[ Re("div",{className:"about-simple-header",children:[ qe(mt,{size:18,style:{color:"#ef4444"}}),le("devAndMaintain")]}), qe("p",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:1.6,marginBottom:16},children:le("creditsDesc")}), Re("div",{style:{display:"flex",gap:8},children:[ qe(Ux,{text:"Made with ❤️"}), qe(Ux,{text:"Open Source"}), qe(Ux,{text:"Privacy First"})]}), Re("div",{style:{marginTop:16,fontSize:"12px",color:"var(--gh-text-secondary)"},children:["GNU GPLv3 © ", (new Date).getFullYear()," ",rv]})]}), Re("div",{className:"about-privacy-banner",children:[ qe(ft,{size:24,className:"about-privacy-icon"}), Re("div",{children:[ qe("div",{className:"about-privacy-title",children:le("privacyTitle")}), qe("div",{className:"about-privacy-desc",children:le("privacyText")})]})]})]})},Fx=({name:e,version:t,desc:n})=>Re("div",{className:"about-tech-card",children:[ Re("div",{className:"about-tech-header",children:[ qe("div",{className:"about-tech-name",children:e}), qe("div",{className:"about-tech-version",children:t})]}), qe("div",{className:"about-tech-desc",children:n})]}),Ux=({text:e})=>qe("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 Hx(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Wx(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 jx,Gx;function Qx(){if(Gx)return jx;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}Gx=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},q={scope:"number",begin:S,relevance:0},R={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[C,{begin:/\[/,end:/\]/,relevance:0,contains:[C]}]},P={scope:"title",begin:y,relevance:0},D={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:q,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:R,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:D});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,Q(n[0],n[1])];});}}function Q(e,t){return t?Number(t):function(e){return j.includes(e.toLowerCase())}(e)?0:1}const V={},K=e=>{console.error(e);},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t);},Y=(e,t)=>{V[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),V[`${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(R>1e5&&R>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,q=0,R=0,P=false;try{if(k.__emitTokens)k.__emitTokens(n,I);else {for(A.matcher.considerAll();;){R++,P?P=!1:A.matcher.considerAll(),A.matcher.lastIndex=q;const e=A.matcher.exec(n);if(!e)break;const t=S(n.substring(q,e.index),e);q=e.index+t;}S(n.substring(q));}return I.finalize(),E=I.toHTML(),{language:e,value:E,relevance:N,illegal:!1,_emitter:I,_top:A}}catch(D){if(D.message&&D.message.includes("Illegal"))return {language:e,value:oe(n),illegal:true,relevance:0,_illegalBy:{message:D.message,index:q,context:n.slice(q-100,q+100),mode:D.mode,resultSoFar:E},_emitter:I};if(a)return {language:e,value:oe(n),illegal:false,relevance:0,errorRaised:D,_emitter:I,_top:A};throw D}}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({}),jx=le,le.HighlightJS=le,le.default=le,jx}const Vx=Hx(Qx()),Kx=["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"],Zx=["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(),Yx=["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(),Xx=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Jx=["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 ew={};const tw=Wx(U);var nw;const rw=Hx(function(){if(nw)return ew;nw=1;var e=ew&&ew.__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=ew&&ew.__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);ew.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 ew}());class ow 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 qe("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:qe("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 qe(rw,{...this.props})}}const iw=({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 Re("div",{className:"theme-preview-layout",style:{backgroundColor:n,borderColor:o},children:[ Re("div",{className:"theme-preview-header",style:{backgroundColor:r},children:[ qe("div",{className:"theme-preview-dot"}), qe("div",{className:"theme-preview-dot delay-1"}), qe("div",{className:"theme-preview-dot delay-2"})]}), Re("div",{className:"theme-preview-body",children:[ Re("div",{className:"theme-preview-sidebar",style:{backgroundColor:l,borderColor:o},children:[ qe("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.3}}), qe("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), qe("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), qe("div",{className:"theme-preview-active-item",style:{backgroundColor:i,opacity:.15}})]}), Re("div",{className:"theme-preview-content",children:[ qe("div",{className:"theme-preview-hero",style:{backgroundColor:i,opacity:.1}}), Re("div",{className:"theme-preview-row",children:[ qe("div",{className:"theme-preview-avatar",style:{backgroundColor:s,opacity:.2}}), Re("div",{style:{flex:1},children:[ qe("div",{className:"theme-preview-line",style:{backgroundColor:a,opacity:.6,marginBottom:4}}), qe("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.4}})]})]}), qe("div",{className:"theme-preview-button",style:{backgroundColor:i}})]})]})]})};Vx.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:":("+Yx.join("|")+")"},{begin:":(:)?("+Xx.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Jx.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:Zx.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Kx.join("|")+")\\b"}]}});const aw=({preset:e,isActive:t,onClick:n})=>{const r=`themePreset_${e.id}`,o=le(r),i=o&&o!==r?o:e.name; return Re("div",{className:"settings-theme-card "+(t?"active":""),onClick:n,children:[ qe(iw,{preset:e}), qe("div",{className:"settings-theme-name",children:i})]})},sw=({siteId:e,initialTab:t})=>{const[n,r]=_(t||$r),{settings:o,setSettings:i}=zi();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:$r,label:le("themePresetsTab")},{id:_r,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=[...Dy,...h.filter(e=>"light"===e.mode).map(g)],m=[...By,...h.filter(e=>"dark"===e.mode).map(g)]; return Re("div",{children:[ qe(Ox,{title:le("navAppearance"),Icon:lt}), qe("p",{className:"settings-page-desc",children:le("appearancePageDesc")}), qe(Dx,{settingId:"appearance-theme-sync",children:qe($x,{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"})}), qe(_x,{tabs:u,activeTab:n,onTabChange:r}),n===$r&&Re(Ne,{children:[ qe(Dx,{title:le("lightModePreset"),description:le("lightModePresetDesc"),settingId:"appearance-preset-light",children:qe("div",{className:"settings-theme-grid",children:p.map(t=>qe(aw,{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))})}), qe(Dx,{title:le("darkModePreset"),description:le("darkModePresetDesc"),settingId:"appearance-preset-dark",children:qe("div",{className:"settings-theme-grid",children:m.map(t=>qe(aw,{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===_r&&qe(Ne,{children:Re(Dx,{title:le("customCSS"),description:le("customCSSDesc"),settingId:"appearance-custom-styles",children:[ Re("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?qe("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")}):qe("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:(o?.theme?.customStyles||[]).map(e=>Re("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"8px"},children:[ Re("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ qe("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?"☀️":"🌙"}), qe("span",{style:{fontSize:"14px",fontWeight:500},children:e.name||le("unnamedStyle")})]}), Re("div",{style:{display:"flex",gap:"8px"},children:[ Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{c(e),s(true);},style:{padding:"6px 12px",fontSize:"12px"},children:["✏️ ",le("edit")]}), qe("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),style:{padding:"6px 12px",fontSize:"12px"},children:"🗑️"})]})]},e.id))})]})}),a&&l&&qe("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:Re("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:[ Re("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ qe("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:l.id?le("editStyle"):le("newStyle")}), qe("button",{onClick:()=>s(false),style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:"✕"})]}), Re("div",{style:{padding:"16px",overflowY:"auto",flex:1,display:"flex",flexDirection:"column"},children:[ Re("div",{style:{marginBottom:"16px"},children:[ qe("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:le("styleNameLabel")}), qe("input",{type:"text",className:"settings-input",value:l.name,onChange:e=>c({...l,name:e.target.value}),placeholder:le("enterStyleName"),style:{width:"100%"}})]}), Re("div",{style:{marginBottom:"16px"},children:[ qe("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:le("styleModeLabel")}), Re("div",{style:{display:"flex",gap:"12px"},children:[ Re("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ qe("input",{type:"radio",checked:"light"===l.mode,onChange:()=>c({...l,mode:"light"})}), Re("span",{children:["☀️ ",le("lightMode")]})]}), Re("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ qe("input",{type:"radio",checked:"dark"===l.mode,onChange:()=>c({...l,mode:"dark"})}), Re("span",{children:["🌙 ",le("darkMode")]})]})]})]}), Re("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[ Re("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:["CSS ",le("code")]}), qe("div",{className:"settings-textarea",style:{flex:1,padding:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:qe(ow,{value:l.css,onValueChange:e=>c({...l,css:e}),highlight:e=>gu(Vx.highlight(e,{language:"css"}).value),padding:12,style:{fontFamily:'"Menlo", "Monaco", "Consolas", monospace',fontSize:13,minHeight:"100%"},textareaClassName:"focus-outline-none"})})]})]}), Re("div",{style:{padding:"16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ qe("button",{className:"settings-btn settings-btn-secondary",onClick:()=>s(false),children:le("cancel")}), qe("button",{className:"settings-btn settings-btn-primary",onClick:()=>{if(!l)return;if(!l.name.trim())return void Gi(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),Gi(l.id?le("styleUpdated"):le("styleCreated"));},children:l.id?le("save"):le("create")})]})]})})]})},lw=e=>Boolean(e)&&"object"==typeof e&&!Array.isArray(e);function cw(e){const t=[];if(!lw(e))return {valid:false,errorKeys:["backupValidationInvalidFormat"]};if(e.version||t.push("backupValidationMissingVersion"),!lw(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.promptChains&&((e=>{if(Array.isArray(e))return true;if(!lw(e))return false;if(Array.isArray(e.chains))return true;const t=e.state;return lw(t)&&Array.isArray(t.chains)})(n.promptChains)||t.push("backupValidationPromptChainsType")),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 dw(e,t){const n=e.getElementsByTagNameNS("*",t)[0];return n?.textContent?.trim()||null}function uw(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(`${nv}_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 hw(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=>uw(dw(e,"href"),dw(e,"getcontentlength"),dw(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 uw(r?.[1]??null,o?.[1]??null,i?.[1]??null)}).filter(e=>Boolean(e))}(e)}const gw=[{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 pw(e){return gw.some(t=>t.id===e)}function mw(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 fw={enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:nv};class bw{config=fw;autoSyncTimer=null;constructor(){this.loadConfig();}async loadConfig(){const{getSettingsState:e}=await o(async()=>{const{getSettingsState:e}=await Promise.resolve().then(()=>Wi);return {getSettingsState:e}},void 0),t=e();if(t?.webdav){const e={...fw,...t.webdav,provider:pw(t.webdav.provider)?t.webdav.provider:void 0};!e.provider&&e.url&&(e.provider=mw(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(()=>Wi);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 so.includes(e)&&n?.state&&(n=lo.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 `${nv}_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=hw(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=cw(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(so.includes(e)){let n;if(lo.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?r:"readingHistory"!==e||void 0===r.history&&void 0===r.lastCleanupRun?"readingHistory"===e?{history:t}:{[e]:t}:r;}else n="promptChains"===e?Array.isArray(t)?{chains:t}:"object"!=typeof t||Array.isArray(t)||void 0===t.chains?{chains:[]}:t:{[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 yw=null;function vw(){return yw||(yw=new bw),yw}let xw=null;const ww=Vo()(Yo((e,t)=>(xw=()=>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:Ko(()=>Ti),partialize:e=>({history:e.history,lastCleanupRun:e.lastCleanupRun}),onRehydrateStorage:()=>()=>{xw?.();}})),Sw=()=>ww.getState(),Cw=Object.freeze(Object.defineProperty({__proto__:null,getReadingHistoryStore:Sw,useReadingHistoryStore:ww},Symbol.toStringTag,{value:"Module"})),kw=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]},Tw=e=>e instanceof Error?e.message:String(e),Ew=e=>Boolean(e)&&"object"==typeof e&&!Array.isArray(e),Aw=({onClose:e,onRestore:t})=>{const[n,r]=_([]),[o,a]=_(true),[s,l]=_({show:false,title:"",message:"",onConfirm:()=>{}}),c=async()=>{a(true);try{const e=vw(),t=await e.getBackupList();r(t);}catch(e){Gi(le("loadFailed")+": "+String(e));}finally{a(false);}};i.useEffect(()=>{c();},[]); return Re("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&&qe(yb,{title:s.title,message:s.message,danger:s.danger,onConfirm:s.onConfirm,onCancel:()=>l(e=>({...e,show:false}))}), Re("div",{className:"settings-modal",style:{width:"500px",height:"600px",background:"var(--gh-card-bg, #ffffff)",borderRadius:"12px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ Re("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ qe("div",{style:{fontWeight:600,fontSize:"16px"},children:le("webdavBackupList")}), Re("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ qe(Sd,{content:le("refresh"),children:qe("button",{onClick:c,className:"settings-btn settings-btn-secondary","aria-label":le("refresh"),style:{padding:"6px",display:"flex",alignItems:"center"},children:qe(He,{size:16})})}), qe("button",{onClick:e,className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px"},children:"✕"})]})]}), qe("div",{style:{overflowY:"auto",padding:"16px",flex:1},children:o?qe("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:le("loading")}):0===n.length?qe("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:le("noBackupsFound")}):qe("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:n.map(e=>Re("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:[ Re("div",{style:{minWidth:0,flex:1,marginRight:"12px"},children:[ qe("div",{style:{fontSize:"13px",fontWeight:500,color:"var(--gh-text, #1f2937)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginTop:"2px"},children:[kw(e.size)," • ",e.lastModified.toLocaleString()]})]}), Re("div",{style:{display:"flex",gap:"6px",flexShrink:0},children:[ qe(Sd,{content:le("restore"),children:qe("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=vw();if((await n.download(e.name)).success){try{"extension"===ti.type&&"undefined"!=typeof chrome&&(await ti.storage.set(wi,Date.now()),await chrome.runtime.sendMessage({type:qd}));}catch{}Gi(le("restoreSuccess")),setTimeout(()=>{t();},1500);}else Gi(le("restoreError")),a(!1);}catch(n){Gi(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:qe(cn,{size:16,color:"currentColor"})})}), qe(Sd,{content:le("delete"),children:qe("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=vw();(await t.deleteFile(e.name)).success?(Gi(le("deleteSuccess")),c()):(Gi(le("deleteError")),a(!1));}catch(t){Gi(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:qe(Wt,{size:16,color:"currentColor"})})})]})]},e.name))})})]})]})},Mw=({onNavigate:e})=>{const{settings:t,setSettings:n,resetSettings:r}=zi(),[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=pw(e.provider)?e.provider:e.url?mw(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=>{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 so.includes(e)&&n?.state&&(n=lo.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","promptChains"],e));let i=[],a=[];try{const t="string"==typeof e.prompts?JSON.parse(e.prompts):e.prompts;t?.state?.prompts&&(i=t.state.prompts);const n="string"==typeof e.promptChains?JSON.parse(e.promptChains):e.promptChains,r=n?.state;Ew(r)&&Array.isArray(r.chains)&&(a="number"==typeof r.defaultChainsVersion?{chains:r.chains,defaultChainsVersion:r.defaultChainsVersion}:r.chains);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"prompts",data:{prompts:i,promptChains:a}},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),Gi(le("exportSuccess"));}catch{Gi(le("exportError"));}},f=async e=>{try{const n=JSON.parse(e),r=cw(n);if(!r.valid)return console.error("Backup validation failed:",r.errorKeys),void Gi(le("invalidBackupFile"));h({show:!0,title:le("importData"),message:Re("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ qe("div",{children:le("importConfirm")}), qe("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:Re("div",{style:{display:"grid",gridTemplateColumns:"72px 1fr",rowGap:"6px",columnGap:"10px",alignItems:"start"},children:[ qe("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:le("backupTime")}), qe("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:String(n.timestamp||"-")}), qe("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:le("backupType")}), qe("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")))})]})}), qe("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(so.includes(t)){let r=n;if(lo.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 if("promptChains"===t)if(Array.isArray(n))r={chains:n};else if(Ew(n)){const e=n.state;r=Ew(e)&&Array.isArray(e.chains)?e:void 0!==n.chains?n:{chains:[]};}else r={chains:[]};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(async e=>{await new Promise((t,n)=>chrome.storage.local.set(e,()=>chrome.runtime.lastError?n(chrome.runtime.lastError):t()));})(e),await(async()=>{try{"extension"===ti.type&&"undefined"!=typeof chrome&&(await ti.storage.set(wi,Date.now()),await chrome.runtime.sendMessage({type:qd}));}catch{}})(),Gi(le("importSuccess")),setTimeout(()=>window.location.reload(),1e3);}catch(e){console.error("[Backup] import storage write failed:",e),Gi(`${le("importError")}${Tw(e)}`);}}});}catch(n){console.error("[Backup] import parse failed:",n),Gi(`${le("importError")}${Tw(n)}`);}var t;},b=async e=>{const t=c.url;if(!t)return Gi(le("webdavConfigIncomplete")),false;if(!ti.hasCapability("permissions"))return await e(),true;try{const n=new URL(t).origin+"/*";return (await chrome.runtime.sendMessage({type:Md,origin:n})).hasPermission?(await e(),!0):(p({show:!0,onConfirm:async()=>{p(e=>({...e,show:!1}));try{const t=await chrome.runtime.sendMessage({type:Ld,permType:"allUrls"});if(!t.success)return void Gi(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 Gi(le("permissionRequired"));await e();}catch(vT){console.warn("WebDAV permission request failed:",vT),Gi(le("permissionRequired"));}}}),!1)}catch(n){return console.warn("Perm check logic skipped:",n),await e(),true}},y=(()=>{const e=t.webdav??gi.webdav,n=e.provider??(e.url?mw(e.url):"custom");return c.url!==e.url||c.username!==e.username||c.password!==e.password||c.remoteDir!==e.remoteDir||c.provider!==n})(); return Re("div",{className:"settings-content",children:[ qe(Ox,{title:le("navBackup"),Icon:yt}),u.show&&qe(yb,{title:u.title,message:u.message,danger:u.danger,onConfirm:u.onConfirm,onCancel:()=>h(e=>({...e,show:false}))}),g.show&&qe(yb,{title:le("permissionRequired"),message:le("webdavPermissionDesc"),onConfirm:g.onConfirm,onCancel:()=>p(e=>({...e,show:false}))}),o&&qe(Aw,{onClose:()=>i(false),onRestore:()=>window.location.reload()}), Re("div",{className:"backup-grid",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(400px, 1fr))",gap:"20px",marginBottom:"24px"},children:[ qe(Dx,{title:le("exportData"),description:le("exportDataDesc"),children:Re("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Re("div",{children:[ qe("div",{style:{fontWeight:500,fontSize:"14px"},children:le("fullBackup")}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("fullBackupDesc")})]}), qe("button",{onClick:()=>m("full"),className:"settings-btn settings-btn-success",style:{padding:"6px 16px"},children:le("export")})]}), Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Re("div",{children:[ qe("div",{style:{fontWeight:500,fontSize:"14px"},children:le("promptsBackup")}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("promptsBackupDesc")})]}), qe("button",{onClick:()=>m("prompts"),className:"settings-btn settings-btn-primary",style:{padding:"6px 16px"},children:le("export")})]}), Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Re("div",{children:[ qe("div",{style:{fontWeight:500,fontSize:"14px"},children:le("settingsBackup")}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("settingsBackupDesc")})]}), qe("button",{onClick:()=>m("settings"),className:"settings-btn settings-btn-secondary",style:{padding:"6px 16px"},children:le("export")})]})]})}), qe(Dx,{title:le("importData"),description:le("importDataDesc"),children:Re("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ qe("div",{style:{fontSize:"14px",fontWeight:500},children:le("selectFile")}), Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>a.current?.click(),style:{padding:"6px 12px"},children:[le("browse"), qe("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="");}})]})]}), Re("div",{style:{flex:1},children:[ qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginBottom:"4px"},children:le("dataPreview")}), qe("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"}})]}), qe("button",{onClick:()=>{s.trim()?f(s):Gi(le("selectFileOrPasteFirst"));},className:"settings-btn settings-btn-primary",style:{width:"100%",justifyContent:"center",padding:"8px"},disabled:!s.trim(),children:le("importBtn")})]})})]}), Re(Dx,{title:le("webdavConfig"),description:le("webdavConfigDesc"),children:[ Re("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:[ Re("div",{style:{fontWeight:600,marginBottom:"4px",display:"flex",alignItems:"center",gap:"6px",color:"var(--gh-text)"},children:[ qe(xt,{size:14,color:"var(--gh-primary, #4285f4)"})," ",le("restoreTip")]}), qe("div",{style:{lineHeight:1.5},children:le("restoreTipContent")})]}), qe(Bx,{label:le("webdavProvider"),children:qe("select",{className:"settings-input settings-select",value:c.provider||"custom",onChange:e=>{const t=e.target.value,n=gw.find(e=>e.id===t);d(e=>({...e,provider:t,...n?.urlTemplate?{url:n.urlTemplate}:{}}));},style:{width:"280px"},children:gw.map(e=>qe("option",{value:e.id,children:le(e.labelKey)},e.id))})}),(()=>{const e=gw.find(e=>e.id===(c.provider||"custom"));return e?.hintKey?Re("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:[ qe(xt,{size:14,color:"var(--gh-primary, #4285f4)",style:{flexShrink:0,marginTop:"1px"}}), Re("div",{children:[le(e.hintKey),e.helpUrl&&qe("a",{href:e.helpUrl,target:"_blank",rel:"noreferrer noopener",style:{marginLeft:"6px",color:"var(--gh-primary, #4285f4)",textDecoration:"underline"},children:le("learnMore")})]})]}):null})(), qe(Bx,{label:le("webdavAddress"),children:(()=>{const e=gw.find(e=>e.id===(c.provider||"custom")); return qe("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"}})})()}), qe(Bx,{label:le("username"),children:qe("input",{type:"text",className:"settings-input",value:c.username,onChange:e=>d({...c,username:e.target.value}),style:{width:"280px"}})}), qe(Bx,{label:le("password"),children:(()=>{const e=gw.find(e=>e.id===(c.provider||"custom")),t=le(e?.passwordPlaceholderKey?e.passwordPlaceholderKey:"webdavPasswordPlaceholder"); return qe("input",{type:"password",className:"settings-input",placeholder:t,value:c.password,onChange:e=>d({...c,password:e.target.value}),style:{width:"280px"}})})()}), qe(Bx,{label:le("defaultDir"),description:le("defaultDirHint"),children:qe("input",{type:"text",className:"settings-input",placeholder:"ophel",value:c.remoteDir,onChange:e=>d({...c,remoteDir:e.target.value}),style:{width:"280px"}})}), Re("div",{style:{marginTop:"16px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"8px"},children:[ Re("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Re("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{await b(async()=>{const e=vw();await e.setConfig(c,!1);(await e.testConnection()).success?Gi(le("webdavConnectionSuccess")):Gi(le("webdavConnectionFailed"));});},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ qe(ln,{size:16})," ",le("webdavTestBtn")]}), Re("div",{style:{position:"relative"},children:[ Re("button",{className:"settings-btn "+(y?"settings-btn-primary":"settings-btn-secondary"),onClick:()=>{const e=t.webdav??gi.webdav;n({webdav:{...e,...c}}),Gi(le("saveSuccess"));},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ qe(sn,{size:16})," ",le("saveConfig")]}),y&&qe("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)"}})]})]}), Re("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Re("button",{className:"settings-btn settings-btn-secondary",style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await b(async()=>{const e=vw();await e.setConfig(c,!1),i(!0);});},children:[ qe(cn,{size:16,color:"currentColor"})," ",le("restore")]}), Re("button",{className:"settings-btn "+(y?"settings-btn-secondary":"settings-btn-primary"),style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await b(async()=>{const e=vw();await e.setConfig(c,!1);(await e.upload()).success?Gi(le("webdavUploadSuccess")):Gi(le("webdavUploadFailed"));});},children:[ qe(vt,{size:16,color:"currentColor"})," ",le("backupNow")]})]})]})]}), qe(Dx,{title:le("dangerZone"),description:le("dangerZoneDesc"),className:"danger-zone-card",children:Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Re("div",{children:[ qe("div",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-danger, #ef4444)"},children:le("clearAllData")}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("clearAllDataDesc")})]}), qe("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"===ti.type&&"undefined"!=typeof chrome)try{await chrome.runtime.sendMessage({type:Nd});}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 ti.storage.set(oi,Date.now()),r(),nb.getState().setPrompts(co()),wy.getState().setChains(ho()),lf.setState({folders:go}),hf.setState({tags:[]}),tf.setState({conversations:{},lastUsedFolderId:"inbox"}),ww.setState({history:{},lastCleanupRun:0}),Gi(le("clearSuccess")),setTimeout(()=>window.location.reload(),1500);}catch(e){Gi(le("error")+": "+String(e));}}});},style:{padding:"8px 16px",fontSize:"13px"},children:le("clearAllData")})]})})]})},Iw="ophel:usageMonitor",Lw={version:2,records:{},events:[]},Nw=(e,t=0)=>Number.isFinite(e)?Math.max(0,Math.floor(e)):t,qw=e=>{const t=Date.now();return e?{count:Nw(e.count),updatedAt:Nw(e.updatedAt,t),resetAt:Nw(e.resetAt,t)}:{count:0,updatedAt:t,resetAt:t}},Rw=e=>{if(!e||"object"!=typeof e)return null;const t=Nw(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:Nw(e.countDelta,1)||1,requestTokens:Nw(e.requestTokens),roundTripTokens:Nw(e.roundTripTokens),loadedConversationTokens:Nw(e.loadedConversationTokens),loadedOutputTokens:Nw(e.loadedOutputTokens)}},Pw=e=>{const t=Date.now();return e.filter(e=>t-e.ts<=3456e7).sort((e,t)=>e.ts-t.ts).slice(-4e3)},Dw=e=>{if(!e||"object"!=typeof e)return {...Lw};const t=Array.isArray(e.events)?e.events:[];return {version:2,records:e.records&&"object"==typeof e.records?e.records:{},events:Pw(t.map(e=>Rw(e)).filter(Boolean))}};async function Bw(){const e=await ti.storage.get(Iw);return Dw(e)}async function $w(e){await ti.storage.set(Iw,Dw(e));}const _w=e=>{const t=new Date(e);return t.setMinutes(0,0,0),t},Ow=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t},zw=e=>{const t=new Date(e);return t.setDate(1),t.setHours(0,0,0,0),t},Fw=e=>`${`${e.getHours()}`.padStart(2,"0")}:00`,Uw=e=>`${e.getMonth()+1}/${e.getDate()}`,Hw=e=>`${e.getFullYear()}/${`${e.getMonth()+1}`.padStart(2,"0")}`,Ww=(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 jw(e){return ti.storage.watch(Iw,(t,n)=>{e(Dw(t),Dw(n));})}const Gw=({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 qe("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})},Qw=({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:yo,label:"Gemini"},{id:wo,label:"Gemini Enterprise"},{id:vo,label:"ChatGPT"},{id:bo,label:"Claude"},{id:So,label:"Grok"},{id:Co,label:"AI Studio"},{id:Eo,label:"DeepSeek"},{id:ko,label:"Doubao"},{id:To,label:"ima"},{id:xo,label:"ChatGLM"},{id:Ao,label:"Kimi"},{id:Mo,label:"Qianwen"},{id:Io,label:"Qwen Studio"},{id:No,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 Bw()).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=_w(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}-${r.getHours()}`,l=Fw(r)):"day"===t?(e.setDate(e.getDate()-a),r=Ow(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`,l=Uw(r)):(e.setMonth(e.getMonth()-a),r=zw(e),s=`${r.getFullYear()}-${r.getMonth()}`,l=Hw(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=jw(()=>{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=>Ww(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)),q=l.map((e,t)=>{const n=E+I*t,o=Ww(e,r);return {x:n,y:k+M-o/v*M,value:o,label:e.label}}),R=q.length>0?q.map((e,t)=>`${0===t?"M":"L"} ${e.x.toFixed(2)} ${e.y.toFixed(2)}`).join(" "):"",P=q.length>0?`${R} L ${q[q.length-1].x.toFixed(2)} ${(k+M).toFixed(2)} L ${q[0].x.toFixed(2)} ${(k+M).toFixed(2)} Z`:"",D=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,Q="var(--gh-border, #e5e7eb)",V="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 Re("div",{style:{marginTop:"14px",padding:"14px",borderRadius:"12px",border:`1px solid ${ee}`,background:"var(--gh-bg-secondary, #f9fafb)"},children:[ Re("div",{style:{display:"flex",justifyContent:"space-between",gap:"12px",flexWrap:"wrap"},children:[ Re("div",{children:[ qe("div",{style:{fontSize:"14px",fontWeight:600,color:"var(--gh-text, #374151)"},children:le("usageMonitorChartTitle")}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:le("usageMonitorChartDesc")}), Re("div",{style:{marginTop:"8px",display:"inline-flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[ qe("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:le("usageMonitorChartSiteLabel")}), qe("select",{className:"settings-select",value:a,onChange:e=>s(e.target.value),style:{minWidth:"170px"},children:m.map(e=>qe("option",{value:e.id,children:e.label},e.id))})]})]}), Re("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap",alignItems:"flex-start"},children:[ qe("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["hour",le("usageMonitorChartHour")],["day",le("usageMonitorChartDay")],["month",le("usageMonitorChartMonth")]].map(([e,r])=>qe(xb,{size:"sm",variant:t===e?"primary":"secondary",onClick:()=>n(e),children:r},e))}), qe("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])=>qe(xb,{size:"sm",variant:r===e?"primary":"secondary",onClick:()=>o(e),children:t},e))})]})]}), Re("div",{style:{display:"flex",gap:"18px",marginTop:"12px",marginBottom:"8px",flexWrap:"wrap"},children:[ Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Re("span",{children:[w,": "]}), qe("strong",{style:{color:"var(--gh-text, #374151)"},children:x})]}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Re("span",{children:[le("usageMonitorChartCurrentSite"),": "]}), qe("strong",{style:{color:"var(--gh-text, #374151)"},children:f})]}), Re("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ qe("span",{children:"MAX: "}), qe("strong",{style:{color:"var(--gh-text, #374151)"},children:v})]}), qe("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:qe("span",{children:le("usageMonitorChartScrollHint")})})]}), Re("div",{style:{position:"relative",marginTop:"4px"},onMouseLeave:()=>g(null),children:[ Re("div",{ref:p,style:{position:"relative",borderRadius:"10px",overflowX:"auto",overflowY:"hidden",background:J,border:`1px solid ${ee}`,minHeight:"220px"},children:[ qe("div",{style:{width:`${C}px`,minWidth:"100%",position:"relative"},children:Re("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 qe("line",{x1:E,x2:C-T,y1:t,y2:t,stroke:Q,strokeWidth:"1",opacity:.6},e)}),P&&qe("path",{d:P,fill:V}),R&&qe("path",{d:R,fill:"none",stroke:K,strokeWidth:"2.5",strokeLinejoin:"round",strokeLinecap:"round"}),q.map(e=>qe("circle",{cx:e.x,cy:e.y,r:"3",fill:K},`${e.label}-${e.x}`)),B&&qe("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=q[t],r=q[t-1],o=q[t+1],i=r?(r.x+n.x)/2:E,a=o?(n.x+o.x)/2:C-T; return qe("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 qe("text",{x:E+I*t,y:210,textAnchor:"middle",fill:Y,fontSize:"11",children:e.label},e.key)})]})}),!d&&l.every(e=>0===Ww(e,r))&&qe("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Y,fontSize:"13px"},children:le("usageMonitorChartEmpty")})]}),D&&B&&Re("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:[ qe("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")}`})(D)}),null!==F&&Re("div",{style:{fontSize:"11px",marginBottom:"8px",color:"var(--gh-text-secondary, #6b7280)"},children:[w,": ",O," · ",F>=0?"+":"",F," ",le("usageMonitorChartDelta")]}), Re("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"6px 10px",fontSize:"12px"},children:[ qe("span",{style:{color:Y},children:le("usageMonitorChartMetricCount")}), qe("strong",{children:D.count}), qe("span",{style:{color:Y},children:le("usageMonitorChartMetricRequest")}), qe("strong",{children:D.requestTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMetricRoundTrip")}), qe("strong",{children:D.roundTripTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMetricConversation")}), qe("strong",{children:D.loadedConversationTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMetricOutput")}), qe("strong",{children:D.loadedOutputTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMaxConversation")}), qe("strong",{children:D.maxLoadedConversationTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMaxRequest")}), qe("strong",{children:D.maxRequestTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMaxRoundTrip")}), qe("strong",{children:D.maxRoundTripTokens}), qe("span",{style:{color:Y},children:le("usageMonitorChartMaxOutput")}), qe("strong",{children:D.maxLoadedOutputTokens})]})]})]})]})},Vw=({siteId:e,initialTab:t})=>{const n=[{id:Ir,label:le("tabOutline")},{id:Lr,label:le("tabConversations")},{id:Nr,label:le("tabPrompts")},{id:qr,label:le("tabSettingsTab")},{id:Rr,label:le("reminderTab")},{id:Pr,label:le("navContent")},{id:Dr,label:le("readingHistoryTitle")}],[r,o]=_(t||n[0].id),[a,s]=_(false),l=i.useRef(null),{settings:c,updateDeepSetting:d,updateNestedSetting:u}=zi(),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!==Rr&&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=ao.length>1,M=e=>le("secondsValueLabel",{val:String(e)}),I=e=>`${e}x`,N=le("notificationSoundPreviewButtonLabel"),q=e=>{const t=e||c.tab?.notificationSoundPreset||ao[0].id,n=ti.getNotificationSoundUrl(t);if(!n)return void Gi(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),Gi(le("notificationSoundPreviewFailed"),2e3);},s(true),r.play().catch(()=>{h(),s(false),Gi(le("notificationSoundPreviewFailed"),2e3);});},R=Re(Dx,{title:le("notificationSettings"),children:[ qe($x,{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(!ti.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 Rd({type:Id,permissions:["notifications"]});e.success&&e.hasPermission?u("tab","showNotification",true):(await Rd({type:Ld,permType:"notifications"}),Gi(le("permissionRequestToast"),3e3));}}}}), qe($x,{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&&qe(Bx,{label:le("notificationSoundPresetLabel"),settingId:"tab-notification-sound-preset",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("select",{className:"settings-select",value:c.tab?.notificationSoundPreset||ao[0].id,onChange:e=>{const t=e.target.value;u("tab","notificationSoundPreset",t),q(t);},disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{flex:1},children:ao.map(e=>qe("option",{value:e.id,children:le(e.labelKey)},e.id))}), qe(xb,{type:"button",variant:a?"primary":"secondary",size:"sm",onClick:()=>q(),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{minWidth:"56px",flexShrink:0},children:N})]})}), qe(Bx,{label:le("notificationVolumeLabel"),settingId:"tab-notification-volume",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("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"}}), Re("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(c.tab?.notificationVolume||.5)),"%"]})]})}), qe(Bx,{label:le("notificationRepeatCountLabel"),settingId:"tab-notification-repeat-count",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:qe("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=>qe("option",{value:e,children:I(e)},e))})}), qe(Bx,{label:le("notificationRepeatIntervalLabel"),settingId:"tab-notification-repeat-interval",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:qe("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=>qe("option",{value:e,children:M(e)},e))})}), qe($x,{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)}), qe($x,{label:le("autoFocusLabel"),description:le("autoFocusDesc"),settingId:"tab-auto-focus",checked:c.tab?.autoFocus??false,onChange:()=>u("tab","autoFocus",!c.tab?.autoFocus)})]}),P=Re(Dx,{title:le("usageMonitorSettingsTitle"),description:le("usageMonitorSettingsDesc"),children:[ Re("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:[ qe("div",{children:le("usageMonitorExplainLocalOnly")}), qe("div",{children:le("usageMonitorExplainNoBackend")}), qe("div",{children:le("usageMonitorExplainReset")})]}), qe($x,{label:le("usageMonitorEnabledLabel"),description:le("usageMonitorEnabledDesc"),settingId:"usage-monitor-enabled",checked:c.usageMonitor?.enabled??false,onChange:()=>u("usageMonitor","enabled",!c.usageMonitor?.enabled)}), qe("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")}), qe(Bx,{label:le("usageMonitorDailyLimitLabel"),description:le("usageMonitorDailyLimitDesc"),settingId:"usage-monitor-daily-limit",disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(le("usageMonitorEnabledLabel")),children:qe(wb,{value:c.usageMonitor?.dailyLimit??100,onChange:e=>u("usageMonitor","dailyLimit",e),min:1,max:9999,defaultValue:100,disabled:!c.usageMonitor?.enabled,style:{width:"96px"}})}), qe($x,{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)}), qe(Qw,{siteId:e})]}); return Re("div",{children:[ qe(Ox,{title:le("navFeatures"),Icon:dt}), qe("p",{className:"settings-page-desc",children:le("featuresPageDesc")}), qe(_x,{tabs:n,activeTab:r,onTabChange:o}),r===qr&&Re(Ne,{children:[ Re(Dx,{title:le("tabBehaviorTitle"),children:[ qe($x,{label:le("openNewTabLabel"),description:le("openNewTabDesc"),settingId:"tab-open-new",checked:c.tab?.openInNewTab??true,onChange:()=>u("tab","openInNewTab",!c.tab?.openInNewTab)}), qe($x,{label:le("autoRenameTabLabel"),description:le("autoRenameTabDesc"),settingId:"tab-auto-rename",checked:c.tab?.autoRename??false,onChange:()=>u("tab","autoRename",!c.tab?.autoRename)}), qe(Bx,{label:le("renameIntervalLabel"),settingId:"tab-rename-interval",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:qe("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=>qe("option",{value:e,children:M(e)},e))})}), qe(Bx,{label:le("titleFormatLabel"),description:le("titleFormatDesc"),settingId:"tab-title-format",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:qe(Eb,{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"}})}), qe($x,{label:le("showStatusLabel"),description:le("showStatusDesc"),settingId:"tab-show-status",checked:c.tab?.showStatus??true,onChange:()=>u("tab","showStatus",!c.tab?.showStatus)}), qe($x,{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)})]}), Re(Dx,{title:le("privacyModeTitle"),children:[ qe($x,{label:le("privacyModeLabel"),description:le("privacyModeDesc"),settingId:"tab-privacy-mode",checked:c.tab?.privacyMode??false,onChange:()=>u("tab","privacyMode",!c.tab?.privacyMode)}), qe(Bx,{label:le("privacyTitleLabel"),settingId:"tab-privacy-title",disabled:!c.tab?.privacyMode,onDisabledClick:()=>m(v),children:qe("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===Rr&&Re(Ne,{children:[R,P]}),r===Ir&&Re(Ne,{children:[ Re(Dx,{title:le("outlineSettings"),description:le("outlineSettingsDesc"),children:[ qe($x,{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)}), qe(Bx,{label:le("outlineUpdateIntervalLabel"),description:le("outlineUpdateIntervalDesc"),settingId:"outline-update-interval",children:qe(wb,{value:c.features?.outline?.updateInterval??2,onChange:e=>d("features","outline","updateInterval",e),min:1,max:60,defaultValue:2,style:{width:"80px"}})}), qe(Bx,{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:Re("select",{className:"settings-select",value:c.features?.outline?.followMode||"current",onChange:e=>d("features","outline","followMode",e.target.value),children:[ qe("option",{value:"current",children:le("outlineFollowCurrent")}), qe("option",{value:"latest",children:le("outlineFollowLatest")}), qe("option",{value:"manual",children:le("outlineFollowManual")})]})}), qe($x,{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)})]}), Re(Dx,{title:le("bookmarkSettings"),description:le("bookmarkSettingsDesc"),children:[ qe(Bx,{label:le("inlineBookmarkModeLabel"),description:le("inlineBookmarkModeDesc"),settingId:"outline-inline-bookmark-mode",children:Re("select",{className:"settings-select",value:c.features?.outline?.inlineBookmarkMode||"always",onChange:e=>d("features","outline","inlineBookmarkMode",e.target.value),children:[ qe("option",{value:"always",children:le("inlineBookmarkModeAlways")}), qe("option",{value:"hover",children:le("inlineBookmarkModeHover")}), qe("option",{value:"hidden",children:le("inlineBookmarkModeHidden")})]})}), qe(Bx,{label:le("panelBookmarkModeLabel"),description:le("panelBookmarkModeDesc"),settingId:"outline-panel-bookmark-mode",children:Re("select",{className:"settings-select",value:c.features?.outline?.panelBookmarkMode||"always",onChange:e=>d("features","outline","panelBookmarkMode",e.target.value),children:[ qe("option",{value:"always",children:le("inlineBookmarkModeAlways")}), qe("option",{value:"hover",children:le("inlineBookmarkModeHover")}), qe("option",{value:"hidden",children:le("inlineBookmarkModeHidden")})]})})]}), qe(Dx,{title:le("scrollSettings"),children:qe($x,{label:le("preventAutoScrollLabel"),description:le("preventAutoScrollDesc"),settingId:"outline-prevent-auto-scroll",checked:c.panel?.preventAutoScroll??false,onChange:()=>u("panel","preventAutoScroll",!c.panel?.preventAutoScroll)})})]}),r===Lr&&Re(Ne,{children:[ Re(Dx,{title:le("conversationsSettingsTitle"),description:le("conversationsSettingsDesc"),children:[ qe($x,{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)}), qe($x,{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)}), qe($x,{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))})]}), Re(Dx,{title:le("exportSettings"),children:[ qe(Bx,{label:le("exportPackagingLabel"),description:le("exportPackagingDesc"),settingId:"export-packaging",children:qe(kb,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:C,value:S,ariaLabel:le("exportPackagingLabel"),onChange:e=>u("export","packaging",e)})}), qe($x,{label:le("exportFilenameTimestamp"),description:le("exportFilenameTimestampDesc"),settingId:"export-filename-timestamp",checked:c.export?.exportFilenameTimestamp??false,onChange:()=>u("export","exportFilenameTimestamp",!c.export?.exportFilenameTimestamp)}), qe($x,{label:le("exportIncludeThoughtsLabel"),description:le("exportIncludeThoughtsDesc"),settingId:"export-include-thoughts",checked:c.export?.includeThoughts??true,onChange:()=>u("export","includeThoughts",!(c.export?.includeThoughts??1))}), qe(Bx,{label:le("exportCustomUserName"),description:le("exportCustomUserNameDesc"),settingId:"export-custom-user-name",children:qe(Gw,{className:"settings-input",value:c.export?.customUserName||"",onChange:e=>u("export","customUserName",e),placeholder:"User",style:{width:"180px"}})}), qe(Bx,{label:le("exportCustomModelName"),description:le("exportCustomModelNameDesc"),settingId:"export-custom-model-name",children:qe(Gw,{className:"settings-input",value:c.export?.customModelName||"",onChange:e=>u("export","customModelName",e),placeholder:"Site Name",style:{width:"180px"}})})]})]}),r===Nr&&Re(Ne,{children:[ Re(Dx,{title:le("promptSettingsTitle"),description:le("promptSettingsDesc"),children:[ qe($x,{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)}), qe(Bx,{label:le("promptSubmitShortcutLabel"),description:le("promptSubmitShortcutDesc"),settingId:"shortcuts-prompt-submit-shortcut",children:Re("select",{className:"settings-select",value:c.features?.prompts?.submitShortcut??"enter",onChange:e=>d("features","prompts","submitShortcut",e.target.value),children:[ qe("option",{value:"enter",children:le("promptSubmitShortcutEnter")}), qe("option",{value:"ctrlEnter",children:le("promptSubmitShortcutCtrlEnter")})]})}), qe($x,{label:le("queueSettingLabel"),description:le("queueSettingDesc"),settingId:"prompt-queue",checked:c.features?.prompts?.promptQueue??false,onChange:()=>d("features","prompts","promptQueue",!c.features?.prompts?.promptQueue)})]}), qe(Dx,{title:le("quickQuoteSettingsTitle"),description:le("quickQuoteSettingsDesc"),children:qe($x,{label:le("quickQuoteEnabledLabel"),description:le("quickQuoteEnabledDesc"),settingId:"prompt-quick-quote-enabled",checked:c.features?.prompts?.quickQuoteEnabled??true,onChange:()=>d("features","prompts","quickQuoteEnabled",!(c.features?.prompts?.quickQuoteEnabled??1))})})]}),r===Dr&&Re(Dx,{title:le("readingHistoryTitle"),description:le("readingHistoryDesc"),children:[ qe($x,{label:le("readingHistoryPersistenceLabel"),description:le("readingHistoryPersistenceDesc"),settingId:"reading-history-persistence",checked:c.readingHistory?.persistence??true,onChange:()=>u("readingHistory","persistence",!c.readingHistory?.persistence)}), qe($x,{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)}), qe(Bx,{label:le("readingHistoryCleanup"),settingId:"reading-history-cleanup-days",disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(x),children:Re("select",{className:"settings-select",value:c.readingHistory?.cleanupDays||30,onChange:e=>u("readingHistory","cleanupDays",parseInt(e.target.value)),disabled:!c.readingHistory?.persistence,children:[ Re("option",{value:1,children:["1 ",le("day")]}), Re("option",{value:3,children:["3 ",le("days")]}), Re("option",{value:7,children:["7 ",le("days")]}), Re("option",{value:30,children:["30 ",le("days")]}), Re("option",{value:90,children:["90 ",le("days")]}), qe("option",{value:-1,children:le("forever")})]})})]}),r===Pr&&Re(Dx,{title:le("interactionEnhance"),description:le("interactionEnhanceDesc"),children:[ qe($x,{label:le("assistantMermaidLabel"),description:le("assistantMermaidDesc"),settingId:"content-assistant-mermaid",checked:c.content?.assistantMermaid??true,onChange:()=>u("content","assistantMermaid",!(c.content?.assistantMermaid??1))}), qe($x,{label:le("userQueryMarkdownLabel"),description:le("userQueryMarkdownDesc"),settingId:"content-user-query-markdown",checked:c.content?.userQueryMarkdown??true,onChange:()=>u("content","userQueryMarkdown",!(c.content?.userQueryMarkdown??1))}), qe($x,{label:le("formulaCopyLabel"),description:le("formulaCopyDesc"),settingId:"content-formula-copy",checked:c.content?.formulaCopy??true,onChange:()=>u("content","formulaCopy",!c.content?.formulaCopy)}), qe(Bx,{label:le("formulaCopyFormatLabel"),description:le("formulaCopyFormatDesc"),settingId:"content-formula-copy-format",disabled:!c.content?.formulaCopy,onDisabledClick:()=>m(w),children:qe(kb,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:T,value:k,ariaLabel:le("formulaCopyFormatLabel"),disabled:!c.content?.formulaCopy,onChange:e=>u("content","formulaCopyFormat",e)})}), qe($x,{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)}), qe($x,{label:le("tableCopyLabel"),description:le("tableCopyDesc"),settingId:"content-table-copy",checked:c.content?.tableCopy??true,onChange:()=>u("content","tableCopy",!c.content?.tableCopy)})]})]})},Kw=(e,t)=>{const n=le(e);return n===e?t:n},Zw=({siteId:e})=>{const{settings:t,updateNestedSetting:n}=zi();if(!t)return null;const r=t.globalSearch?.promptEnterBehavior||"smart",o=t.globalSearch?.doubleShift??gi.globalSearch.doubleShift,i=t.globalSearch?.enableFuzzySearch??false,a=mr(),s=t.shortcuts?.keybindings?.[Kn],l=null===s?null:s||sr[Kn],c=l?pr(l,a):"",d=[];o&&d.push(Kw("globalSearchTriggerDoubleShift","double-press Shift")),c&&d.push(c);const u=((e,t,n)=>{let r=Kw(e,t);return Object.keys(n).forEach(e=>{r=r.replace(new RegExp(`{${e}}`,"g"),n[e]);}),r})("globalSearchTriggerHint","Trigger: {shortcut}",{shortcut:d.join(" / ")||Kw("shortcutNotSet","Not set")}),h=`shortcut-binding-${Kn}`; return Re("div",{children:[ qe(Ox,{title:Kw("navGlobalSearch","Global Search"),Icon:Yt}), qe("p",{className:"settings-page-desc",children:`${Kw("globalSearchPageDesc","Configure Search Everywhere behavior and interaction details")} · ${u}`}), Re(Dx,{title:Kw("globalSearchMatchingSettingsTitle","Search Matching"),description:Kw("globalSearchMatchingSettingsDesc","Configure how Search Everywhere matches search results"),children:[ qe(Bx,{label:Kw("globalSearchShortcutSettingLabel","全局搜索快捷键"),description:Kw("globalSearchShortcutSettingDesc","跳转到快捷键设置,自定义或禁用全局搜索快捷键。"),settingId:"global-search-shortcut-setting-link",children:qe("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:Tr,settingId:h}}));},children:Kw("globalSearchShortcutSettingAction","前往设置")})}), qe($x,{label:Kw("doubleShiftToSearch","Double Shift to open Global Search"),description:Kw("doubleShiftToSearchDesc","Press Shift twice quickly to open Global Search"),checked:o,onChange:()=>n("globalSearch","doubleShift",!o),settingId:"global-search-double-shift"}), qe($x,{label:Kw("globalSearchEnableFuzzySearchLabel","Enable fuzzy search"),description:Kw("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"})]}), qe(Dx,{title:Kw("globalSearchPromptSettingsTitle","Prompt Behavior"),description:Kw("globalSearchPromptSettingsDesc","Choose what happens when pressing Enter on a prompt result in Search Everywhere"),children:qe(Bx,{label:Kw("globalSearchPromptEnterBehaviorLabel","Search Everywhere prompt Enter behavior"),description:Kw("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:Re("select",{className:"settings-select",value:r,onChange:e=>n("globalSearch","promptEnterBehavior",e.target.value),children:[ qe("option",{value:"smart",children:Kw("globalSearchPromptEnterBehaviorSmart","Smart (Recommended)")}), qe("option",{value:"locate",children:Kw("globalSearchPromptEnterBehaviorLocate","Locate Only")})]})})})]})},Yw=({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})=>Re("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:[ qe("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:qe(wt,{size:16})}),e&&qe("span",{className:"settings-sortable-item-icon",children:e}), qe("span",{className:"settings-sortable-item-label",children:t}), qe("div",{className:"settings-sortable-item-actions",children:i&&qe(mb,{checked:o,onChange:()=>a?.(),size:"sm"})})]}),Xw=({siteId:e,initialTab:t})=>{const[n,r]=_(t||"panel"),{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l,updateDeepSetting:c}=zi();L(()=>{t&&r(t);},[t]);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 Re("div",{children:[ qe(Ox,{title:le("navGeneral"),Icon:st}), qe("p",{className:"settings-page-desc",children:le("generalPageDesc")}), qe(_x,{tabs:y,activeTab:n,onTabChange:r}),"panel"===n&&Re(Dx,{title:le("panelSettings"),children:[ qe(Bx,{label:le("panelModeLabel"),description:le("panelModeDesc"),settingId:"panel-mode",children:qe("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[{value:"edge-snap",label:le("panelModeEdgeSnap"),Icon:nn},{value:"floating",label:le("panelModeFloating"),Icon:rn}].map((e,t)=>Re("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:[ qe(e.Icon,{size:14}),e.label]},e.value))})}), qe(Bx,{label:le("defaultPositionLabel"),description:le("defaultPositionDesc"),settingId:"panel-default-position",children:Re("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[ qe("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")}), qe("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")})]})}), qe(Bx,{label:le("panelWidthLabel"),description:le("panelWidthDesc"),settingId:"panel-width",children:qe(Cb,{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")})}), qe(Bx,{label:le("panelHeightLabel"),description:le("panelHeightDesc"),settingId:"panel-height",children:qe(Cb,{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")&&qe(Bx,{label:le("edgeSnapThresholdLabel"),description:le("edgeSnapThresholdDesc"),settingId:"panel-edge-snap-threshold",children:qe(Cb,{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")&&qe(Bx,{label:le("defaultEdgeDistanceLabel"),description:le("defaultEdgeDistanceDesc"),settingId:"panel-edge-distance",children:qe(Cb,{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&&qe(Dx,{title:le("tabOrderSettings"),description:le("tabOrderDesc"),children:o.features?.order?.filter(e=>Zr[e]).map((e,t)=>{const n=Zr[e],r="prompts"===e?false!==o.features?.prompts?.enabled:"outline"===e?false!==o.features?.outline?.enabled:"conversations"!==e||false!==o.features?.conversations?.enabled; return qe(Yw,{iconNode:n.IconComponent?qe(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:le(n.label),index:t,total:o.features?.order.filter(e=>Zr[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&&Re(Ne,{children:[ Re(Dx,{title:le("quickButtonsBehaviorTitle"),description:le("quickButtonsBehaviorDesc"),children:[ qe($x,{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)}), qe(Bx,{label:le("quickButtonsProximityRadiusLabel"),description:le("quickButtonsProximityRadiusDesc"),settingId:"quick-buttons-proximity-radius",children:Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("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"}}), Re("span",{style:{fontSize:"12px",minWidth:"36px"},children:[o.quickButtons?.proximityRadius??150,"px"]})]})}), qe(Bx,{label:le("quickButtonsOpacityLabel"),description:le("quickButtonsOpacityDesc"),settingId:"quick-buttons-opacity",children:Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("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"}}), Re("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(o.quickButtons?.opacity??1)),"%"]})]})})]}), qe(Dx,{title:le("collapsedButtonsOrderTitle"),description:le("collapsedButtonsOrderDesc"),children:o.quickButtons?.collapsed?.map((e,t)=>{if("manualAnchor"===e.id)return null;const n=Yr[e.id];return n?qe(Yw,{iconNode:n.IconComponent?qe(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&&qe(Dx,{title:le("toolboxMenuTitle"),description:le("toolboxMenuDesc"),children:Wo.filter(e=>e.id!==Ho).map(e=>{const t=(o.quickButtons?.toolsMenu??Wo.map(e=>e.id)).includes(e.id); return qe($x,{label:le(e.labelKey),settingId:`tools-menu-${e.id}`,checked:t,onChange:()=>{const n=o.quickButtons?.toolsMenu??Wo.map(e=>e.id),r=t?n.filter(t=>t!==e.id):[...n,e.id];l("quickButtons","toolsMenu",r);}},e.id)})})]})},Jw=[{id:"storage",name:"存储",nameKey:"permissionStorage",description:"permissionStorageDesc",icon:"💾"}],eS=[{id:"notifications",name:"通知",nameKey:"permissionNotifications",description:"permissionNotificationsDesc",icon:"🔔",permissions:["notifications"]},{id:"cookies",name:"Cookie管理",nameKey:"permissionCookies",description:"permissionCookiesDesc",icon:"🍪",permissions:["cookies"]}],tS=[{id:"webdav",name:"WebDAV 访问权限",nameKey:"permissionWebdavAccess",description:"permissionWebdavAccessDesc",icon:"☁️",origins:[""]}],nS=()=>{const{updateNestedSetting:e}=zi(),[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 eS)try{let t=!1;if(s)t=await chrome.permissions.contains({permissions:n.permissions||[]});else {const e=await Rd({type:Id,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 tS)try{let t=!1;if(s)t=await chrome.permissions.contains({origins:n.origins||[]});else {const e=await Rd({type:Id,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 Rd({type:Ld,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=tS[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:qe("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 Rd({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 Re("div",{children:[ qe(Ox,{title:le("navPermissions"),Icon:ut}), qe("p",{className:"settings-page-desc",children:le("permissionsPageDesc")}), Re(Dx,{title:le("optionalPermissions"),description:le("optionalPermissionsDesc"),children:[ Re("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",paddingBottom:"12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ qe("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #9ca3af)"},children:le("permissionsSyncHint")}), qe("button",{className:"settings-btn settings-btn-secondary",onClick:async e=>{e.preventDefault(),e.stopPropagation(),await l(),Gi(le("permissionsRefreshed"),1500);},disabled:r,style:{fontSize:"12px",padding:"4px 12px",flexShrink:0},children:le(r?"refreshing":"refreshStatus")})]}),[...eS,...tS].map((e,n,r)=>qe(Bx,{label:Re("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("span",{style:{fontSize:"18px"},children:e.icon}), qe("span",{children:le(e.nameKey)})]}),description:le(e.description),style:n===r.length-1?{borderBottom:"none"}:{},children:qe("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:t[e.id]?Re(Ne,{children:[ qe("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(16, 185, 129, 0.1)",color:"#10b981"},children:le("granted")}), qe("button",{className:"settings-btn settings-btn-secondary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),d(e);},children:le("revoke")})]}):Re(Ne,{children:[ qe("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(239, 68, 68, 0.1)",color:"#ef4444"},children:le("notGranted")}), qe("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))]}), qe(Dx,{title:le("requiredPermissions"),description:le("requiredPermissionsDesc"),children:Jw.map((e,t)=>qe(Bx,{label:Re("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("span",{style:{fontSize:"18px"},children:e.icon}), qe("span",{children:le(e.nameKey)})]}),description:le(e.description),style:t===Jw.length-1?{borderBottom:"none"}:{},children:qe("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&&qe(yb,{title:le("warning"),message:i.message,confirmText:le("confirm"),cancelText:le("cancel"),danger:true,onConfirm:i.onConfirm,onCancel:()=>a(e=>({...e,open:false}))})]})},rS=({binding:e,onChange:t,onRemove:n,conflictWarning:r})=>{const[o,i]=_(false),a=mr(),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:ur(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?pr(e,a):le("shortcutNotSet"); return Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe("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&&qe(Sd,{content:le("shortcutRemove"),children:qe("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&&qe("span",{style:{fontSize:"12px",color:"var(--gh-error, #ef4444)"},children:r})]})},oS=({siteId:e})=>{const{settings:t,setSettings:n}=zi(),r=t?.shortcuts,o=i.useMemo(()=>mr(),[]),a=E((e,t)=>{if(!t)return;const n=hr(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=ir[r];if(!t)continue;const o=hr(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:{...sr}}}),d(false);},[r,n]),h=Object.entries(ar).map(([e,t])=>{const n=Object.entries(ir).filter(([,t])=>t.category===e);return {categoryId:e,categoryMeta:t,actions:n}});return t?Re("div",{children:[ qe(Ox,{title:le("navShortcuts"),Icon:Lt}), qe("p",{className:"settings-page-desc",children:le("shortcutsPageDesc")}), Re(Dx,{title:le("shortcutsGlobalSettings"),children:[ qe($x,{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??sr}})}),ti.hasCapability("commands")&&Re(Ne,{children:[ qe(Bx,{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:qe("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??sr}}),style:{width:"280px"},placeholder:"https://gemini.google.com"})}), qe(Bx,{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 qe("span",{style:{fontSize:"13px",color:"var(--gh-text-tertiary)"},children:le("browserNotSupported")});let o="chrome://extensions/shortcuts";return n&&(o="edge://extensions/shortcuts"),r?qe("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:"1.5"},children:le("firefoxShortcutsGuide")}):qe("button",{onClick:()=>Rd({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")})})()})]}), qe("div",{style:{marginTop:"16px",paddingTop:"16px",display:"flex",justifyContent:"flex-end"},children:qe("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})=>qe(Dx,{title:le(t.labelKey),children:n.map(([e,t])=>{const n=r?.keybindings?.[e],o=null===n?null:n||sr[e],i=a(e,o); return qe(Bx,{label:le(t.labelKey),disabled:!r?.enabled,settingId:`shortcut-binding-${e}`,children:qe(rS,{binding:o,onChange:t=>s(e,t),onRemove:()=>l(e),conflictWarning:i||void 0})},e)})},e)),c&&qe(yb,{title:le("resetShortcuts"),message:le("resetShortcutsConfirm"),danger:true,onConfirm:u,onCancel:()=>d(false)})]}):null};let iS=null;const aS=Vo()(Yo((e,t)=>(iS=()=>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:Ko(()=>Ti),partialize:e=>({keys:e.keys,currentKeyId:e.currentKeyId}),onRehydrateStorage:()=>()=>{iS?.();}})),sS=Object.freeze(Object.defineProperty({__proto__:null,useClaudeSessionKeysStore:aS},Symbol.toStringTag,{value:"Module"})),lS=({siteId:e})=>{const{keys:t,currentKeyId:n,addKey:r,deleteKey:o,setCurrentKey:i,testKey:a,setKeys:s}=aS(),[l,c]=_({}),[d,u]=_({type:"none"}),[h,g]=_(null),[p,m]=_(null),[f,b]=_(false),[y,v]=_(""),x=e===bo,w=t.find(e=>e.id===n),S=()=>u({type:"none"}),C=async(e,t)=>{try{await navigator.clipboard.writeText(t),m(e),Gi(le("claudeKeyCopied"),eo),setTimeout(()=>m(null),eo);}catch{Gi(le("claudeKeyCopyFailed"),eo);}},k=async e=>{if(!e)return void Gi(le("claudePleaseSelectKey"),eo);if(e===n)return void Gi(le("claudeAlreadyUsing"),eo);if(ti.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Gi(le("claudeRequestPermission"),no)}else {if(!(await Rd({type:Id,permissions:["cookies"]})).hasPermission)return await Rd({type:Ld,permType:"cookies"}),void Gi(le("claudeRequestPermission"),no)}const r=e?t.find(t=>t.id===e)?.key:"";await ti.setClaudeSessionKey(r||""),i(e),Gi(le("claudeKeySwitched"),to);},T=async(e,t,n,r=true)=>{if(ti.hasCapability("tabs"))try{if((await Rd({type:"CHECK_CLAUDE_GENERATING"})).isGenerating)return r&&Gi(le("claudeGenerating"),no),!1}catch{}c(t=>({...t,[e]:true}));try{const o=await ti.testClaudeSessionKey(n);return o.isValid?(a(e,{isValid:!0,accountType:o.accountType}),r&&Gi(`${t}: ${o.accountType}`,to),!0):(a(e,{isValid:!1}),r&&Gi(`${t}: ${le("claudeKeyInvalid")}`,to),!1)}catch{return a(e,{isValid:false}),r&&Gi(`${t}: ${le("claudeKeyTest")} ${le("claudeKeyInvalid")}`,to),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 Re("div",{children:[ Re(Dx,{title:le("claudeSessionKeyTitle"),description:le("claudeSessionKeyDesc"),settingId:"claude-session-keys",children:[ Re("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:[ Re("div",{style:{display:"flex",alignItems:"center",gap:"12px",flex:"1 1 auto"},children:[ qe("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:le("claudeCurrentUsing")}), qe("span",{style:{fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",gap:"8px"},children:w?Re(Ne,{children:[ Re("span",{style:{fontWeight:600},children:["🔑 ",w.name]}),w.accountType&&qe("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})]}):qe("span",{style:{color:"var(--gh-text-secondary)"},children:le("claudeNoKeySelected")})})]}), Re("div",{style:{display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap"},children:[!x&&Re("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:[ qe("span",{children:"⚠️"}), qe("span",{children:le("claudeNotOnSiteHint")})]}), qe(Sd,{content:x?"":le("claudeNotOnSiteHint"),children:qe("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?qe("option",{value:"",children:le("claudePleaseAddKey")}):t.map(e=>Re("option",{value:e.id,children:["🔑 ",e.name," ",e.accountType?`(${e.accountType})`:""]},e.id))})})]})]}), Re("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"nowrap"},children:[ Re("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")]}), qe("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,fo));}Gi(le("claudeBatchTestDone").replace("{valid}",String(e)).replace("{invalid}",String(n)),no);}catch{Gi(le("claudeBatchTestFailed"),to);}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:Re(Ne,f?{children:[ qe("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")]})}),ti.hasCapability("cookies")&&qe(Sd,{content:x?"":le("claudeNotOnSiteHint"),children:Re("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{try{if(ti.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Gi(le("claudeRequestPermission"),no)}else {if(!(await Rd({type:Id,permissions:["cookies"]})).hasPermission)return await Rd({type:Ld,permType:"cookies"}),void Gi(le("claudeRequestPermission"),no)}const e=await ti.getClaudeSessionKey();if(!e.success)return void Gi(e.error||le("claudeNoCookieFound"),to);const n=t.find(t=>t.key===e.sessionKey);if(n)return void Gi(le("claudeTokenExists").replace("{name}",n.name),to);u({type:"import-name",sessionKey:e.sessionKey});}catch(vT){Gi(le("claudeKeyCopyFailed")+": "+vT.message,no);}},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")]})}), Re("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 Gi(le("claudeInvalidJSON"),to);const o=new Set(t.map(e=>e.key)),i=r.filter(e=>!o.has(e.key));if(0===i.length)return void Gi(le("claudeNoNewTokens"),eo);s([...t,...i]),Gi(le("claudeImported").replace("{count}",String(i.length)),to);}catch(vT){Gi(le("claudeInvalidJSON")+": "+vT.message,no);}},e.click();},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["📥 ",le("claudeImportJSON")]}), Re("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{if(0===t.length)return void Gi(le("claudeNoTokensToExport"),eo);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),Gi(le("claudeExported"),eo);},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?Re("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:[ qe("div",{style:{marginBottom:"8px",fontSize:"24px"},children:"🔑"}), qe("div",{children:le("claudeNoKeys")}), qe("div",{style:{fontSize:"12px",marginTop:"4px"},children:le("claudeNoKeysHint")})]}):qe("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.map(e=>{const t=e.id===n,r=h===e.id; return Re("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:[ Re("div",{style:{display:"flex",flexDirection:"column",gap:"6px",flex:"1 1 auto",minWidth:0},children:[ Re("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ qe("span",{style:{fontWeight:600,fontSize:"15px",color:"var(--gh-text)"},children:e.name}),t&&qe("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,qe("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")}))]}), Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe(Sd,{content:le("claudeKeyDoubleTapCopy"),children:Re("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)&&qe(Sd,{content:p===e.id?le("claudeCopied"):le("claudeCopyKey"),children:qe("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?"✓":qe(Nt,{size:14})})})]})]}), Re("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[ qe("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:(o=e.isValid,void 0===o?qe("span",{style:{color:io},children:"-"}):Re("span",o?{style:{color:ro,fontWeight:500},children:["✓ ",le("claudeKeyValid")]}:{style:{color:oo,fontWeight:500},children:["✗ ",le("claudeKeyInvalid")]}))}), Re("div",{style:{display:"flex",gap:"8px"},children:[ qe(Sd,{content:le(t?"claudeAlreadyUsing":x?"claudeKeyUse":"claudeNotOnSiteHint"),children:qe("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")})}), qe("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]?qe("div",{style:{width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}):le("claudeKeyTest")}), qe("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")}), qe("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&&qe(cS,{onConfirm:(e,n)=>{e.trim()?n.trim()?mo.CLAUDE_KEY.test(n)?t.some(e=>e.key===n)?Gi(le("claudeKeyExists"),to):(r({name:e.trim(),key:n.trim()}),Gi(le("claudeKeyAdded"),eo),S()):Gi(le("claudeKeyInvalidFormat"),to):Gi(le("claudeKeyRequired"),eo):Gi(le("claudeNameRequired"),eo);},onCancel:S}),"import-name"===d.type&&qe(vb,{title:le("claudeImportNameTitle"),defaultValue:`Import-${(new Date).toLocaleDateString()}`,placeholder:le("claudeImportNamePlaceholder"),onConfirm:e=>{if(!e.trim())return void Gi(le("claudeNameRequired"),eo);const t=d,n=r({name:e.trim(),key:t.sessionKey});i(n.id),Gi(le("claudeKeyImported"),eo),S(),setTimeout(()=>E(n.id),fo);},onCancel:S}),"delete"===d.type&&qe(yb,{title:le("claudeDeleteConfirmTitle"),message:le("claudeDeleteConfirmMsg").replace("{name}",d.name),confirmText:le("claudeKeyDelete"),danger:true,onConfirm:()=>{o(d.id),Gi(le("claudeKeyDeleted"),eo),S();},onCancel:S})]})},cS=({onConfirm:e,onCancel:t})=>{const[n,r]=_(""),[o,a]=_(""),s=i.useRef(null);i.useEffect(()=>{s.current?.focus();},[]);const l=()=>{e(n,o);}; return Re(bb,{onClose:t,children:[ qe("div",{className:"gh-dialog-title",children:le("claudeAddKey")}), Re("div",{style:{display:"flex",flexDirection:"column",gap:"16px",marginBottom:"24px"},children:[ Re("div",{children:[ qe("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:le("claudeAddKeyNameTitle").split("-")[1].trim().replace("输入","")}), qe("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()})]}), Re("div",{children:[ qe("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:"Session Key"}), qe("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()})]})]}), Re("div",{className:"gh-dialog-buttons",children:[ qe("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:t,children:le("cancel")}), qe("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:l,children:le("confirm")})]})]})};const dS=({label:e,siteKey:t,settings:n,setSettings:r,placeholder:o,onDisabledClick:i,settingId:a})=>{const s=D(()=>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 Re("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:s.enabled?"default":"not-allowed"},"data-setting-id":a,children:[ qe("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:s.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:e}), qe("div",{onMouseDown:e=>{s.enabled||(e.preventDefault(),i?.());},children:qe("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"}})}), qe(mb,{checked:s.enabled,onChange:()=>{r({modelLock:{...n.modelLock,[t]:{...s,enabled:!s.enabled}}});}})]})},uS=({settings:e,setSettings:t,onDisabledClick:n,settingId:r})=>{const i="aistudio",a=e.modelLock?.[i]||{enabled:false,keyword:""},[s,l]=_(e.aistudio?.cachedModels||[]),[c,d]=_(false);L(()=>{e.aistudio?.cachedModels&&l(e.aistudio.cachedModels);},[e.aistudio?.cachedModels]); return Re("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:a.enabled?"default":"not-allowed"},"data-setting-id":r,children:[ qe("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:a.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:"AI Studio"}), qe(Sd,{content:le("aistudioRefreshModelListTooltip"),children:qe("button",{className:"icon-button",onClick:async()=>{d(true);try{const n=await async function(){if("extension"===ti.type)return Rd({type:"GET_AISTUDIO_MODELS"});if("aistudio.google.com"!==window.location.hostname)return {success:!1,error:"NO_AISTUDIO_TAB"};const{getAdapter:e}=await o(async()=>{const{getAdapter:e}=await Promise.resolve().then(()=>Jm);return {getAdapter:e}},void 0),t=e();return function(e){if(!e||"object"!=typeof e)return !1;const t=e;return "function"==typeof t.getSiteId&&"function"==typeof t.getModelList}(t)&&t.getSiteId()===Co?{success:!0,models:await t.getModelList()}:{success:!1,error:"NOT_AISTUDIO"}}();if(n.success&&n.models)l(n.models),t({aistudio:{...e.aistudio,cachedModels:n.models}}),Gi(le("aistudioModelsFetched"),2e3);else {Gi("NO_AISTUDIO_TAB"===n.error?le("aistudioNoTabError"):le("aistudioModelsError"),3e3);}}catch(n){Gi(le("aistudioModelsError"),3e3),console.error("Refresh model list failed:",n);}finally{d(false);}},disabled:c,style:{padding:"4px",opacity:c?.5:1,cursor:c?"not-allowed":"pointer",background:"transparent",border:"none",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center"},children:qe(He,{size:16})})}), qe("div",{onMouseDown:e=>{a.enabled||(e.preventDefault(),n?.());},children:Re("select",{className:"settings-select",value:a.keyword||"",onChange:n=>{return r=n.target.value,void t({modelLock:{...e.modelLock,[i]:{...a,keyword:r}}});var r;},disabled:!a.enabled||0===s.length,style:{width:"200px",opacity:a.enabled?1:.5,pointerEvents:a.enabled?"auto":"none"},children:[0===s.length&&qe("option",{value:"",children:le("aistudioRefreshModelListFirst")}),s.map(e=>qe("option",{value:e.id,children:e.name},e.id))]})}), qe(mb,{checked:a.enabled,onChange:()=>{t({modelLock:{...e.modelLock,[i]:{...a,enabled:!a.enabled}}});}})]})},hS=({siteId:e,initialTab:t})=>{const[n,r]=_(t||Or);L(()=>{t&&r(t);},[t]);const{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l}=zi(),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,po.PAGE_WIDTH.DEFAULT_PERCENT),v=b(m?.value,po.USER_QUERY_WIDTH.DEFAULT_PERCENT),x=(t,n)=>{if(!o)return;const r="pageWidth"===t?po.PAGE_WIDTH:po.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:Or,label:le("tabLayout")},{id:zr,label:le("tabModelLock")},{id:yo,label:le("tabGemini")},{id:Co,label:"AI Studio"},{id:vo,label:"ChatGPT"},{id:bo,label:"Claude"}]; return Re("div",{children:[ qe(Ox,{title:le("navSiteSettings"),Icon:ct}), qe("p",{className:"settings-page-desc",children:le("siteSettingsPageDesc")}), qe(_x,{tabs:C,activeTab:n,onTabChange:r}),n===Or&&Re(Ne,{children:[ Re(Dx,{title:le("layoutSettingsTitle"),children:[ qe($x,{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}}}});}}), qe(Bx,{label:le("pageWidthValueLabel"),settingId:"layout-page-width-value",disabled:!p?.enabled,onDisabledClick:()=>d(u),children:qe(Cb,{value:y,onChange:e=>S("pageWidth",e),onPreviewChange:e=>w("pageWidth",e),onCancelPreview:s,min:po.PAGE_WIDTH.MIN_PERCENT,max:po.PAGE_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(po.PAGE_WIDTH.DEFAULT_PERCENT,10),disabled:!p?.enabled,formatValue:e=>`${e}%`,ariaLabel:le("pageWidthValueLabel")})})]}), Re(Dx,{title:le("userQueryWidthSettings"),children:[ qe($x,{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}}}});}}), qe(Bx,{label:le("userQueryWidthValueLabel"),settingId:"layout-user-query-width-value",disabled:!m?.enabled,onDisabledClick:()=>d(h),children:qe(Cb,{value:v,onChange:e=>S("userQueryWidth",e),onPreviewChange:e=>w("userQueryWidth",e),onCancelPreview:s,min:po.USER_QUERY_WIDTH.MIN_PERCENT,max:po.USER_QUERY_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(po.USER_QUERY_WIDTH.DEFAULT_PERCENT,10),disabled:!m?.enabled,formatValue:e=>`${e}%`,ariaLabel:le("userQueryWidthValueLabel")})})]}), Re(Dx,{title:le("zenModeTitle"),children:[ qe($x,{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});}}), qe($x,{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)}}}});}})]}), qe(Dx,{title:le("cleanModeTitle"),children:qe($x,{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===zr&&Re(Dx,{title:le("modelLockTitle"),description:le("modelLockDesc"),children:[ qe(dS,{label:"Gemini",siteKey:"gemini",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini"}), qe(dS,{label:"Gemini Enterprise",siteKey:"gemini-enterprise",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini-enterprise"}), qe(uS,{settings:o,setSettings:i,onDisabledClick:()=>d(g),settingId:"model-lock-aistudio"}), qe(dS,{label:"ChatGPT",siteKey:"chatgpt",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-chatgpt"}), qe(dS,{label:"Claude",siteKey:"claude",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-claude"}), qe(dS,{label:"Grok",siteKey:"grok",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-grok"}), qe(dS,{label:"Kimi",siteKey:"kimi",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-kimi"}), qe(dS,{label:"Qianwen",siteKey:"qianwen",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qianwen"}), qe(dS,{label:"Qwen Studio",siteKey:"qwenai",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qwenai"}), qe(dS,{label:"Yuanbao",siteKey:"yuanbao",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-yuanbao"}), qe(dS,{label:"ima",siteKey:"ima",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-ima"}), qe(dS,{label:"Z.ai",siteKey:"zai",settings:o,setSettings:i,placeholder:le("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-zai"})]}),"gemini"===n&&Re(Dx,{title:le("geminiSettingsTab"),description:le("contentProcessingDesc"),children:[ qe($x,{label:le("markdownFixLabel"),description:le("markdownFixDesc"),settingId:"gemini-markdown-fix",checked:o.content?.markdownFix??false,onChange:()=>l("content","markdownFix",!o.content?.markdownFix)}), qe($x,{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(!ti.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 Rd({type:Id,origins:[""]});e.success&&e.hasPermission?l("content","watermarkRemoval",true):(await Rd({type:Ld,permType:"allUrls"}),Gi(le("permissionRequestToast"),3e3));}}}}), Re("div",{className:"setting-subsection",style:{marginTop:"24px",paddingTop:"16px",borderTop:"1px solid var(--gh-border-color)"},children:[ qe("h3",{style:{fontSize:"14px",fontWeight:600,marginBottom:"12px"},children:"Gemini Enterprise"}), qe($x,{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&&qe(Bx,{label:le("maxRetriesLabel"),settingId:"gemini-policy-max-retries",children:Re("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ qe(wb,{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"}}), qe("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:le("retryCountSuffix")})]})})]})]}),n===Co&&Re(Dx,{title:le("aistudioSettingsTitle"),description:le("aistudioSettingsDesc"),children:[ qe($x,{label:le("aistudioCollapseNavbar"),description:le("aistudioCollapseNavbarDesc"),settingId:"aistudio-collapse-navbar",checked:o.aistudio?.collapseNavbar??false,onChange:()=>i({aistudio:{...o.aistudio,collapseNavbar:!o.aistudio?.collapseNavbar}})}), qe($x,{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}})}), qe($x,{label:le("aistudioCollapseTools"),description:le("aistudioCollapseToolsDesc"),settingId:"aistudio-collapse-tools",checked:o.aistudio?.collapseTools??false,onChange:()=>i({aistudio:{...o.aistudio,collapseTools:!o.aistudio?.collapseTools}})}), qe($x,{label:le("aistudioCollapseAdvanced"),description:le("aistudioCollapseAdvancedDesc"),settingId:"aistudio-collapse-advanced",checked:o.aistudio?.collapseAdvanced??false,onChange:()=>i({aistudio:{...o.aistudio,collapseAdvanced:!o.aistudio?.collapseAdvanced}})}), qe($x,{label:le("aistudioEnableSearch"),description:le("aistudioEnableSearchDesc"),settingId:"aistudio-enable-search",checked:o.aistudio?.enableSearch??true,onChange:()=>i({aistudio:{...o.aistudio,enableSearch:!o.aistudio?.enableSearch}})}), qe($x,{label:le("aistudioRemoveWatermark"),description:le("aistudioRemoveWatermarkDesc"),settingId:"aistudio-remove-watermark",checked:o.aistudio?.removeWatermark??false,onChange:()=>{i({aistudio:{...o.aistudio,removeWatermark:!o.aistudio?.removeWatermark}}),Gi(le("aistudioReloadHint"),3e3);}}), qe($x,{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&&qe(lS,{siteId:e}),n===vo&&qe(Dx,{title:le("chatgptSettingsTitle"),description:le("chatgptSettingsDesc"),children:qe($x,{label:le("chatgptMarkdownFixLabel"),description:le("chatgptMarkdownFixDesc"),settingId:"chatgpt-markdown-fix",checked:o.chatgpt?.markdownFix??false,onChange:()=>i({chatgpt:{...o.chatgpt,markdownFix:!o.chatgpt?.markdownFix}})})})]})},gS=(e,t)=>{const n=le(e);return n===e?t:n},pS=[{id:xr,Icon:st,labelKey:"navGeneral",label:"基本设置"},{id:wr,Icon:lt,labelKey:"navAppearance",label:"外观主题"},{id:Sr,Icon:dt,labelKey:"navFeatures",label:"功能模块"},{id:Cr,Icon:ct,labelKey:"navSiteSettings",label:"站点配置"},{id:kr,Icon:Yt,labelKey:"navGlobalSearch",label:"全局搜索"},{id:Tr,Icon:Lt,labelKey:"navShortcuts",label:"快捷键位"},{id:Er,Icon:({size:e=20,color:t="currentColor",className:n="",style:r})=>qe("svg",{viewBox:"0 0 1027 1024",width:e,height:e,className:n,style:{display:"block",...r},children:qe("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:Ar,Icon:ut,labelKey:"navPermissions",label:"权限管理"},{id:Mr,Icon:ht,labelKey:"navAbout",label:"关于"}],mS=({isOpen:e,onClose:t,siteId:n,onOpenReleaseNotes:r})=>{const[o,i]=_(xr),[a,s]=_(void 0),[l,c]=_(null),[d,u]=_(false),{settings:h}=zi(),g=Fi(),p=$(null),m=$(null),f=$(void 0),b=$(null);if(L(()=>{g&&h?.language&&ae(h.language);},[g,h?.language]),L(()=>{p.current&&(p.current.scrollTop=0);},[o]),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=Wr(e.settingId),n=jr(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&&pS.some(e=>e.id===t.page)&&i(t.page),s(t.subTab),t.settingId?c({settingId:t.settingId,token:Date.now()}):c(null);};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[]),L(()=>{if(!e||!l?.settingId)return;let t,n,r=false;const o=`[data-setting-id="${"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(l.settingId):JSON.stringify(l.settingId).slice(1,-1)}"]`,i=e=>{if(r)return;const n=p.current?.querySelector(o);return n?(void 0!==f.current&&(window.clearTimeout(f.current),f.current=void 0),b.current&&b.current!==n&&b.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"),b.current=n,f.current=window.setTimeout(()=>{n.classList.remove("setting-locate-highlight"),b.current===n&&(b.current=null),f.current=void 0;},2200),void c(null)):e>=12?(console.warn(`[Ophel] Failed to locate setting: ${l.settingId}`),void c(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,o,a,l]),L(()=>()=>{ void 0!==f.current&&window.clearTimeout(f.current),b.current&&(b.current.classList.remove("setting-locate-highlight"),b.current=null);},[]),L(()=>{if(e){const e=m.current;if(!e)return;return vs(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 qe("div",{className:"settings-modal-overlay",...ms,onClick:t,children:Re("div",{ref:m,className:"settings-modal-container "+(d?"maximized":""),onClick:e=>e.stopPropagation(),children:[ Re("div",{className:"settings-modal-actions",children:[ qe(Sd,{content:le(d?"restore":"maximize"),children:qe("button",{className:"settings-modal-action-btn",onClick:()=>u(!d),children:qe(d?At:Et,{size:16})})}), qe(Sd,{content:le("close"),children:qe("button",{className:"settings-modal-action-btn close",onClick:t,children:qe($e,{size:16})})})]}), Re("aside",{className:"settings-sidebar",children:[ qe("div",{className:"settings-sidebar-header",children:Re("div",{className:"settings-sidebar-logo",children:[ qe("img",{src:iv,alt:rv}), qe("span",{children:rv})]})}), Re("nav",{className:"settings-sidebar-nav",children:[pS.filter(e=>!(!ti.hasCapability("permissions")&&e.id===Ar)).map(e=>Re("button",{className:"settings-nav-item "+(o===e.id?"active":""),onClick:()=>{i(e.id),s(void 0),c(null);},children:[ qe("span",{className:"settings-nav-item-icon",children:qe(e.Icon,{size:22})}), qe("span",{children:gS(e.labelKey,e.label)})]},e.id)), qe(Ix,{})]}), qe(qx,{siteId:n})]}), qe("main",{className:"settings-content",ref:p,children:(()=>{if(!h||!g) return qe("div",{style:{padding:40,textAlign:"center"},children:le("loading")});switch(o){case xr: return qe(Xw,{siteId:n,initialTab:a});case Cr: return qe(hS,{siteId:n,initialTab:a});case wr: return qe(sw,{siteId:n,initialTab:a});case Sr: return qe(Vw,{siteId:n,initialTab:a});case kr: return qe(Zw,{siteId:n});case Tr: return qe(oS,{siteId:n});case Ar: return qe(nS,{siteId:n});case Er: return qe(Mw,{siteId:n,onNavigate:i});case Mr: return qe(zx,{onOpenReleaseNotes:r});default: return qe(Xw,{siteId:n,initialTab:a})}})()})]})})},fS=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:q,activeSyntaxSuggestionIndex:R,onHoverSyntaxSuggestion:P,onApplySyntaxSuggestion:D,syntaxDiagnostics:B,resolveSyntaxDiagnosticTitle:$,showShortcutNudge:_,shortcutNudgeMessage:O,closeLabel:z,dismissShortcutNudgeLabel:F,onHideShortcutNudge:U,onDismissShortcutNudgeForever:H,categoriesLabel:W,categories:j,activeCategoryId:G,onSelectCategory:Q,activeContext:V,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?vs(e):void 0},[t]),t?Re("div",{className:"settings-search-overlay gh-interactive",onClick:n,children:[ Re("div",{ref:pe,className:"settings-search-modal",onClick:e=>e.stopPropagation(),children:[ Re("div",{className:"settings-search-input-wrap",children:[ qe(Yt,{size:16}), qe("button",{type:"button",className:"settings-search-fuzzy-toggle "+(g?"active":""),"aria-pressed":g,"aria-label":h,onClick:p,children:u}), qe("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}), Re("span",{className:"settings-search-hotkey",children:["⌨ ",d]}), Re("div",{className:"settings-search-help",children:[ qe("button",{ref:m,type:"button",className:"settings-search-help-trigger "+(b?"active":""),"aria-expanded":b,"aria-label":v,onClick:y,children:"?"}),b?Re("div",{ref:f,className:"settings-search-help-popover",role:"dialog","aria-label":x,children:[ qe("div",{className:"settings-search-help-title",children:x}), qe("div",{className:"settings-search-help-tip",children:w}), qe("div",{className:"settings-search-help-items",children:S.map(e=>Re("button",{type:"button",className:"settings-search-help-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),C(e);},children:[ qe("span",{className:"settings-search-help-token",children:e.token}), qe("span",{className:"settings-search-help-desc",children:e.description})]},e.id))})]}):null]})]}),k.length>0?Re("div",{className:"settings-search-filter-chips","aria-label":"active search filters",children:[k.map(e=>Re("button",{type:"button",className:"settings-search-filter-chip",onClick:()=>I(e.id),title:A,children:[ qe("span",{className:"settings-search-filter-chip-label",children:e.label}), qe("span",{className:"settings-search-filter-chip-close","aria-hidden":true,children:"×"})]},e.id)),T?qe("span",{className:"settings-search-filter-chip-overflow",children:E}):null, qe("button",{type:"button",className:"settings-search-filter-chip-clear-all",onClick:L,children:M})]}):null,N?qe("div",{className:"settings-search-syntax-suggestions",role:"listbox",children:q.map((e,t)=>Re("button",{type:"button",role:"option","aria-selected":R===t,className:"settings-search-syntax-suggestion "+(R===t?"active":""),onMouseEnter:()=>P(t),onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),D(e);},children:[ qe("span",{className:"settings-search-syntax-suggestion-token",children:e.label}), qe("span",{className:"settings-search-syntax-suggestion-desc",children:e.description})]},e.id))}):null,B.length>0?qe("div",{className:"settings-search-syntax-diagnostics",role:"status","aria-live":"polite",children:B.map(e=>Re("div",{className:"settings-search-syntax-diagnostic",children:[ qe("span",{className:"settings-search-syntax-diagnostic-title",children:$(e.code)}), Re("span",{className:"settings-search-syntax-diagnostic-detail",children:[e.operator,e.value?`:${e.value}`:"",e.suggestion?` → ${e.suggestion}:`:""]})]},e.id))}):null,_&&O?Re("div",{className:"settings-search-shortcut-nudge",role:"status","aria-live":"polite",children:[ qe("span",{className:"settings-search-shortcut-nudge-text",children:O}), qe("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:U,children:z}), qe("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:H,children:F})]}):null,j.length>0?qe("div",{className:"settings-search-categories",role:"tablist","aria-label":W,children:j.map(e=>Re("button",{type:"button",role:"tab","aria-selected":G===e.id,className:"settings-search-category "+(G===e.id?"active":""),onClick:()=>Q(e.id),children:[ qe("span",{children:e.label}), qe("span",{className:"settings-search-category-count",children:null==e.count?"-":e.count})]},e.id))}):null,V?Re("div",{className:"settings-search-context-bar",children:[ qe("span",{className:"settings-search-context-label",children:V.label}), qe("span",{className:"settings-search-context-meta",children:V.meta})]}):null, qe("div",{id:K,className:"settings-search-results",role:"listbox","aria-label":Z,ref:o,onWheel:Y,children:0===X.length?Re("div",{className:"settings-search-empty",children:[ qe("div",{children:re}), qe("div",{className:"settings-search-empty-guide-title",children:oe}), qe("div",{className:"settings-search-empty-guide-desc",children:ie}), qe("div",{className:"settings-search-empty-guide-examples",children:ae.map(e=>qe("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=>Re("section",{className:"settings-search-group",children:[ Re("div",{className:"settings-search-group-title",children:[ qe("span",{children:ee(e.category)}),e.totalCount>te?Re("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?qe("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))}), qe("div",{className:"settings-search-footer",children:he})]}),ge]}):null},bS=new Map,yS=(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)},vS=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=bS.get(r);if(o)return o;const i=yS(e,t,n);if(bS.size>=500){const e=bS.keys().next().value;void 0!==e&&bS.delete(e);}return bS.set(r,i),i})(e,o,n);return r.map((e,n)=>{if("none"===e.matchType) return qe(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 qe("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 Re("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:[ qe("div",{className:"settings-search-item-title",title:e.title,children:f?Re("div",{className:"gs-tip-item-head",children:[ qe("span",{className:"gs-tip-icon","aria-hidden":"true",children:"💡"}), qe("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})]}):g?Re("div",{className:"settings-search-outline-head",children:[ qe("span",{className:"settings-search-outline-role "+(b?"query":"reply"),title:y,children:y}),e.code?qe("span",{className:"settings-search-outline-code",title:e.code,children:h(e.code,"code",k)}):null, qe("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})]}):qe("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})}),e.snippet?Re("div",{className:"settings-search-item-snippet",title:`${T}${e.snippet}`,children:[T?qe("span",{className:"settings-search-item-snippet-prefix",children:T}):null,h(e.snippet,"default",C)]}):null, Re("div",{className:("settings-search-item-meta "+(v?"":"no-code")).trim(),children:[ Re("div",{className:"settings-search-item-meta-left",children:[ qe("span",{className:"settings-search-item-breadcrumb",title:e.breadcrumb,children:h(e.breadcrumb,"default",S)}),"conversations"===e.category&&e.tagBadges&&e.tagBadges.length>0?qe("div",{className:"settings-search-tag-list",children:e.tagBadges.map(e=>qe("span",{className:"settings-search-tag",style:{backgroundColor:e.color},title:e.name,children:h(e.name,"tag")},e.id))}):null,E.length>0?qe("div",{className:"settings-search-match-reason-list",children:E.map(e=>qe("span",{className:"settings-search-match-reason-badge",children:e.label},e.reason))}):null]}),v?qe("code",{title:e.code,children:h(e.code,"code",k)}):null]})]})}),xS=["type","folder","tag","is","level","date"],wS=["outline","conversations","prompts","settings"],SS=["pinned","unpinned"],CS=["0","1","2","3","4","5","6"],kS=["7d","30d"],TS=e=>e.trim().toLowerCase(),ES=e=>TS(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0),AS=e=>e?e.replace(/^"|"$/g,"").replace(/\\([\\"\s:])/g,"$1").trim():"",MS=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},IS=(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)},LS=(e,t)=>!!t&&("type"===e?wS.includes(t):"is"===e?SS.includes(t):"level"===e?CS.includes(t):"date"!==e||null!==MS(t)),NS=e=>"type"===e?"outline | conversations | prompts | settings":"is"===e?"pinned | unpinned":"level"===e?"0 ~ 6":"date"===e?"Nd (e.g. 7d, 30d)":void 0,qS=(e,t,n)=>`${e}:${t}:${n}`,RS=e=>{const t=e.trim().toLowerCase();if(!t)return null;const n=xS.find(e=>e.startsWith(t));if(n)return n;const r=xS.find(e=>t.startsWith(e));return r||null},PS=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}},DS=globalThis.fuzzysort,BS=DS&&"function"==typeof DS.single?DS:{single:()=>null,go:()=>[],prepare:e=>e,cleanup:()=>{}},$S=[{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"}],_S=["outline","conversations","prompts","settings","tips"],OS=Object.entries(Hr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),zS=({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);c>=o.length&&(l=Math.max(0,o.length-r));return `${l>0?"…":""}${o.slice(l,c).trim()}${c{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},US=e=>e?e.split(/[^a-z0-9\u4e00-\u9fff]+/gi).map(e=>e.trim()).filter(e=>e.length>0):[],HS=(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]},WS=({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?(({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=BS.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=>{t.value&&US(t.value).forEach(o=>{if(Math.abs(o.length-e.length)>r)return;const i=HS(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))})({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},jS=(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},GS=e=>{const t=e.fields.map(e=>e.value).filter(Boolean).join(" "),n=US(t);return {...e,searchableText:t,fuzzyWords:n,fuzzyAcronym:(r=n,r.map(e=>e[0]||"").join("").trim())};var r;},QS=(e,t)=>{if(!e||e.length>t.length)return false;let n=0;for(let r=0;r{const{normalizedQuery:n,tokens:r}=t;return n?e.searchableText===n?5:e.searchableText.startsWith(n)?4:e.searchableText.includes(n)||e.fuzzyAcronym===n||e.fuzzyAcronym.startsWith(n)?3:e.fuzzyAcronym.includes(n)||r.some(t=>e.searchableText.startsWith(t))?2:r.some(t=>e.searchableText.includes(t))?1:n.length>=2&&e.fuzzyAcronym&&QS(n,e.fuzzyAcronym)||((e,t)=>{if(t.length<4)return false;const n=t.length>=8?2:1;return e.fuzzyWords.some(e=>!(Math.abs(e.length-t.length)>n)&&HS(t,e,n)<=n)})(e,n)?2:n.length>=3&&QS(n,e.searchableText)?0:-1:-1},KS=(e,t)=>t?{...e,score:e.score+t}:e,ZS=(e,t)=>{const n=[],r=[];return e.forEach(e=>{const o=WS({normalizedQuery:t.normalizedQuery,tokens:t.tokens,index:e.index,enableFuzzySearch:false,fields:e.fields});if(o){const r=KS(o,e.scoreBoost);return void n.push({item:e.createItem(r,t),scoreMeta:r,index:e.index,recency:e.recency})}t.enableFuzzySearch&&t.normalizedQuery&&r.push(e);}),t.enableFuzzySearch&&t.normalizedQuery&&((e,t,n)=>{if(t<=800)return e;const r=e.map(e=>({entry:e,rank:VS(e,n)})).filter(({rank:e})=>e>=0).sort((e,t)=>t.rank!==e.rank?t.rank-e.rank:e.entry.index-t.entry.index).slice(0,300).map(({entry:e})=>e);return r.length>0?r:e.slice(0,300)})(r,e.length,t).forEach(e=>{const r=WS({normalizedQuery:t.normalizedQuery,tokens:t.tokens,index:e.index,enableFuzzySearch:true,fields:e.fields});if(!r)return;const o=KS(r,e.scoreBoost);n.push({item:e.createItem(o,t),scoreMeta:o,index:e.index,recency:e.recency});}),n.sort(jS).map(({item:e})=>e)},YS=({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=D(()=>{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 $S.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)))},[g,x,m,p,v]),S=D(()=>({normalizedQuery:TS(e),tokens:ES(e),enableFuzzySearch:t}),[e,t]),C=D(()=>x?[]:r.map((e,t)=>{const n=o(e),r=i(e.settingId),a=[{value:TS(n),exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:TS((e.keywords||[]).join(" ")),exact:0,prefix:0,includes:68,tokenPrefix:0,tokenIncludes:8,matchReason:"keyword"},{value:TS(e.settingId),exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"id",highlightField:"code"},{value:TS((OS[e.settingId]||[]).join(" ")),exact:0,prefix:0,includes:44,tokenPrefix:0,tokenIncludes:6,matchReason:"alias"}];return GS({index:t,fields:a,createItem:t=>({id:`settings:${e.settingId}`,title:n,breadcrumb:r,code:e.settingId,category:"settings",settingId:e.settingId,matchReasons:t.matchReasons,fuzzyMatch:t.fuzzyMatch})})}),[i,x,o,r]),k=D(()=>x?[]:ZS(C,S),[S,x,C]),T=D(()=>{if(x||!a)return [];const e=a.getConversations(),t=a.getFolders(),n=a.getTags(),r=new Map(t.map(e=>[e.id,e])),o=new Map(n.map(e=>[e.id,e])),i=g({key:"untitledConversation",fallback:"Untitled conversation"});return e.map((e,t)=>{const n=e.title?.trim()||i,a=r.get(e.folderId),s=a?`${a.icon?`${a.icon} `:""}${FS(a)}`.trim():e.folderId,l=(e.tagIds||[]).map(e=>{const t=o.get(e);return t?{id:t.id,name:t.name,color:t.color}:null}).filter(e=>Boolean(e)),c=[{value:TS(n),exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:TS(s),exact:0,prefix:0,includes:72,tokenPrefix:0,tokenIncludes:8,matchReason:"folder",highlightField:"breadcrumb"},{value:TS(l.map(e=>e.name).join(" ")),exact:0,prefix:0,includes:64,tokenPrefix:0,tokenIncludes:8,matchReason:"tag"}];return GS({index:t,fields:c,recency:e.updatedAt||0,scoreBoost:e.pinned?6:0,createItem:t=>({id:`conversations:${e.id}`,title:n,breadcrumb:s,category:"conversations",conversationId:e.id,conversationUrl:e.url,tagBadges:l,folderName:s,tagNames:l.map(e=>e.name),isPinned:Boolean(e.pinned),searchTimestamp:e.updatedAt||0,matchReasons:t.matchReasons,fuzzyMatch:t.fuzzyMatch})})})},[a,s,l,c,g,x]),E=D(()=>x?[]:ZS(T,S),[T,S,x]),A=D(()=>{if(x)return [];const e=g({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),t=g({key:"uncategorized",fallback:"Uncategorized"});return d.map((n,r)=>{const o=n.title?.trim()||n.content?.trim().split("\n")[0]||`${e} #${r+1}`,i=n.content?.trim()||"",a=n.category?.trim()||t,s=`${e} / ${a}`,l=[{value:TS(o),exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:TS(a),exact:0,prefix:0,includes:70,tokenPrefix:0,tokenIncludes:8,matchReason:"category",highlightField:"breadcrumb"},{value:TS(i),exact:0,prefix:0,includes:60,tokenPrefix:0,tokenIncludes:6,matchReason:"content",highlightField:"snippet"},{value:TS(n.id),exact:0,prefix:0,includes:20,tokenPrefix:0,tokenIncludes:4,matchReason:"id",highlightField:"code"}];return GS({index:r,fields:l,recency:n.lastUsedAt||0,scoreBoost:n.pinned?6:0,createItem:(e,t)=>({id:`prompts:${n.id}`,title:o,breadcrumb:s,snippet:e.matchReasons.includes("content")?zS({content:i,normalizedQuery:t.normalizedQuery,tokens:t.tokens}):"",category:"prompts",promptId:n.id,promptContent:n.content,folderName:a,isPinned:Boolean(n.pinned),searchTimestamp:n.lastUsedAt||0,matchReasons:e.matchReasons,fuzzyMatch:e.fuzzyMatch})})})},[g,x,d]),M=D(()=>x?[]:ZS(A,S),[S,x,A]),I=D(()=>{if(x||!u)return [];const e=(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()),t=g({key:"globalSearchCategoryOutline",fallback:"Outline"}),n=g({key:"outlineUserQueryRoleLabel",fallback:"User queries"}),r=g({key:"globalSearchOutlineReplies",fallback:"Replies"});return e.map((e,o)=>{const i=e.text?.trim();if(!i)return null;const a=e.isUserQuery?`Q${e.queryIndex??o+1}`:`H${e.level}`,s=e.isUserQuery?n:r,l=e.isUserQuery?`${t} / ${s}`:`${t} / ${s} / H${e.level}`,c=[{value:TS(i),exact:200,prefix:120,includes:90,tokenPrefix:16,tokenIncludes:10,matchReason:"title",highlightField:"title"},{value:TS(e.isUserQuery?s:`${s} h${e.level}`),exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"type",highlightField:"breadcrumb"},{value:TS(a),exact:0,prefix:0,includes:36,tokenPrefix:0,tokenIncludes:4,matchReason:"code",highlightField:"code"}];return GS({index:o,fields:c,scoreBoost:e.isBookmarked?4:0,createItem:t=>({id:`outline:${e.index}`,title:i,breadcrumb:l,code:a,category:"outline",matchReasons:t.matchReasons,fuzzyMatch:t.fuzzyMatch,outlineTarget:{index:e.index,level:e.level,text:i,isUserQuery:Boolean(e.isUserQuery),id:e.id,navigationId:e.navigationId,queryIndex:e.queryIndex,isGhost:Boolean(e.isGhost),scrollTop:e.scrollTop}})})}).filter(e=>Boolean(e))},[g,x,u,h]),L=D(()=>x?[]:ZS(I,S),[S,x,I]),N=D(()=>[...w,...k,...E,...L,...M],[w,E,L,M,k]),q=D(()=>N.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=MS(n);if(null===t)return false;const r=e.searchTimestamp||0;return !(r<=0)&&Date.now()-r<=864e5*t}return true}))(e,n)),[n,N]),R=D(()=>{const e={all:0,outline:0,conversations:0,prompts:0,settings:0,tips:0};return q.forEach(t=>{e[t.category]+=1,e.all+=1;}),e},[q]),P=D(()=>"all"!==f?[]:_S.map(e=>{const t=q.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,q]),B=D(()=>"all"!==f?q.filter(e=>e.category===f):P.flatMap(e=>e.items),[f,q,P]);return {filteredGlobalSearchResults:q,globalSearchResultCounts:R,groupedGlobalSearchResults:P,visibleGlobalSearchResults:B}},XS={"loading-history":"exportOverlayLoadingHistory",preparing:"exportOverlayPreparing",extracting:"exportOverlayExtracting",packaging:"exportOverlayPackaging",downloading:"exportOverlayDownloading",copying:"exportOverlayCopying",restoring:"exportOverlayRestoring"},JS={"loading-history":"outlineCopyOverlayLoadingHistory",preparing:"outlineCopyOverlayPreparing",extracting:"outlineCopyOverlayExtracting",packaging:"exportOverlayPackaging",downloading:"exportOverlayDownloading",copying:"outlineCopyOverlayCopying",restoring:"outlineCopyOverlayRestoring"},eC={[xr]:{key:"navGeneral",fallback:"General"},[Sr]:{key:"navFeatures",fallback:"Features"},[Cr]:{key:"navSiteSettings",fallback:"Site Config"},[kr]:{key:"navGlobalSearch",fallback:"Global Search"},[wr]:{key:"navAppearance",fallback:"Appearance"},[Tr]:{key:"navShortcuts",fallback:"Keyboard Shortcuts"},[Er]:{key:"navBackup",fallback:"Data Management"},[Ar]:{key:"navPermissions",fallback:"Permissions"},[Mr]:{key:"navAbout",fallback:"About"}},tC={panel:{key:"panelTab",fallback:"Panel"},tabOrder:{key:"tabOrderTab",fallback:"Tab Order"},shortcuts:{key:"shortcutsTab",fallback:"Quick Buttons"},toolsMenu:{key:"toolboxMenu",fallback:"Toolbox"},[qr]:{key:"tabSettingsTab",fallback:"Tab Settings"},[Rr]:{key:"reminderTab",fallback:"Alerts"},[Ir]:{key:"outlineSettingsTitle",fallback:"Outline"},[Lr]:{key:"conversationsSettingsTitle",fallback:"Conversations"},[Nr]:{key:"promptSettingsTitle",fallback:"Prompts"},[Dr]:{key:"readingHistorySettings",fallback:"Reading History"},[Pr]:{key:"contentProcessing",fallback:"Content"},[Br]:{key:"toolboxMenu",fallback:"Toolbox"},[Or]:{key:"layoutTab",fallback:"Layout"},[zr]:{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"},[$r]:{key:"themePresetsTab",fallback:"Theme Presets"},[_r]:{key:"customStylesTab",fallback:"Custom Styles"}},nC=new Set(["Meta","OS","Command","Cmd"]),rC=new Set(["Control","Ctrl"]),oC=[{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"}}],iC={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"}},aC={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"}},sC="settings-search-option",lC="ophel:global-search-shortcut-nudge:v1",cC={"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","prompt-quick-quote-enabled":"quickQuoteEnabledLabel","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"},dC={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"}},uC=e=>e.replace(/[-_]/g," ").replace(/\s+/g," ").trim().replace(/\b([a-z])/g,(e,t)=>t.toUpperCase()),hC=Object.freeze(Object.defineProperty({__proto__:null,App:()=>{const{settings:e,setSettings:t,updateDeepSetting:n,updateNestedSetting:r}=zi(),o=Fi(),i=e?.features?.prompts?.submitShortcut??"enter";zi(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=D(()=>(()=>{if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"";return e.includes("mac")||t.includes("mac os")})(),[]),u=D(()=>gr(e?.shortcuts)||gi.shortcuts,[e?.shortcuts]),h=D(()=>{if(!u.enabled)return null;const e=u.keybindings[Kn];return null===e?null:e||sr[Kn]},[u]),g=h?pr(h,d):"",p=e?.globalSearch?.doubleShift??gi.globalSearch.doubleShift,m=D(()=>{const e=[];return g&&e.push(g),p&&e.push("double shift"),e.join(" / ")},[g,p]),f=d?"⌘":"Ctrl",b=E(e=>{if(e===Kn)return m||null;if(!u.enabled)return null;const t=u.keybindings[e];if(null===t)return null;const n=t||sr[e];return n?pr(n,d):null},[m,d,u]),y=m||le("shortcutNotSet"),v=e?.globalSearch?.enableFuzzySearch??gi.globalSearch.enableFuzzySearch,x=D(()=>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(lC);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(lC,JSON.stringify(e));}catch{}},[]),C=E(()=>{tt.current&&(clearTimeout(tt.current),tt.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(()=>{Ed(t,{size:14});}).catch(()=>{Gi(l({key:"copyFailed",fallback:"Copy failed"}));}):Gi(l({key:"copyFailed",fallback:"Copy failed"})));},[l]),T=E(()=>{Je.current&&(clearTimeout(Je.current),Je.current=null);},[]),A=E(e=>{T(),Se(e),ke(e);},[T]),M=E(e=>{const t=e.trimStart();A(e),xe(e=>t.startsWith("tip:")?"tips"===e?e:"tips":"tips"===e?"all":e);},[A]),I=E(()=>{t({globalSearch:{...gi.globalSearch,...e?.globalSearch||{},enableFuzzySearch:!v}});},[v,t,e?.globalSearch]),N=E(e=>{Se(e),T(),Je.current=setTimeout(()=>{ke(e),Je.current=null;},140);},[T]),q=E(()=>{C(),$e(false),Oe("");},[C]),R=E(()=>{const e=w();S({...e,dismissed:true}),q();},[w,q,S]),P=E(()=>{const e=w(),t=e.shortcutUsedCount+1;S({...e,shortcutUsedCount:t,dismissed:e.dismissed||t>=2}),q();},[w,q,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}),Oe(x),$e(true),C(),tt.current=setTimeout(()=>{$e(false),Oe(""),tt.current=null;},6e3));},[C,w,x,S]),z=E(e=>{const t=eC[e];return t?l(t):e},[l]),F=E(e=>{const t=tC[e];return t?l(t):e},[l]),U=E(e=>{const t=cC[e.settingId];if(t)return l({key:t,fallback:uC(e.settingId)});if(e.settingId.startsWith("model-lock-")){const t=e.settingId.slice(11),n=dC[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=ir[t];if(n){return `${l({key:"navShortcuts",fallback:"Keyboard Shortcuts"})}: ${l({key:n.labelKey,fallback:n.label})}`}}return uC(e.settingId)},[l]),H=E(e=>{const t=jr(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=D(()=>Xm(),[]),j=D(()=>W?new db(W):null,[W]),G=D(()=>W&&j?new pb(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 Q=D(()=>W?new jf(W):null,[W]),[V,K]=_(null);L(()=>{if(Q)return K(null),Q.onExportProgress(K);K(null);},[Q]);const Z=D(()=>{if(!W)return null;return new eb(W,e?.features?.outline??gi.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&&!Ot.current){Ot.current=true;const t=e.panel?.panelMode??"edge-snap",n=e.panel?.defaultPosition??"right";ee(e.panel?.panelExpanded??true),Bt("edge-snap"===t?n:null);}},[o,ee,e]),L(()=>{if(!Ot.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?nC:rC,n=e=>nC.has(e)?"Meta":rC.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]=_(0),[be,ye]=_(false),[ve,xe]=_("all"),[we,Se]=_(""),[Ce,ke]=_(""),[Te,Ee]=_(0),[Ae,Me]=_(false),[Ie,Le]=_("pointer"),[Pe,De]=_({}),[Be,$e]=_(false),[_e,Oe]=_(""),[ze,Fe]=_(false),[Ue,He]=_(-1),[We,je]=_(()=>"undefined"!=typeof window&&Boolean(window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__)),[Ge,Qe]=_(()=>"undefined"!=typeof window&&window.__OPHEL_PENDING_UPDATE_VERSION__||null),Ve=$(null),Ke=$(null),Ze=$(null),Ye=$(null),Xe=$(null),Je=$(null),et=$(0),tt=$(null),nt=$("ui"),rt=$(0),[ot,it]=_(0),at=$(0),st=$(null),lt=$(false),ct=$(false),dt=e?.language??gi.language,ut=av.version===ov,ht=ut?(e=>{const t=lv(e);return av.notes[t]})(dt):"",gt=ut?(e=>{const t=lv(e);return av.fullChangelogUrls[t]})(dt):"https://ophel.app/docs/changelog",pt=E(()=>{(async e=>{await ti.storage.set(dv,{lastSeenVersion:e});})(ov).catch(e=>{console.warn("[Ophel] Failed to save release notes state:",e);});},[]),mt=E(()=>{ut&&ht.trim()&&pe(true);},[ut,ht]),ft=E(()=>{pe(false),pt();},[pt]),bt=E(()=>{ti.openTab(gt);},[gt]);L(()=>{if(lt.current||!ut||!ht.trim()||!o||!e?.hasAgreedToTerms)return;let t=false;return lt.current=true,(async()=>(e=>{if(!e||"object"!=typeof e)return {};const t=e.lastSeenVersion;return "string"==typeof t?{lastSeenVersion:t}:{}})(await ti.storage.get(dv)))().then(e=>{t||e.lastSeenVersion===ov||(ct.current=true,fe(e=>e+1));}).catch(e=>{console.warn("[Ophel] Failed to read release notes state:",e);}),()=>{t=true;}},[ut,o,ht,e?.hasAgreedToTerms]),L(()=>{!ct.current||ge||ue||be||Boolean(V)||We||(ct.current=false,pe(true));},[V,be,ge,ue,me,We]);const{globalSearchPromptPreview:yt,globalSearchPromptPreviewPosition:vt,clearPromptPreviewTimer:xt,clearPromptPreviewHideTimer:wt,hideGlobalSearchPromptPreview:St,scheduleHideGlobalSearchPromptPreview:Ct,scheduleGlobalSearchPromptPreview:kt,scheduleGlobalSearchPointerPreview:Tt,refreshGlobalSearchPromptPreviewAnchorRect:Et}=(({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=D(()=>{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:Ye,pointerDelayMs:450,hideDelayMs:220}),[At,Mt]=_(null),[It,Lt]=_(false),[Nt,qt]=_(null),[Rt,Pt]=_(false),[Dt,Bt]=_(null),$t=$(false),_t=$(false),Ot=$(false),zt=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},[]),Ft=E(e=>{for(const t of zt()){const n=t.querySelector(e);if(n instanceof HTMLElement)return n}return null},[zt]),{isEdgePeeking:Ut,showEdgePeek:Ht,hideEdgePeek:Wt,scheduleEdgePeekSync:jt,showEdgePeekFromShortcut:Gt,markSuppressOverlayInit:Qt,markSyncAfterOpen:Vt,handlePanelMouseEnter:Kt,handlePanelMouseLeave:Zt,handleInteractionChange:Yt}=jy({edgeSnapState:Dt,panelMode:e?.panel?.panelMode,isPanelExpanded:Y,findUiElement:Ft,getQueryRoots:zt,isSettingsOpenRef:$t}),[Xt,Jt]=_(false),[en,tn]=_(null),nn=$(false),rn=$(false),on=$(null),an=$(null),sn=$(null),ln=$(false),cn=E(()=>{on.current&&(clearTimeout(on.current),on.current=null);},[]),dn=E(()=>{an.current&&(clearTimeout(an.current),an.current=null);},[]),un=E(()=>{cn(),dn(),nn.current=false,rn.current=false,Jt(false),tn(null);},[cn,dn]),hn=E(()=>{if(ln.current)return false;const e=[".gh-main-panel",".quick-prompt-btn.panel-btn"],t=sn.current;for(const n of e){const e=Ft(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},[Ft]),gn=E(()=>{cn(),dn();const e=()=>{an.current=null,nn.current&&(rn.current||bs(zt())||hn()?an.current=setTimeout(e,250):(nn.current=false,Jt(false),tn(null)));};an.current=setTimeout(e,250);},[cn,dn,zt,hn]),pn=E(e=>{Yt(e),rn.current=e,nn.current&&(e?dn():gn());},[dn,Yt,gn]),mn=E((e,t)=>{if(J.current)return;ln.current=false,cn(),dn();const n={left:e.left,right:e.right,top:e.top,bottom:e.bottom,width:e.width,height:e.height};if(tn(n),nn.current)return;const r=300+(t?.waitForGroupDwell?300:0);on.current=setTimeout(()=>{on.current=null,J.current||(tn(n),nn.current=true,Jt(true));},r);},[cn,dn]),fn=E(()=>{nn.current?gn():cn();},[cn,gn]),bn=E(e=>{if(nn.current)return cn(),void dn();Kt();},[cn,dn,Kt]),yn=E(e=>{nn.current?gn():Zt();},[Zt,gn]);L(()=>{Y&&Xt&&un();},[un,Xt,Y]),L(()=>{const e=e=>{ln.current=false,sn.current={clientX:e.clientX,clientY:e.clientY};},t=()=>{ln.current=true,sn.current=null,cn(),nn.current&&gn();},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);}},[cn,gn]),L(()=>{if(!Xt)return;let e=bs(zt());e&&dn();const t=new MutationObserver(()=>{const t=bs(zt());t?dn():e&&gn(),e=t;});for(const n of zt())t.observe(n,{childList:true,subtree:true});return ()=>{t.disconnect();}},[dn,zt,Xt,gn]),L(()=>()=>{cn(),dn();},[cn,dn]),L(()=>{const e=e=>{be&&(_t.current=false,st.current=null,T(),ye(false),xe("all"),Se(""),ke(""),He(-1),Ee(0),Me(false),Le("pointer"),De({}),et.current=0),$t.current||($t.current=true,Dt&&"edge-snap"===ne.current?.panel?.panelMode&&Ht(),he(true));};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[T,Dt,be,Ht]);const vn=tf(e=>e.conversations),xn=lf(e=>e.folders),wn=hf(e=>e.tags),Sn=nb(e=>e.prompts),Cn=D(()=>(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=RS(s),g=AS(l),p=TS(g);if(!xS.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(!LS(m,p)){r.push({id:`invalid:${m}:${p}:${a.index||0}`,code:"invalidValue",operator:m,value:g,suggestion:NS(m)}),o.push({start:c,end:d}),a=t.exec(e);continue}const f=(i[m]||0)+1;i[m]=f;const b={id:qS(m,p,f),key:m,value:g,normalizedValue:p};IS(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=>{lCn.filters,[Cn.filters]),Tn=D(()=>Cn.diagnostics,[Cn.diagnostics]),En=D(()=>Cn.plainQuery,[Cn.plainQuery]),An=D(()=>Kr(""),[]);L(()=>{if(!Z||!be)return;Z.setGlobalSearchActive(true),Z.refresh(),it(e=>e+1);const e=Z.subscribe(()=>{it(e=>e+1);});return ()=>{e(),Z.setGlobalSearchActive(false);}},[be,Z]);const Mn=D(()=>Array.from(new Set(ES(En))).sort((e,t)=>t.length-e.length),[En]),{filteredGlobalSearchResults:In,globalSearchResultCounts:Ln,groupedGlobalSearchResults:Nn,visibleGlobalSearchResults:qn}=YS({activeGlobalSearchPlainQuery:En,enableFuzzySearch:v,activeGlobalSearchSyntaxFilters:kn,settingsSearchResults:An,resolveSettingSearchTitle:U,getSettingsBreadcrumb:H,conversationManager:Q,conversationsSnapshot:vn,foldersSnapshot:xn,tagsSnapshot:wn,promptsSnapshot:Sn,outlineManager:Z,outlineSearchVersion:ot,getLocalizedText:l,resolveShortcutLabel:b,passThroughModifierLabel:f,activeGlobalSearchCategory:ve,expandedGlobalSearchCategories:Pe,allCategoryItemLimit:12}),Rn=D(()=>{const e=new Map;return qn.forEach((t,n)=>{e.set(t.id,n);}),e},[qn]),Pn=D(()=>0===qn.length?-1:Math.min(Te,qn.length-1),[Te,qn.length]),Dn=Pn>=0?`${sC}-${Pn}`:void 0,Bn=D(()=>oC.find(e=>e.id===ve)||oC[0],[ve]),$n=D(()=>({label:l(Bn.label),placeholder:l(Bn.placeholder),emptyText:l(Bn.emptyText)}),[Bn,l]),_n=D(()=>oC.reduce((e,t)=>(e[t.id]=l(t.label),e),{}),[l]),On=D(()=>Object.entries(iC).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),zn=D(()=>Object.entries(aC).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),{activeGlobalSearchFilterChips:Fn,hasOverflowGlobalSearchFilterChips:Un,globalSearchSyntaxDiagnosticMessages:Hn,globalSearchSyntaxHelpTitle:Wn,globalSearchSyntaxHelpDescription:jn,globalSearchSyntaxHelpItems:Gn,globalSearchSyntaxSuggestions:Qn,shouldShowGlobalSearchSyntaxSuggestions:Vn}=(({getLocalizedText:e,activeGlobalSearchSyntaxFilters:t,filterChipMaxCount:n,isGlobalSettingsSearchOpen:r,settingsSearchInputValue:o,filteredGlobalSearchResults:i,suggestionLimit:a})=>{const s=D(()=>({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=D(()=>({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=D(()=>e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),[e]),d=D(()=>e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"}),[e]),u=D(()=>({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=D(()=>({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=D(()=>({pinned:e({key:"globalSearchSyntaxPinned",fallback:"Pinned"}),unpinned:e({key:"globalSearchSyntaxUnpinned",fallback:"Unpinned"})}),[e]),p=D(()=>({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=D(()=>e({key:"globalSearchSyntaxHelpTitle",fallback:"Search syntax examples"}),[e]),f=D(()=>e({key:"globalSearchSyntaxHelpDesc",fallback:"Click to insert. Keywords are English-only."}),[e]),b=D(()=>e({key:"featureTipSearchPlaceholder",fallback:"Search feature tips…"}),[e]),y=D(()=>[{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=D(()=>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=D(()=>{if(!r)return [];const t=PS(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(!xS.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)wS.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)CS.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});}}kS.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 xS.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(PS(o)?.token)}})({getLocalizedText:l,activeGlobalSearchSyntaxFilters:kn,filterChipMaxCount:4,isGlobalSettingsSearchOpen:be,settingsSearchInputValue:we,filteredGlobalSearchResults:In,suggestionLimit:8}),Zn=D(()=>l({key:"globalSearchResultsLabel",fallback:"Global search results"}),[l]),Yn=E(e=>{const t=PS(we),n=!e.token.endsWith(":"),r=`${e.token}${n?" ":""}`,o=t?`${we.slice(0,t.start)}${r}`:we.trim().length>0?`${we}${we.endsWith(" ")?"":" "}${r}`:r;M(o),He(-1),Ee(0),window.requestAnimationFrame(()=>{const e=Ve.current;if(!e)return;const t=o.length;e.focus({preventScroll:true}),e.setSelectionRange(t,t);});},[we,M]),Xn=E(e=>{Yn(e),Fe(false);},[Yn]),Jn=E(e=>{const t=kn.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:En,filters:t});A(n),He(-1),Ee(0);},[En,kn,A]),er=E(()=>{A(En),He(-1),Ee(0);},[En,A]),tr=D(()=>{if(Pn<0)return null;const e=qn[Pn];if(!e)return null;const t=On[e.category],n=c({key:"globalSearchContextCurrentItem",fallback:"第 {current} 项"},{current:String(Pn+1)});if("all"!==ve)return {label:t,meta:`${n} · ${c({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(qn.length)})}`};const r=Nn.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(qn.length)})}`}},[ve,Pn,c,Nn,On,qn]),nr=E(()=>{$t.current=false,he(false);const e=ne.current;if("edge-snap"!==e?.panel?.panelMode)return;const t=Ft(".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{nt.current=e,$t.current?(_t.current=true,nr()):_t.current=false,Dt&&"edge-snap"===ne.current?.panel?.panelMode&&Ht();const t=document.activeElement;t instanceof HTMLElement&&t!==document.body?st.current=t:st.current=null,T(),Se(""),ke(""),Fe(false),He(-1),xe("all"),Ee(0),Me(false),Le("pointer"),De({}),et.current=0,ye(true);},[T,nr,Dt,Ht]),or=E(e=>{const t=e?.restoreFocus??true,n=e?.reopenSettings??false,r=st.current;if(st.current=null,_t.current=false,T(),ye(false),xe("all"),Se(""),ke(""),Fe(false),He(-1),Ee(0),Me(false),Le("pointer"),De({}),et.current=0,n)return $t.current=true,Dt&&"edge-snap"===ne.current?.panel?.panelMode&&Ht(),void he(true);jt(),t&&r&&r.isConnected&&window.requestAnimationFrame(()=>{if(r.isConnected)try{r.focus({preventScroll:!0});}catch{r.focus();}});},[T,Dt,jt,Ht]),ar=E(()=>{be&&or({restoreFocus:false}),_t.current=false,$t.current=true,Dt&&"edge-snap"===ne.current?.panel?.panelMode&&Ht(),he(true);},[or,Dt,be,Ht]),lr=E(async t=>{const n=++at.current;if(or({restoreFocus:false}),t.tipId){if(t.tipHighlightTarget){const e=Ft(`[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"})}Gi(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!==at.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 Gi(le("bookmarkContentMissing"),3e3)}return}if("prompts"===t.category&&t.promptId){const n=Sn.find(e=>e.id===t.promptId);if(!n)return;const o=()=>{te(true);const t=(e?.features?.order||gi.features.order).indexOf(fr);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 Gi(`${le("inserted")}: ${n.title}`);i(),Gi(le("insertFailed"));})()}var r;"conversations"===t.category&&t.conversationId&&W?.navigateToConversation(t.conversationId,t.conversationUrl);}},[W,or,Ft,Z,te,j,Sn,e]);L(()=>{be&&(Ve.current?.focus(),Ve.current?.select());},[be]),L(()=>{be&&"ui"===nt.current&&B();},[be,B]),L(()=>()=>{C();},[C]);const cr=$(be);L(()=>{cr.current=be;},[be]);const dr=E(()=>{cr.current||(rt.current=0,P(),rr("shortcut"));},[P,rr]);L(()=>{const e=e=>{if(cr.current)return;if("Shift"!==e.key&&(rt.current=0),"Shift"!==e.key||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;const t=Date.now();if((ne.current?.globalSearch?.doubleShift??gi.globalSearch.doubleShift)&&t-rt.current<=360)return e.preventDefault(),e.stopPropagation(),rt.current=0,P(),void rr("shortcut");rt.current=t;};return window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}},[P,rr]),L(()=>{const e=()=>{rr("event");};return window.addEventListener("ophel:openSettingsSearch",e),()=>{window.removeEventListener("ophel:openSettingsSearch",e);}},[rr]),L(()=>()=>{T();},[T]),L(()=>{if(!be||!ze)return;const e=e=>{const t=e.composedPath?e.composedPath():[e.target];Ke.current&&t.includes(Ke.current)||Ze.current&&t.includes(Ze.current)||Fe(false);};return document.addEventListener("mousedown",e,true),()=>{document.removeEventListener("mousedown",e,true);}},[be,ze]),L(()=>{if(!be)return void St();if("keyboard"!==Ie)return;const e=qn[Te];if(!e||"prompts"!==e.category)return void St();const t=Ye.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${Te}"]`);n&&kt({item:e,anchorElement:n,delay:700,source:"keyboard"});},[St,be,kt,Te,Ie,qn]),L(()=>{Ee(0),Me(false),Le("pointer"),De({}),et.current=0,St();},[ve,St,Ce]),L(()=>{be||St();},[St,be]),L(()=>{yt&&Xe.current&&Ad(Xe.current,{size:14});},[yt]),L(()=>{if(!be||!yt)return;const e=()=>{Et();},t=Ye.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);}},[yt,be,Et]),L(()=>()=>{xt(),wt();},[wt,xt]),(({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:be,showGlobalSearchSyntaxHelp:ze,setShowGlobalSearchSyntaxHelp:Fe,activeGlobalSearchCategory:ve,categoryIds:oC.map(e=>e.id),setActiveGlobalSearchCategory:xe,settingsSearchActiveIndex:Te,setSettingsSearchActiveIndex:Ee,settingsSearchNavigationMode:Ie,setSettingsSearchNavigationMode:Le,setSettingsSearchHoverLocked:Me,shouldShowGlobalSearchSyntaxSuggestions:Vn,globalSearchSyntaxSuggestions:Qn,activeSearchSyntaxSuggestionIndex:Ue,setActiveSearchSyntaxSuggestionIndex:He,applyGlobalSearchSyntaxSuggestion:Yn,visibleGlobalSearchResults:qn,navigateToSearchResult:lr,closeGlobalSettingsSearch:or,getShouldReturnToSettingsOnEscape:()=>_t.current,settingsSearchResultsRef:Ye,keyboardSafeTop:8,keyboardSafeBottom:12}),L(()=>{o&&e?.language&&(ae(e.language),s(e=>e+1));},[e?.language,o]);const ur=E(e=>{de(e);},[]),hr=E(()=>{de(null),W&&W.clearTextarea();},[W]);L(()=>{Z&&e&&Z.updateSettings(e.features?.outline);},[Z,e]),L(()=>{Q&&e&&Q.updateSettings({syncUnpin:e.features?.conversations?.syncUnpin??false});},[Q,e]);const mr=D(()=>{const t=Xm(),n=t?.getSiteId()||"_default",r=e?.theme?.sites?.[n]||e?.theme?.sites?._default;return Uy({mode:r?.mode||"light",adapter:W,lightPresetId:r?.lightStyleId||"google-gradient",darkPresetId:r?.darkStyleId||"classic-dark",syncNativePageTheme:e?.theme?.syncNativePageTheme??true})},[]),br=O(mr.subscribe,mr.getSnapshot);L(()=>{if(!o)return;return mr.setOnModeChange((e,n)=>{if(!zi.getState()._hasHydrated)return;const r=n||e,o=ne.current,i=o?.theme?.sites||{},a=Xm(),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}}}});}),()=>{mr.setOnModeChange(void 0);}},[mr,t,o]);const yr=e?.theme?.sites,vr=e?.features?.conversations?.syncUnpin,xr=e?.features?.conversations?.syncDelete,wr=e?.features?.outline?.enabled??true,Sr=e?.features?.outline?.inlineBookmarkMode,Cr=Boolean(e),kr=e?.quickButtons||gi.quickButtons,Tr=kr.collapsed,Er=Tr.find(e=>"floatingToolbar"===e.id)?.enabled??true,Ar=kr.floatingToolbar?.open??true,Mr=e?.panel?.preventAutoScroll??false,Ir=Z?.getGhostBookmarkIds().length??0;L(()=>{Er&&Ar||(Mt(null),Lt(false));},[Er,Ar]),L(()=>{if(!o)return;const e=Xm(),t=e?.getSiteId()||"_default",n=yr?.[t]||yr?._default,r=n?.lightStyleId,i=n?.darkStyleId;r&&i&&mr.setPresets(r,i);},[yr,mr,o]),L(()=>{o&&mr.setCustomStyles(e?.theme?.customStyles||[]);},[e?.theme?.customStyles,mr,o]),L(()=>{o&&mr.setNativeThemeOverrideEnabled(e?.theme?.syncNativePageTheme??true);},[e?.theme?.syncNativePageTheme,mr,o]);const Lr=E(async e=>{await mr.toggle(e);},[mr]);L(()=>{if(o)return mr.startThemeMonitoring(),()=>{mr.stopThemeMonitoring();}},[mr,o]),L(()=>{if(j&&j.init(),Q&&Q.init(),Z){Z.refresh();const e=()=>Z.handleUrlChange(),t=()=>Z.refresh();return window.addEventListener("gh-url-change",e),window.addEventListener("ophel:refreshOutline",t),()=>{window.removeEventListener("gh-url-change",e),window.removeEventListener("ophel:refreshOutline",t),Q?.destroy();}}},[j,Q,Z]),L(()=>{if(!Q||"undefined"==typeof chrome)return;const e=(e,t,n)=>e?.type===Nd&&(Q.destroy(),n({success:true}),true);return chrome.runtime.onMessage.addListener(e),()=>{chrome.runtime.onMessage.removeListener(e);}},[Q]),L(()=>{const e=e=>{if(window.__OPHEL_EXTENSION_UPDATE_DISMISSED__)return;const t=e,n=t.detail?.version||window.__OPHEL_PENDING_UPDATE_VERSION__||null;Qe(n),je(true);};return window.addEventListener(Od,e),window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__&&!window.__OPHEL_EXTENSION_UPDATE_DISMISSED__&&(je(true),Qe(window.__OPHEL_PENDING_UPDATE_VERSION__||null)),()=>{window.removeEventListener(Od,e);}},[]),L(()=>(window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=We,We&&document.getElementById("ophel-extension-update-fallback")?.remove(),()=>{window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=false;}),[We]);const Nr=E(()=>{window.__OPHEL_EXTENSION_UPDATE_DISMISSED__=true,window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__=false,je(false);},[]),qr=E(()=>{window.location.reload();},[]);L(()=>{Q&&Q.updateSettings({syncUnpin:vr??false,syncDelete:xr??true});},[Q,vr,xr]),L(()=>{if(!(o&&Z&&W&&Cr))return;const e=Sr||"always";if(!wr||"hidden"===e)return void Jf.cleanupInjectedArtifacts();const t=new Jf(Z,W,e);return ()=>{t.cleanup();}},[Z,W,wr,Sr,Cr,o]);const Rr=E(()=>{const e=ne.current;if(!e)return;const n=!e.panel?.preventAutoScroll;t({panel:{...e.panel,preventAutoScroll:n}}),Gi(le(n?"preventAutoScrollEnabled":"preventAutoScrollDisabled"));},[t]),Pr=E(async()=>{if(!Q||!W)return;const e=W.getSessionId();if(!e)return void Gi(le("exportNeedOpenFirst"));await Q.exportConversation(e,"markdown")||Gi(le("exportFailed"));},[Q,W]),Dr=E(async()=>{if(!Q||!W)return;const e=W.getSessionId();if(e){Pt(true);try{const t=await Q.prepareSegmentedConversationExport(e);if(!t||0===t.segments.length)return void Gi(le("segmentedExportNoSegments"));qt(t);}finally{Pt(false);}}else Gi(le("exportNeedOpenFirst"));},[Q,W]),Br=E(async(e,t)=>{if(Q&&Nt){Pt(true);try{await Q.exportSegmentedConversation(Nt,e,t)&&qt(null);}finally{Pt(false);}}},[Q,Nt]),$r=E(()=>{if(!Q||!W)return;const e=W.getSessionId();if(!e)return void Gi(le("noConversationToLocate"));const t=Q.getConversation(e);Mt({convId:e,activeFolderId:t?.folderId});},[Q,W]),_r=E(()=>{if(!Z)return;const e=Z.clearGhostBookmarks();Gi(0!==e?`${le("cleared")} (${e})`:le("floatingToolbarClearGhostEmpty"));},[Z]),Or=E(async()=>{if(!Q||!W)return;const e=W.getSessionId();if(!e)return void Gi(le("exportNeedOpenFirst"));await Q.exportConversation(e,"clipboard")||Gi(le("exportFailed"));},[Q,W]),zr=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}}}),Gi(le("modelLockDisabled"))):(Gi(le("modelLockNoKeyword")),t({modelLock:{...n.modelLock,[e]:{...r,enabled:true}}}),ar(),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}}}),Gi(le(o?"modelLockEnabled":"modelLockDisabled"));},[W,ar,t]),Fr=D(()=>{if(!W||!e)return false;const t=W.getSiteId();return e.modelLock?.[t]?.enabled||false},[W,e]),Ur=E(()=>{un();const e=!J.current;e&&"edge-snap"===ne.current?.panel?.panelMode?(Dt||Bt(ne.current?.panel?.defaultPosition??"right"),Ht(),Vt()):e||Wt(),te(e);},[Dt,Wt,un,Vt,te,Ht]);tv({settings:e,adapter:W,outlineManager:Z,conversationManager:Q,onPanelToggle:Ur,onThemeToggle:Lr,onOpenSettings:ar,onOpenGlobalSearch:dr,isPanelVisible:Y,isSnapped:!!Dt&&!Ut,onShowSnappedPanel:Gt,onToggleScrollLock:Rr});const Hr=$(void 0);L(()=>{const t=e?.panel?.panelMode??"edge-snap";if(void 0!==Hr.current){if(Hr.current!==t)if(Hr.current=t,"edge-snap"===t){const t=e?.panel?.defaultPosition??"right";Qt(J.current),Bt(t),Wt();}else Bt(null),Wt();}else Hr.current=t;},[Wt,Qt,e?.panel?.defaultPosition,e?.panel?.panelMode]);const Wr=$(e?.panel?.defaultPosition);L(()=>{const t=e?.panel?.defaultPosition;void 0===Wr.current&&t?Wr.current=t:t&&Wr.current!==t&&(Wr.current=t,Dt&&(Bt(t),Wt()));},[Dt,Wt,e?.panel?.defaultPosition]);const Gr=E(e=>{if(!W||W.getSiteId()!==Co)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";Gi(`AI Studio ${le("promptSubmitShortcutLabel")}: ${o}`);},[W]);L(()=>{if(!W||W.getSiteId()!==Co)return;const e=e=>{const t=e.detail;if(t?.forcedByMobile)return;const n=t?.submitShortcut;"enter"!==n&&"ctrlEnter"!==n||Gr(n);};return window.addEventListener(cb,e),()=>{window.removeEventListener(cb,e);}},[W,Gr]),L(()=>{W&&j&&W.getSiteId()===Co&&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||e.altKey)&&!e.shiftKey,o=e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey;if(!(W.getSiteId()===Co&&lb()&&r))if("enter"!==i){if(o){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return void(j.submitCurrentInputImmediately(i)&&de(null))}r&&(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));}else r&&ce&&window.setTimeout(()=>de(null),0);};return W.getSiteId()===bo?(window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}):(document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);})},[W,j,i,ce]),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;const e=()=>{de(null),W.clearTextarea();};return window.addEventListener(zd,e),()=>{window.removeEventListener(zd,e);}},[ce,W]);const[Qr,Vr]=_(null),Zr=E(()=>{if(!Q||!W)return;const e=W.getSessionId();e?Vr({convId:e}):Gi(le("noConversationToLocate"));},[Q,W]),{tags:Yr,addTag:Xr,updateTag:Jr,deleteTag:eo}=hf(),to=E(e=>{Le("pointer"),De(t=>({...t,[e]:!t[e]}));},[]),no=l({key:"extensionUpdateNoticeKicker",fallback:"Extension updated"}),ro=Ge?c({key:"extensionUpdateNoticeWithVersion",fallback:`${rv} has been updated to v{version}. Reload this page to keep using the latest version.`},{version:Ge}):l({key:"extensionUpdateNotice",fallback:`${rv} has been updated. Reload this page to keep using the latest version.`}),oo=l({key:"extensionUpdateNoticeAction",fallback:"Reload page"}),io=le("close"),ao=V?le(("outline-copy"===V.operation?JS:XS)[V.stage]):"",so=le("outline-copy"===V?.operation?"outlineCopyOverlayHint":"exportOverlayHint"),lo=D(()=>({query:l({key:"outlineUserQueryRoleLabel",fallback:"User queries"}),reply:l({key:"globalSearchOutlineReplies",fallback:"Replies"})}),[l]);return W&&j&&Q&&Z?Re("div",{className:"gh-root "+(re?"gh-pass-through":""),children:[ qe(vx,{isOpen:Y||Xt,isLauncherPeeking:Xt,launcherPeekAnchorRect:en,onClose:()=>{un(),Wt(),te(false);},promptManager:j,conversationManager:Q,outlineManager:Z,adapter:W,onThemeToggle:Lr,themeMode:br,selectedPromptId:ce?.id,onPromptSelect:ur,edgeSnapState:Dt,isEdgePeeking:Ut,onEdgeSnap:e=>Bt(e),onUnsnap:()=>{Bt(null),Wt();},onInteractionStateChange:pn,onOpenSettings:()=>{ar();},onMouseEnter:bn,onMouseLeave:yn}), qe(Ex,{isPanelExpanded:Y,onPanelToggle:Ur,onPanelLogoHoverStart:mn,onPanelLogoHoverEnd:fn,onThemeToggle:Lr,themeMode:br,onExport:Pr,onMove:$r,onSetTag:Zr,onScrollLock:()=>Rr(),onSettings:()=>{ar(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"general",subTab:"toolsMenu"}}));},50);},scrollLocked:Mr,onCleanup:()=>{0!==Ir?Lt(true):Gi(le("floatingToolbarClearGhostEmpty"));},onGlobalSearch:rr,onCopyMarkdown:Or,onSegmentedExport:Dr,onModelLockToggle:zr,isModelLocked:Fr,onOpenSettings:ar}),ce&&qe(Mx,{title:ce.title,onClear:hr,adapter:W}), qe(mS,{isOpen:ue,onClose:nr,siteId:W.getSiteId(),onOpenReleaseNotes:ut?mt:void 0}),ge&&ut&&ht.trim()?qe(Sx,{version:av.version,date:av.date,markdown:ht,language:dt,media:av.media,fullChangelogUrl:gt,onClose:ft,onOpenFullChangelog:bt}):null,Nt&&qe(zv,{draft:Nt,isExporting:Rt,onCancel:()=>{Rt||qt(null);},onExport:Br}), qe(fS,{isOpen:be,onClose:()=>{St(),or();},inputRef:Ve,resultsRef:Ye,activeOptionId:Dn,inputValue:we,inputPlaceholder:g?`${$n.placeholder}(${g})`:$n.placeholder,onInputChange:e=>{N(e),He(-1),Ee(0);const t=e.trimStart();t.startsWith("tip:")&&"tips"!==ve?xe("tips"):t.startsWith("tip:")||"tips"!==ve||xe("all");},hotkeyLabel:y,fuzzySearchToggleLabel:l({key:"globalSearchFuzzySearchToggle",fallback:"Fuzzy"}),fuzzySearchToggleAriaLabel:l({key:"globalSearchFuzzySearchToggleAria",fallback:"Toggle fuzzy search"}),isFuzzySearchEnabled:v,onToggleFuzzySearch:I,syntaxHelpTriggerRef:Ke,syntaxHelpPopoverRef:Ze,showSyntaxHelp:ze,onToggleSyntaxHelp:()=>Fe(e=>!e),syntaxHelpTriggerAriaLabel:l({key:"globalSearchSyntaxHelpTriggerAria",fallback:"Open search syntax help"}),syntaxHelpTitle:Wn,syntaxHelpDescription:jn,syntaxHelpItems:Gn,onApplySyntaxHelpItem:Xn,activeFilterChips:Fn,hasOverflowFilterChips:Un,overflowFilterChipText:c({key:"globalSearchSyntaxChipOverflow",fallback:"+{count} more"},{count:String(kn.length-4)}),filterChipRemoveTitle:l({key:"globalSearchSyntaxChipRemove",fallback:"Click to remove filter"}),clearFiltersLabel:l({key:"clear",fallback:"Clear"}),onRemoveFilterChip:Jn,onClearAllFilterChips:er,shouldShowSyntaxSuggestions:Vn,syntaxSuggestions:Qn,activeSyntaxSuggestionIndex:Ue,onHoverSyntaxSuggestion:He,onApplySyntaxSuggestion:Yn,syntaxDiagnostics:Tn,resolveSyntaxDiagnosticTitle:e=>Hn[e]||Hn.invalidValue,showShortcutNudge:Be,shortcutNudgeMessage:_e,closeLabel:l({key:"close",fallback:"Close"}),dismissShortcutNudgeLabel:l({key:"globalSearchShortcutNudgeDismiss",fallback:"Don’t remind me"}),onHideShortcutNudge:q,onDismissShortcutNudgeForever:R,categoriesLabel:l({key:"globalSearchCategoriesLabel",fallback:"Global search categories"}),categories:oC.map(e=>({id:e.id,label:_n[e.id],count:"tips"===e.id&&"tips"!==ve?null:Ln[e.id]})),activeCategoryId:ve,onSelectCategory:e=>{xe(e),Ee(0);},activeContext:tr,listboxId:"settings-search-results-listbox",listboxLabel:Zn,onResultsWheel:()=>{Le("pointer"),et.current=Date.now()+200,St();},visibleResults:qn,groupedResults:Nn,getGroupLabel:e=>On[e],allCategoryItemLimit:12,isAllCategory:"all"===ve,emptyText:$n.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:()=>Yn({id:"example:type-prompts",token:"type:prompts",label:"type:prompts",description:""})},{id:"example:is-pinned",token:"is:pinned",onClick:()=>Yn({id:"example:is-pinned",token:"is:pinned",label:"is:pinned",description:""})},{id:"example:folder-inbox",token:"folder:inbox",onClick:()=>Yn({id:"example:folder-inbox",token:"folder:inbox",label:"folder:inbox",description:""})},{id:"example:tag-work",token:"tag:work",onClick:()=>Yn({id:"example:tag-work",token:"tag:work",label:"tag:work",description:""})},{id:"example:level-0",token:"level:0",onClick:()=>Yn({id:"example:level-0",token:"level:0",label:"level:0",description:""})},{id:"example:date-7d",token:"date:7d",onClick:()=>Yn({id:"example:date-7d",token:"date:7d",label:"date:7d",description:""})}],renderSearchResultItem:(e,t)=>qe(vS,{item:e,index:t,optionIdPrefix:sC,isActive:t===Te,highlightTokens:Mn,outlineRoleLabels:lo,matchReasonLabels:zn,onMouseMove:()=>{Le("pointer"),Date.now(){Le("pointer"),Tt({item:e,anchorElement:t.currentTarget});},onMouseLeave:()=>{Ct();},onClick:()=>lr(e)},e.id),resolveVisibleResultIndex:(e,t)=>Rn.get(e.id)??t,collapseLabel:l({key:"collapse",fallback:"Collapse"}),moreLabel:l({key:"floatingToolbarMore",fallback:"More"}),onToggleCategoryGroup:to,footerTips:l({key:"globalSearchFooterTips",fallback:"Enter to jump · ↑↓ to select · Tab category · Esc to close"}),promptPreview:yt&&vt?Re(Ne,{children:[ qe("div",{ref:Xe,className:"settings-search-prompt-preview-float gh-markdown-preview",style:{top:vt.top,left:vt.left},onMouseEnter:()=>{xt(),wt();},onMouseLeave:()=>{Ct();},onClick:k,dangerouslySetInnerHTML:{__html:gu(tc(yt.content,false))}}), qe("style",{children:nc()})]}):void 0}),At&&qe(bv,{folders:Q.getFolders(),excludeFolderId:Q.getConversation(At.convId)?.folderId,activeFolderId:At.activeFolderId,onSelect:async e=>{await Q.moveConversation(At.convId,e),Mt(null);},onCancel:()=>Mt(null)}),Qr&&qe(yv,{tags:Yr,conv:Q.getConversation(Qr.convId),onCancel:()=>Vr(null),onCreateTag:async(e,t)=>Xr(e,t),onUpdateTag:async(e,t,n)=>Jr(e,t,n),onDeleteTag:async e=>{eo(e);},onSetConversationTags:async(e,t)=>{await Q.updateConversation(e,{tagIds:t});},onRefresh:()=>{}}),It&&qe(pv,{title:le("floatingToolbarClearGhost"),message:le("floatingToolbarClearGhostConfirm").replace("{count}",String(Ir)),danger:true,onConfirm:()=>{Lt(false),_r();},onCancel:()=>Lt(false)}),W&&G&&(e?.features?.prompts?.promptQueue??false)&&qe(xx,{adapter:W,dispatcher:G}),W&&j&&(e?.features?.prompts?.enabled??true)&&qe(Py,{adapter:W,promptManager:j}), qe(Ev,{isVisible:Boolean(V),text:ao,hint:so,tone:"export",blockPageInteraction:true}),We&&Re("section",{className:"gh-update-notice gh-interactive",role:"status","aria-live":"polite",children:[ qe("button",{type:"button",className:"gh-update-notice-close","aria-label":io,onClick:Nr,children:Re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ qe("path",{d:"M18 6 6 18"}), qe("path",{d:"m6 6 12 12"})]})}), Re("div",{className:"gh-update-notice-kicker",children:[ qe("svg",{className:"gh-update-notice-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:qe("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"})}),no]}), qe("p",{className:"gh-update-notice-message",children:ro}), qe("div",{className:"gh-update-notice-actions",children:qe("button",{type:"button",className:"gh-update-notice-button gh-update-notice-button--primary",onClick:qr,children:oo})})]}), qe(Tv,{})]}):null}},Symbol.toStringTag,{value:"Module"})),gC="[GeminiMyStuffBridge]",pC=[1,1,1,0,0,0,1,0],mC=[1,1,1,1,1,0,1,0],fC={"x-same-domain":"1","x-goog-ext-525001261-jspb":"[1,null,null,null,null,null,null,null,[4]]","x-goog-ext-73010989-jspb":"[]"};let bC=false;const yC=new Map,vC=new Map;function xC(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function wC(e=window.location.pathname){return e.replace(/^\/u\/\d+/,"")}function SC(e){return "document"===e?mC:pC}function CC(e){let t=yC.get(e);return t||(t=new Map,yC.set(e,t)),t}function kC(e){return "string"==typeof e&&/^boq_assistant-bard-web-server_/i.test(e)}function TC(e){return "string"==typeof e&&/^\d{10,}$/.test(e)}function EC(e){return "string"==typeof e&&/^[A-Za-z0-9._:-]+:\d{13}$/.test(e)}function AC(e,t){for(const n of Object.values(e))if("string"==typeof n&&t(n))return n;return null}function MC(e,t){const n=e.match(t);return n?.[1]||n?.[0]||null}function IC(){const e=xC(),t=e.WIZ_global_data||{},n=document.querySelector('script[data-id="_gd"]')?.textContent||"",r=(kC(t.cfb2h)?t.cfb2h:null)||AC(t,kC)||MC(n,/"cfb2h":"([^"]+)"/)||MC(n,/boq_assistant-bard-web-server_[^"]+/),o=(TC(t.FdrFJe)?t.FdrFJe:null)||AC(t,TC)||MC(n,/"FdrFJe":"([^"]+)"/)||MC(n,/"\d{10,}"/)?.replace(/"/g,"")||null,i=(EC(t.SNlM0e)?t.SNlM0e:null)||AC(t,EC)||MC(n,/"SNlM0e":"([^"]+)"/)||MC(n,/[A-Za-z0-9._:-]+:\d{13}/)||null;return kC(r)&&TC(o)&&EC(i)?{bl:r,fSid:o,at:i,hl:document.documentElement.lang||navigator.language||"zh-CN"}:(console.warn(`${gC} failed to resolve runtime tokens`,{hasGlobalData:Boolean(e.WIZ_global_data),bl:r,fSid:o,at:i}),null)}function LC(e){const t=new URL("/_/BardChatUi/data/batchexecute",window.location.origin);return t.searchParams.set("rpcids","jGArJ"),t.searchParams.set("source-path",wC()),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 NC(e,t,n){const r=new URLSearchParams,o=n?[SC(t),30,n]:[SC(t),30];return r.set("f.req",JSON.stringify([[["jGArJ",JSON.stringify(o),null,"generic"]]])),r.set("at",e.at),r.toString()}function qC(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 RC(e){return e.flatMap(e=>Array.from(CC(e).values()))}function PC(e){window.postMessage({type:_d,payload:e},"*"),window.dispatchEvent(new CustomEvent(_d,{detail:e}));}async function DC(e){if(!e?.requestId||!function(e=window.location.pathname){const t=wC(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===CC(e).size);try{n&&await Promise.all(t.map(t=>async function(e,t){const n=CC(e);if(!t&&n.size>0)return Array.from(n.values());const r=vC.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=IC();if(!o)throw new Error("mystuff-runtime-tokens-missing");const i=await xC().fetch(LC(o),{method:"POST",credentials:"include",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",...fC},body:NC(o,e,r)}),a=await i.text();if(!i.ok)throw console.warn(`${gC} fetch failed`,{kind:e,page:n,status:i.status,preview:a.slice(0,240)}),new Error(`mystuff-fetch-failed:${i.status}`);const s=qC(a,e);if(s.items.forEach(e=>{return t.set(`${(n=e).conversationId}:${n.responseId}`,e);var n;}),console.info(`${gC} 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())})();vC.set(e,o);try{return await o}finally{vC.delete(e);}}(t,Boolean(e.force))));const r=RC(t);PC({requestId:e.requestId,items:r,kinds:t,reason:n?"sync":"snapshot",timestamp:Date.now()});}catch(vT){console.warn(`${gC} sync request failed`,{requestId:e.requestId,kinds:t,error:vT}),PC({requestId:e.requestId,items:RC(t),kinds:t,reason:"snapshot",timestamp:Date.now()});}}function BC(){bC||"gemini.google.com"!==window.location.hostname||(bC=true,window.addEventListener("message",e=>{e.data?.type===$d&&DC(e.data.payload);}),window.addEventListener($d,e=>{DC(e.detail);}),console.info(`${gC} initialized`));}function $C(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}class _C{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=$C();this._originalFetch=e.fetch,e.fetch=this._boundHookedFetch,this._hookXHR(),this._isMonitoring=true;}stop(){if(!this._isMonitoring)return;const e=$C();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=$C(),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(vT){throw this._decrementAndSchedule(),vT}}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=$C().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=$C().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 OC=null,zC=false;const FC=Object.freeze(Object.defineProperty({__proto__:null,initNetworkMonitor:function(){zC||(zC=true,BC(),window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==Pd&&t!==Bd&&t!==Dd||t===Pd&&(OC&&OC.stop(),OC=new _C({urlPatterns:n?.urlPatterns,urlPathEndsWith:n?.urlPathEndsWith,silenceThreshold:n?.silenceThreshold,requestBodyRules:n?.requestBodyRules,onStart:e=>window.postMessage({type:Dd,payload:e},"*"),onComplete:e=>window.postMessage({type:Bd,payload:e},"*")}),OC.start());}));}},Symbol.toStringTag,{value:"Module"}));let UC=false,HC=null,WC=false;function jC(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function GC(){const e=jC().document.documentElement?.getAttribute(Va)?.trim();return e||null}function QC(e){const t=e.trim();if(!t)return;const n=jC(),r=n.document.documentElement;r?.setAttribute(Ka,t),r?.setAttribute(Za,n.location.pathname);}function VC(){if(WC)return;const e=jC(),t=e.document,n=GC();n&&t.title!==n&&(QC(t.title),WC=true,t.title=n,e.queueMicrotask(()=>{WC=false;}));}const KC=Object.freeze(Object.defineProperty({__proto__:null,initGeminiTitleGuard:function(){UC||"gemini.google.com"!==jC().location.hostname||(UC=true,function(){const e=jC(),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=GC();if(e&&r!==e)return QC(r),void n.set?.call(this,e)}this===e.document&&r!==GC()&&QC(r),n.set?.call(this,r);}});}(),function(){const e=jC(),t=e.document;if(HC||void 0===e.MutationObserver)return;HC=new e.MutationObserver(()=>{WC||VC();});const n=()=>{t.head&&HC?.observe(t.head,{childList:true,subtree:true,characterData:true});};n(),t.head||t.addEventListener("DOMContentLoaded",n,{once:true}),t.documentElement&&HC.observe(t.documentElement,{attributes:true,attributeFilter:[Va]});}(),VC());}},Symbol.toStringTag,{value:"Module"})),ZC="gh-assistant-mermaid-style",YC=".gh-assistant-mermaid",XC="data-ophel-assistant-mermaid-managed",JC="data-ophel-assistant-mermaid-original-display",ek="data-ophel-assistant-mermaid-preview-id",tk="data-ophel-assistant-mermaid-render-token",nk="data-ophel-assistant-mermaid-fullscreen",rk="data-ophel-assistant-mermaid-restore-zoom",ok="data-ophel-assistant-mermaid-fullscreen-max-zoom",ik="OPHEL_ASSISTANT_MERMAID_RENDER_RESPONSE",ak="http://www.w3.org/2000/svg";function sk(e){{const t=window.__OPHEL_USERSCRIPT_ASSET_URLS__?.[e];return "string"==typeof t&&t.length>0?t:null}}function lk(){return "1"===document.documentElement.getAttribute("data-ophel-assistant-mermaid-runner")}function ck(e,t){const n=e.createElementNS(ak,"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 dk{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(){Cs.query(YC,{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=Cs.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(YC))||n.closest(YC);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),Gi(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),Gi(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!==ik)return;if(t?.type!==ik)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=Cs.query(`${YC}[${nk}='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=Cs.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(tk,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(tk)!==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(vT){if(!e.isConnected||!a.isConnected||!s.isConnected||s.getAttribute(tk)!==d)return;console.warn("[AssistantMermaidRenderer] Mermaid render skipped:",vT),!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))}(vT)?(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?.(YC)?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(XC,"true"),e.hasAttribute(JC)||e.setAttribute(JC,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=ck(e,"0 0 24 24"),n=e.createElementNS(ak,"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=ck(e,"0 0 24 24"),n=e.createElementNS(ak,"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=ck(e,"0 0 24 24"),n=e.createElementNS(ak,"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=ck(e,"0 0 24 24"),n=e.createElementNS(ak,"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(ek);if(t)return t;this.previewIdCounter+=1;const n=`gh-assistant-mermaid-preview-${Date.now()}-${this.previewIdCounter}`;return e.setAttribute(ek,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(JC)||"";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(ok)||"");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(nk,"1"),e.setAttribute(rk,e.dataset.zoom||"1");try{await t.requestFullscreen();}catch(vT){throw this.clearFullscreenState(e),vT}}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(ok,`${Math.max(3,s)}`),this.applyPreviewZoom(e,s),t.scrollTop=0,t.scrollLeft=0;}restorePreviewZoomAfterFullscreen(e){const t=Number.parseFloat(e.getAttribute(rk)||"")||1;this.clearFullscreenState(e),this.applyPreviewZoom(e,t);}clearFullscreenState(e){e.removeAttribute(nk),e.removeAttribute(rk),e.removeAttribute(ok);}async copyMermaidSource(e){const t=e.dataset.source||"";t&&(await navigator.clipboard.writeText(t),Gi(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(vT){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")}(vT))throw vT;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);}Gi(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",ak),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(ak,"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(ak,"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(){Cs.query(`[${XC}]`,{all:true,shadow:true}).forEach(e=>{e instanceof HTMLElement&&(e.style.display=e.getAttribute(JC)||"",e.removeAttribute(XC),e.removeAttribute(JC));});Cs.query(YC,{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(JC)||"",e.removeAttribute(XC),e.removeAttribute(JC);}injectStyles(e){if(this.injectedRoots.has(e))return;if(e.querySelector?.(`#${ZC}`))return;const t=document.createElement("style");t.id=ZC,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(!lk())return this.runtimePromise||(this.runtimePromise=(async()=>{const e=sk("assistantMermaidVendor"),t=sk("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"),!lk())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&&!fu(i,e))throw new Error(`Failed to set trusted script src: ${e}`);r||(document.head||document.documentElement).appendChild(i);}catch(vT){a(),o(vT instanceof Error?vT: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 uk="ghTableCopy",hk=[".ProseMirror",".ql-editor",".cm-editor",".monaco-editor"],gk=".gh-user-query-markdown, .gh-markdown-preview";class pk{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(pk.FORMULA_HOST_SELECTOR);if(!r)return;if(!e)return Gi(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();Gi(le("formulaSourceUnavailable")),t.preventDefault(),t.stopPropagation();}catch(r){console.error("[FormulaCopy] Unexpected error:",r),Gi(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 Gi(le("formulaSourceUnavailable"));const t=e.mathml||this.renderLatexToMathml(e.latex||"",e.isBlock);t?this.copyText(t):Gi(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=ec(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(()=>Gi(le("formulaCopied"))).catch(e=>{console.error("[FormulaCopy] Copy failed:",e),Gi(le("copyFailed"));}):Gi(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=Cs.each("table",e=>{this.injectTableButton(e);},{shadow:true});}startRescanTimer(){this.rescanTables(),this.rescanTimer=setInterval(()=>{this.rescanTables();},1e3);}rescanTables(){if(document.hidden)return;const e=Cs.query("table",{all:true,shadow:true});for(const t of e)this.injectTableButton(t);}injectTableButton(e){if(e.dataset[uk])return;const t=!!e.closest(gk);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(Td({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(()=>{Gi(le("tableCopied")),Ed(r,{size:14});}).catch(e=>{console.error("[TableCopy] Copy failed:",e),Gi(le("copyFailed"));});}),n.appendChild(r),e.dataset[uk]="true";}catch(n){console.error("[TableCopy] Error injecting button:",n);}}isTableInsideEditableHost(e){let t=e;for(;t;){if(t instanceof HTMLElement){if(t.matches(gk))return false;if(this.isEditableHost(t))return true}t=Cs.getComposedParent(t);}return false}isEditableHost(e){if(e.isContentEditable)return true;if("textbox"===e.getAttribute("role"))return true;if(hk.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(),Cs.query(".gh-table-copy-btn",{all:true,shadow:true})?.forEach(e=>e.remove()),Cs.query("[data-gh-table-copy]",{all:true,shadow:true})?.forEach(e=>{e instanceof HTMLElement&&e.removeAttribute("data-gh-table-copy");}),Cs.query(".gh-table-container",{all:true,shadow:true})?.forEach(e=>{e.classList.remove("gh-table-container");});}stop(){this.destroyFormulaCopy(),this.destroyTableCopy();}}const mk="gh-page-width-styles",fk="gh-page-width-shadow",bk="gh-user-query-width-styles",yk="gh-user-query-width-shadow",vk="gh-zen-mode-styles",xk="gh-zen-mode-shadow",wk="gh-clean-mode-styles",Sk="gh-clean-mode-shadow",Ck="gh-zen-mode-exit-host",kk={enabled:false,showExitButton:true};class Tk{siteAdapter;pageWidthConfig;userQueryWidthConfig=null;pageWidthStyle=null;userQueryWidthStyle=null;zenModeStyle=null;zenModeConfig=kk;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(mk,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(bk,e),this.refreshShadowInjection();}updateZenMode(e){this.zenModeConfig="boolean"==typeof e?{...this.zenModeConfig,enabled:e}:{...kk,...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(vk,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(wk,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(Ck);e instanceof HTMLElement&&e.remove();const t=document.createElement("div");t.id=Ck,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=gu(`\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),zi.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;Cs.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}`;}Cs.cssToShadow(t,o,fk);}else this.removeStyleFromShadow(t,fk);if(this.userQueryWidthConfig?.enabled){const n=this.userQueryWidthConfig.value||"81",r=this.userQueryWidthConfig.unit||"%",o=this.buildCSSFromSelectors(e.getUserQueryWidthSelectors(),`${n}${r}`,false);Cs.cssToShadow(t,o,yk);}else this.removeStyleFromShadow(t,yk);if(this.zenModeEnabled){const e=this.generateZenModeCSS();e?Cs.cssToShadow(t,e,xk):this.removeStyleFromShadow(t,xk);}else this.removeStyleFromShadow(t,xk);if(this.cleanModeEnabled){const e=this.generateCleanModeCSS();e?Cs.cssToShadow(t,e,Sk):this.removeStyleFromShadow(t,Sk);}else this.removeStyleFromShadow(t,Sk);this.processedShadowRoots.add(t);}});}removeStyleFromShadow(e,t){const n=e.getElementById(t);n&&n.remove();}clearAllShadowStyles(){document.body&&Cs.walkShadowRoots(e=>{this.removeStyleFromShadow(e,fk),this.removeStyleFromShadow(e,yk),this.removeStyleFromShadow(e,xk),this.removeStyleFromShadow(e,Sk),this.processedShadowRoots.delete(e);});}}const Ek=/]*>[\s\S]*?<\/code>/gi,Ak=/]*>([\s\S]*?)<\/b>/gi,Mk=/]*>([\s\S]*?)<\/strong>/gi,Ik=/\*\*([^*]+(?:\*(?!\*)[^*]*)*)\*\*/g,Lk=/###OPHEL_CODE_(\d+)###/g;class Nk{stopObserver=null;enabled=false;config;constructor(e){this.config=e;}start(){this.enabled||(this.enabled=true,this.fixAllParagraphs(),this.stopObserver=Cs.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(){Cs.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(Mk,"**$1**");r=r.replace(Ak,"**$1**");let o=false;if(r=r.replace(Ik,(e,t)=>(o=true,`${t}`)),o){const o=r.replace(Lk,(e,t)=>n[parseInt(t,10)]);t!==o&&pu(e,o);}e.dataset.mdFixerHash=String(e.innerHTML.length);}}class qk{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 Rk{adapter;settings;retryCounts=new Map;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:Pd,payload:{urlPatterns:e.urlPatterns,urlPathEndsWith:e.urlPathEndsWith,silenceThreshold:e.silenceThreshold}},"*"),this.monitorInitialized=true);}handleMessage(e){if(this.adapter.getSiteId()!==wo)return;const t=e.data;if(t&&t.type===Bd){if(!this.settings.enabled)return;this.checkAndRetry();}}async checkAndRetry(){await new Promise(e=>setTimeout(e,500));const e=Cs.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=Cs.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 Pk{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=Pk.HYDRATION_TIMEOUT_MS){return !!ww.getState()._hasHydrated||new Promise(t=>{let n=false,r=0;const o=e=>{n||(n=true,window.clearTimeout(r),i(),t(e));},i=ww.subscribe(e=>{e._hasHydrated&&o(true);});r=window.setTimeout(()=>{ww.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=Pk.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,Pk.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 Vd(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;Sw().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 Dk{settings;enabled=false;constructor(e,t){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 Bk{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;handleTitleUpdateTimer=()=>{this.intervalId=null,this.isRunning&&(this.updateTabName(),this.scheduleNextTitleUpdate());};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(),this.startTitleUpdateLoop();const e=this.adapter.getNetworkMonitorConfig?this.adapter.getNetworkMonitorConfig():null;e&&window.postMessage({type:Pd,payload:{urlPatterns:e.urlPatterns,urlPathEndsWith:e.urlPathEndsWith,silenceThreshold:e.silenceThreshold,requestBodyRules:e.requestBodyRules}},"*");}stop(){this.isRunning&&(this.isRunning=false,this.resetGenerationConfirmationState(),this.stopTitleObserver(),this.expectedTitle=null,this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null,ts(),this.clearTitleUpdateTimer());}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){this.isRunning&&(this.settings.renameInterval=e,this.scheduleNextTitleUpdate(true));}startTitleUpdateLoop(){this.intervalId||this.scheduleNextTitleUpdate();}scheduleNextTitleUpdate(e=false){if(this.isRunning){if(this.intervalId){if(!e)return;clearTimeout(this.intervalId),this.intervalId=null;}this.intervalId=setTimeout(this.handleTitleUpdateTimer,this.getTitleUpdateDelayMs());}}clearTitleUpdateTimer(){this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null);}getTitleUpdateDelayMs(){const e=1e3*Math.max(1,this.settings.renameInterval||5);return this.shouldUseBackgroundIdleTitleUpdateInterval()?Math.max(e,15e3):e}shouldUseBackgroundIdleTitleUpdateInterval(){return !!this.isUserAway()&&("generating"!==this.aiState&&!this.currentNetworkGenerationPending&&!this.currentGenerationUsesDomCompletion&&null===this.generationConfirmationIntervalId&&null===this.domCompletionIntervalId)}togglePrivacyMode(){return this.settings.privacyMode=!this.settings.privacyMode,this.updateTabName(true),this.settings.privacyMode}resetConversationTitleCache(){const e=es(document.title),t=es(this.expectedTitle)||es(ns()),n=es(this.lastConversationTitle),r=e&&e===t?rs(e,{expectedManagedTitle:t,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat}):null;this.lastConversationTitle=null,this.expectedTitle=null,ts(),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=es(t.modelName)?`[${es(t.modelName)}]`:"";return (n?e:is(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(Va,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:rs(e,{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})}shouldIgnoreStaleManagedTitle(e){return !!this.staleManagedTitleAfterRouteChange&&(es(document.title)!==this.staleManagedTitleAfterRouteChange?(this.clearStaleManagedTitleAfterRouteChange(),false):this.isManagedDocumentTitleFallback(e,this.staleManagedTitleAfterRouteChange,this.staleConversationTitleAfterRouteChange))}shouldIgnoreCurrentManagedDocumentTitle(e){return !!this.expectedTitle&&(es(document.title)===es(this.expectedTitle)&&this.isManagedDocumentTitleFallback(e,this.expectedTitle,this.lastConversationTitle))}isManagedDocumentTitleFallback(e,t,n){const r=es(e),o=es(t);if(!r||!o)return false;if(r===o)return true;const i=es(o.replace(/^(?:[⏳✅]\s*)+/u,""));if(i&&r===i)return true;const a=rs(o,{expectedManagedTitle:o,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat});return !(!a||r!==a)||Boolean(n&&r===es(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.scheduleNextTitleUpdate(true),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(),this.scheduleNextTitleUpdate(true);}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(),this.scheduleNextTitleUpdate(true);}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),this.scheduleNextTitleUpdate(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===Dd?this.beginNetworkGeneration(n):t===Bd&&this.onAiComplete();}isUserAway(){const e=document.hidden,t=document.hasFocus(),n="visible"!==document.visibilityState;return e||!t||n}onVisibilityChange(){const e=this.isUserAway();e||this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"!==this.aiState||e||this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true),"completed"!==this.aiState||e||this.completionViewed||(this.completionViewed=true,this.updateTabName(true)),this.scheduleNextTitleUpdate(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.isRunning&&(this.updateTabName(true),this.scheduleNextTitleUpdate(true));}onWindowBlur(){this.scheduleNextTitleUpdate(true);}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,this.updateTabName(true),void this.scheduleNextTitleUpdate(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),this.scheduleNextTitleUpdate(true);}sendCompletionNotification(){if(this.stopNotificationPlayback(),this.settings.showNotification)try{const e=this.adapter.getName(),t=le("notificationTitle").replace("{site}",e),n=this.lastConversationTitle||rs(this.adapter.getConversationTitle?.(),{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})||le("notificationBody");ti.notify({title:t,message:n});}catch(e){console.error("[TabManager] 通知发送失败:",e);}this.settings.showNotification&&this.settings.notificationSound&&this.playNotificationSound(),this.settings.autoFocus&&ti.focusWindow();}playNotificationSound(){const e=this.settings.notificationSoundPreset||ao[0].id,t=ao.find(t=>t.id===e)||ao[0],n=ti.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 $k="gh-usage-monitor-style",_k="gh-usage-monitor-host",Ok={count:0,updatedAt:Date.now(),resetAt:Date.now()},zk=e=>e.replace(/[\u200B\u200C\u200D\uFEFF\u00A0]/g,"").replace(/\s+/g," ").trim(),Fk=/[\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g,Uk=/[A-Za-z0-9]/g,Hk=/[^\sA-Za-z0-9\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g;class Wk{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={...Ok};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=jw(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=_k),this.slot||(this.slot=document.createElement("div"),this.slot.className=`${_k}-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 Bw();return n.records[e]=t,await $w(n),t}(this.getRecordKey()),this.scheduleRender(0);});}ensureStyles(){if(document.getElementById($k))return;const e=document.createElement("style");e.id=$k,e.textContent=this.getUsageMonitorStyles(),document.head.appendChild(e);}ensureStylesForTarget(e){const t=e.getRootNode();t instanceof ShadowRoot&&(Cs.cssToShadow(t,this.getUsageMonitorStyles(),$k),this.injectedStyleRoots.add(t));}getUsageMonitorStyles(){return `\n .${_k} {\n box-sizing: border-box;\n width: 100%;\n max-width: 100%;\n margin: 0;\n pointer-events: auto;\n }\n\n .${_k}-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 .${_k} * {\n box-sizing: border-box;\n }\n\n .${_k} .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 .${_k}[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 .${_k} .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 .${_k} .gh-usage-monitor-title {\n font-weight: 600;\n letter-spacing: 0.01em;\n }\n\n .${_k} .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 .${_k} .gh-usage-monitor-count {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${_k} .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 .${_k}[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 .${_k} .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 .${_k} .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${_k} .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 .${_k} .gh-usage-monitor-control:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${_k}[data-theme="dark"] .gh-usage-monitor-reset {\n border-color: var(--gh-input-border, var(--gh-border, #333333));\n }\n\n .${_k}[data-theme="dark"] .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #262626);\n }\n\n .${_k} .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 .${_k} .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 .${_k}[data-theme="dark"] .gh-usage-monitor-progress {\n background: var(--gh-border, #333333);\n }\n\n .${_k}[data-level="warning"] .gh-usage-monitor-progress-bar {\n background: var(--gh-secondary, #34a853);\n }\n\n .${_k}[data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${_k}[data-level="danger"] .gh-usage-monitor-progress-bar {\n background: var(--gh-danger, #ef4444);\n }\n\n .${_k}[data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${_k}[data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${_k}[data-theme="dark"][data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${_k}[data-theme="dark"][data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${_k}[data-theme="dark"][data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${_k} .gh-usage-monitor-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 6px 12px;\n }\n\n .${_k} .gh-usage-monitor-item {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 10px;\n }\n\n .${_k} .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .${_k}[data-theme="dark"] .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${_k} .gh-usage-monitor-value {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${_k} .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 .${_k}[data-theme="dark"] .gh-usage-monitor-footnote {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n @media (max-width: 640px) {\n .${_k} .gh-usage-monitor-grid {\n grid-template-columns: 1fr;\n }\n }\n `}removeStyles(){document.getElementById($k)?.remove();for(const e of this.injectedStyleRoots)e.getElementById($k)?.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 Bw(),n=qw(t.records[e]);return t.records[e]||(t.records[e]=n,await $w(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=Cs.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=Cs.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=[Cs.closestComposed(e,"form"),t?Cs.closestComposed(t,"form"):null,this.findClosestCommonAncestor(e,t),Cs.closestComposed(e,'[role="form"]')].filter(Boolean),r=this.pickBestMountCandidate(n,e,t);if(r)return r;const o=[Cs.closestComposed(e,".chat-input-editor-container"),Cs.closestComposed(e,".chat-editor"),Cs.closestComposed(e,".input-area-container"),Cs.closestComposed(e,".input-area"),Cs.closestComposed(e,".composer"),Cs.closestComposed(e,".footer-input-wrap"),Cs.closestComposed(e,".input-container"),Cs.closestComposed(e,".editor-container"),Cs.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=Rw(e);if(!t)return;const n=await Bw();n.events=Pw([...n.events,t]),await $w(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 Bw(),n=qw(t.records[e]),r={count:n.count+1,updatedAt:Date.now(),resetAt:n.resetAt};return t.records[e]=r,await $w(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 (Cs.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?zk(e.value||""):zk(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=Cs.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=zk(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(Fk)||[]).length,n=(e.match(Uk)||[]).length,r=(e.match(Hk)||[]).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 jk=[/^\s*#{1,6}\s+\S/m,/^\s*```/m,/^\s*(?:>|>)\s+\S/m,/^\s*[-*]\s+\S/m,/^\s*\d+\.\s+\S/m],Gk=[/\*\*[^*]+\*\*/,/`[^`]+`/,/\[.+\]\(.+\)/],Qk=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],Vk=[/(^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$)/,/\\\([^\n]+?\\\)/],Kk="gh-user-query-markdown-style";function Zk(){return "undefined"==typeof window?"":window.__OPHEL_USER_QUERY_MARKDOWN_STYLES__||""}function Yk(e){const t=e.trim();return !!t&&(jk.some(e=>e.test(t))||Gk.some(e=>e.test(t))||function(e){const t=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(e);return Qk.some(e=>e.test(t))||Vk.some(e=>e.test(t))}(t))}class Xk{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=Cs.each(e,e=>{this.processQueryElement(e);},{shadow:true});const t=this.adapter.getSiteId();t!==ko&&t!==Io&&t!==Mo||this.startRescanTimer();}}injectGlobalStyles(){const e=this.getStyleText();let t=document.getElementById(Kk);t||(t=document.createElement("style"),t.id=Kk,document.head.appendChild(t)),t.textContent!==e&&(t.textContent=e);}injectStyleToShadowRoot(e){const t=this.getStyleText(),n=e.querySelector(`#${Kk}`);if(n)return n.textContent!==t&&(n.textContent=t),void this.injectedShadowRoots.add(e);const r=document.createElement("style");r.id=Kk,r.textContent=t,e.prepend(r),this.injectedShadowRoots.has(e)||(e.addEventListener("click",e=>this.handleCodeCopy(e)),this.injectedShadowRoots.add(e));}getStyleText(){return [nc(),Jl(),Zk()].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(()=>{Ed(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=Cs.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(!Yk(t))return;if(this.processedElements.get(e)===t)return;const n=tc(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),Ad(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(Kk);e&&e.remove(),this.codeCopyHandler&&(document.removeEventListener("click",this.codeCopyHandler,true),this.codeCopyHandler=null);}}let Jk={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},eT=null,tT=null;function nT(e){return e.content?.assistantMermaid??true}async function rT(e){const{adapter:t,settings:n}=e;if("fallback"!==t.getAssistantMermaidSupportMode())return Jk.assistantMermaidRenderer?.stop(),void(Jk.assistantMermaidRenderer=null);nT(n)?Jk.assistantMermaidRenderer?Jk.assistantMermaidRenderer.updateSettings(true):(tT||(tT=(async()=>{"fallback"===t.getAssistantMermaidSupportMode()&&nT(Ui())&&(Jk.assistantMermaidRenderer?Jk.assistantMermaidRenderer.updateSettings(true):Jk.assistantMermaidRenderer=new dk(t,true));})().finally(()=>{tT=null;})),await tT):Jk.assistantMermaidRenderer?.updateSettings(false);}function oT(e){const{adapter:t,settings:n,siteId:r}=e,o=pi(n,r),i=Uy({mode:o.mode,adapter:t,lightPresetId:o.lightStyleId||"google-gradient",darkPresetId:o.darkStyleId||"classic-dark",syncNativePageTheme:n.theme?.syncNativePageTheme??true,apply:true});return Jk.themeManager=i,i}async function iT(e){const{adapter:t,settings:n,siteId:r}=e,o=pi(n,r);if("system"===o.mode&&Jk.themeManager)return void(await Jk.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 Jk.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&&(Jk.themeManager&&Jk.themeManager.applyTheme(i),t&&"function"==typeof t.toggleTheme&&await t.toggleTheme(i));}function aT(e,t){switch(t){case yo:return e.content?.markdownFix??false;case Co:return e.aistudio?.markdownFix??false;case vo:return e.chatgpt?.markdownFix??false;default:return false}}function sT(e){const{adapter:t,settings:n,siteId:r}=e,o=t.getMarkdownFixerConfig(),i=aT(n,r);o&&i&&(Jk.markdownFixer=new Nk(o),Jk.markdownFixer.start(),console.warn(`[Ophel] MarkdownFixer started for ${t.getName()}`));}function lT(e){const{adapter:t,settings:n,siteId:r}=e,o=mi(n,r),i=bi(n,r),a=yi(n,r),s=a.enabled,l=vi(n,r),c=!!t.getCleanModeConfig()&&l.enabled;(o?.enabled||i?.enabled||s||c)&&(Jk.layoutManager=new Tk(t,o),o?.enabled&&Jk.layoutManager.apply(),i?.enabled&&Jk.layoutManager.updateUserQueryConfig(i),s&&Jk.layoutManager.updateZenMode(a),c&&Jk.layoutManager.updateCleanMode(true));}function cT(e){const{adapter:t,settings:n}=e;n.content&&(Jk.copyManager=new pk(n.content,t),n.content.formulaCopy&&Jk.copyManager.initFormulaCopy(),n.content.tableCopy&&Jk.copyManager.initTableCopy());}function dT(e){const{adapter:t,settings:n}=e;n.tab&&(Jk.tabManager=new Bk(t,n.tab),Jk.tabManager.start());}function uT(e){const{adapter:t,settings:n,siteId:r}=e;Jk.usageCounterManager=new Wk(t,n.usageMonitor,r),Jk.usageCounterManager.start();}function hT(e){const{settings:t,siteId:n}=e;n!==yo&&n!==wo||!t.content?.watermarkRemoval||(Jk.watermarkRemover=new Iu,Jk.watermarkRemover.start());}async function gT(e){const{adapter:t,settings:n}=e;if(n.readingHistory?.persistence){eT&&(clearTimeout(eT),eT=null);const e=e=>{Jk.readingHistoryManager||(Jk.readingHistoryManager=new Pk(t,e.readingHistory),Jk.readingHistoryManager.startRecording(),Jk.readingHistoryManager.cleanup());};if(await(xi||(xi=(async()=>{try{const e=await ti.storage.get(oi);if(void 0===e)return !1;const t="number"==typeof e?e:Number(e);return !Number.isFinite(t)||Date.now()-t<=5e3||(await ti.storage.remove(oi),!1)}catch(vT){return console.warn("[Ophel] Failed to consume clear all flag:",vT),false}})(),xi))||Ci())return void(eT=setTimeout(()=>{eT=null;const t=Ui();t.readingHistory?.persistence&&!Jk.readingHistoryManager&&e(t);},5e3));if(e(n),n.readingHistory.autoRestore){const{showToast:e}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Vi);return {showToast:e}},void 0);Jk.readingHistoryManager.restoreProgress(t=>e(t,3e3)).then(t=>{t&&e(le("restoredPosition"),2e3);});}Jk.readingHistoryManager.cleanup();}}function pT(e){const{adapter:t,settings:n,siteId:r}=e,o=fi(n,r);Jk.modelLocker=new qk(t,o),o.enabled&&o.keyword&&Jk.modelLocker.start();}function mT(e){const{adapter:t,settings:n}=e;Jk.scrollLockManager=new Dk(t,n);}function fT(e){const{adapter:t,settings:n}=e;Jk.userQueryMarkdownRenderer=new Xk(t,n.content?.userQueryMarkdown??true);}function bT(e){const{adapter:t,settings:n,siteId:r}=e;r===wo&&(Jk.policyRetryManager=new Rk(t,n.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3}));}const yT=Object.freeze(Object.defineProperty({__proto__:null,initAssistantMermaidRenderer:rT,initCopyManager:cT,initCoreModules:async function(e){return oT(e),setTimeout(()=>iT(e),1e3),sT(e),lT(e),cT(e),dT(e),hT(e),uT(e),await gT(e),pT(e),mT(e),fT(e),await rT(e),bT(e),Jk},initLayoutManager:lT,initMarkdownFixer:sT,initModelLocker:pT,initPolicyRetryManager:bT,initReadingHistoryManager:gT,initScrollLockManager:mT,initTabManager:dT,initThemeManager:oT,initUrlChangeObserver:function(e){const{adapter:t}=e;let n=window.location.href,r=window.location.pathname,i=null;const a=async()=>{const e=window.location.href;if(e===n)return;const a=n;n=e,window.dispatchEvent(new CustomEvent(zd,{detail:{href:e,previousHref:a}}));const s=window.location.pathname;s!==r&&(r=s,console.warn("[Ophel] URL changed, reinitializing modules..."),i&&(clearTimeout(i),i=null),Jk.readingHistoryManager&&(Jk.readingHistoryManager.stopRecording(),i=setTimeout(async()=>{i=null;const{showToast:e}=await o(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Vi);return {showToast:e}},void 0);if(!Ci()){await(Jk.readingHistoryManager?.restoreProgress(t=>e(t,3e3)))&&e(le("restoredPosition"),2e3);}Jk.readingHistoryManager?.startRecording();},1500)),window.dispatchEvent(new Event("gh-url-change")),Jk.tabManager&&(Jk.tabManager.resetConversationTitleCache(),[300,800,1500].forEach(e=>setTimeout(()=>Jk.tabManager?.updateTabName(true),e))),t.findTextarea(),Jk.usageCounterManager?.handleUrlChange(),Jk.modelLocker?.relock(300));};window.addEventListener("popstate",a),window.addEventListener("hashchange",a);const s=history.pushState,l=history.replaceState;history.pushState=function(...e){s.apply(this,e),a();},history.replaceState=function(...e){l.apply(this,e),a();},setInterval(a,1e3);},initUsageCounterManager:uT,initUserQueryMarkdownRenderer:fT,initWatermarkRemover:hT,subscribeModuleUpdates:function(e){const{adapter:t,siteId:n}=e;let r=Ui().language;Hi(e=>{e.language&&e.language!==r&&(r=e.language,ae(e.language),Jk.assistantMermaidRenderer?.refreshLocalizedTexts(),Jk.layoutManager?.refreshLocalizedTexts());const o=pi(e,n);o&&Jk.themeManager&&(Jk.themeManager.setNativeThemeOverrideEnabled(e.theme?.syncNativePageTheme??true),Jk.themeManager.setPresets(o.lightStyleId||"google-gradient",o.darkStyleId||"classic-dark"));const i=fi(e,n);i&&Jk.modelLocker&&Jk.modelLocker.updateConfig(i),e&&Jk.scrollLockManager&&Jk.scrollLockManager.updateSettings(e);const a=t.getMarkdownFixerConfig(),s=aT(e,n);a&&s?(Jk.markdownFixer||(Jk.markdownFixer=new Nk(a)),Jk.markdownFixer.start()):Jk.markdownFixer?.stop();const l=mi(e,n),c=bi(e,n),d=yi(e,n),u=d.enabled,h=vi(e,n),g=!!t.getCleanModeConfig()&&h.enabled;Jk.layoutManager?(Jk.layoutManager.updateConfig(l),Jk.layoutManager.updateUserQueryConfig(c),Jk.layoutManager.updateZenMode(d),Jk.layoutManager.updateCleanMode(g)):(l?.enabled||c?.enabled||u||g)&&(Jk.layoutManager=new Tk(t,l),l?.enabled&&Jk.layoutManager.apply(),c?.enabled&&Jk.layoutManager.updateUserQueryConfig(c),u&&Jk.layoutManager.updateZenMode(d),g&&Jk.layoutManager.updateCleanMode(true)),!e||n!==yo&&n!==wo||(e.content?.watermarkRemoval?(Jk.watermarkRemover||(Jk.watermarkRemover=new Iu),Jk.watermarkRemover.start()):Jk.watermarkRemover?.stop()),e?.tab&&(Jk.tabManager?Jk.tabManager.updateSettings(e.tab):(Jk.tabManager=new Bk(t,e.tab),Jk.tabManager.start())),e?.usageMonitor&&(Jk.usageCounterManager?Jk.usageCounterManager.updateSettings(e.usageMonitor):(Jk.usageCounterManager=new Wk(t,e.usageMonitor,n),Jk.usageCounterManager.start())),e?.readingHistory&&(Jk.readingHistoryManager?Jk.readingHistoryManager.updateSettings(e.readingHistory):e.readingHistory.persistence&&(Jk.readingHistoryManager=new Pk(t,e.readingHistory),Jk.readingHistoryManager.startRecording())),e?.content&&(Jk.copyManager?Jk.copyManager.updateSettings(e.content):(Jk.copyManager=new pk(e.content),e.content.formulaCopy&&Jk.copyManager.initFormulaCopy(),e.content.tableCopy&&Jk.copyManager.initTableCopy()),e.content.userQueryMarkdown?Jk.userQueryMarkdownRenderer?Jk.userQueryMarkdownRenderer.updateSettings(true):Jk.userQueryMarkdownRenderer=new Xk(t,true):Jk.userQueryMarkdownRenderer?.updateSettings(false)),rT({adapter:t,settings:e}).catch(e=>{console.error("[Ophel] Assistant Mermaid renderer update failed:",e);}),e?.geminiEnterprise&&n===wo&&Jk.policyRetryManager&&Jk.policyRetryManager.updateSettings(e.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3});});},syncHostThemeWithSettings:iT},Symbol.toStringTag,{value:"Module"})); })(__OphelGeminiWatermarkRemover);