// ==UserScript== // @name AI Chat Turbo Engine // @namespace https://cyojkoy.github.io/Payment/ // @version 0.23.9 // @description 跨平台 AI 对话加速:常驻统计 + 完整消息提取 + YAML 交接 + 多平台适配 + 长代码折叠 + 自适应脱水 + 推理强度记忆 + 元宝原子工具记忆 + 新对话快捷键覆盖 // @author Yoko // @updateURL https://cdn.jsdelivr.net/gh/CYoJkoY/Yoko-ScriptCat-Scripts@release/ai-chat-turbo-engine.user.js // @downloadURL https://ghfast.top/https://raw.githubusercontent.com/CYoJkoY/Yoko-ScriptCat-Scripts/release/ai-chat-turbo-engine.user.js // @match https://chatgpt.com/* // @match https://chat.openai.com/* // @match https://gemini.google.com/* // @match https://grok.com/* // @match https://x.com/i/grok* // @match https://chat.deepseek.com/* // @match https://copilot.com/* // @match https://copilot.microsoft.com/* // @match https://perplexity.ai/* // @match https://www.perplexity.ai/* // @match https://poe.com/* // @match https://doubao.com/* // @match https://www.doubao.com/* // @match https://yuanbao.tencent.com/* // @match https://chat.qwen.ai/* // @match https://qianwen.com/* // @match https://www.qianwen.com/* // @match https://chatglm.cn/* // @match https://chat.z.ai/* // @match https://zchat.z.ai/* // @run-at document-start // @early-start // @grant none // @noframes // @icon data:image/svg+xml;utf8, // @license MIT // ==/UserScript== "use strict"; (() => { // shared/userscript/globals.ts function isRecord(value) { return typeof value === "object" && value !== null; } function readUserscriptInfo(scope) { if (!("GM_info" in scope)) return null; const candidate = scope.GM_info; if (!isRecord(candidate)) return null; const script = candidate["script"]; if (!isRecord(script)) return null; const name = typeof script["name"] === "string" ? script["name"] : void 0; const version = typeof script["version"] === "string" ? script["version"] : void 0; return { script: { name, version } }; } // scripts/ai-chat-turbo-engine/src/config.ts var HUD_ID = "ai-turbo-extreme-hud"; var STYLE_ID = "ai-turbo-engine-styles"; var CODE_COLLAPSE_HEIGHT = 300; var CODE_PREVIEW_HEIGHT = 200; var DEFAULT_MESSAGE_LIMIT = 60; var MESSAGE_LIMIT_MIN = 10; var MESSAGE_LIMIT_MAX = 999; var SIDEBAR_PEEK_DELAY_MIN = 0; var SIDEBAR_PEEK_DELAY_MAX = 2e3; var SIDEBAR_PEEK_SHOW_DELAY_MS = 180; var SIDEBAR_PEEK_HIDE_DELAY_MS = 160; var LOAD_WARNING_RATIO = 0.7; var LOAD_RING_RADIUS = 16.2; var LOAD_RING_CIRCUMFERENCE = 2 * Math.PI * LOAD_RING_RADIUS; var TURN_MARKER_ATTRIBUTES = /* @__PURE__ */ new Set([ "data-testid", "data-test-id", "data-turn", "data-turn-key", "data-message-author-role", "data-message-role", "data-conversation-role", "data-role", "data-content-search-unit-key", "data-content-search-turn-key", "data-thread-find-target", "data-conversation-transcript", "data-user-message-bubble", "data-chatgpt-agent-turn-start", "data-app-shell-main-surface" ]); var CHATGPT_SHELL_ROOT_SELECTOR = '[data-app-shell-main-surface] [data-thread-find-target="conversation"]'; var CHATGPT_SHELL_TURN_SELECTOR = '[data-app-shell-main-surface] [data-thread-find-target="conversation"] [data-turn-key]'; var CHATGPT_TRANSCRIPT_ROOT_SELECTOR = "ol[data-conversation-transcript]"; var CHATGPT_TRANSCRIPT_MESSAGE_SELECTOR = "ol[data-conversation-transcript] > li[data-message-role]"; var CHATGPT_CODE_CARD_BOUNDARY_SELECTOR = [ "[data-turn-key]", '[data-testid^="conversation-turn-"]', "article[data-turn]", "section[data-turn]", 'li[data-message-role="assistant"]', '[data-message-author-role="assistant"]' ].join(", "); var CHATGPT_CODE_HEADER_MARKER_SELECTOR = [ ".code-block-decoration", '[data-testid*="code-block-header" i]', '[data-testid*="code-block-toolbar" i]', '[class*="code-block-header" i]', '[class*="code-header" i]', '[class*="code-toolbar" i]', 'button[aria-label*="copy code" i]', 'button[title*="copy code" i]', '[data-testid*="copy-code" i]', 'button[aria-label*="复制代码"]', 'button[title*="复制代码"]' ].join(", "); var CHATGPT_CODE_CARD_MAX_ANCESTORS = 10; var SEARCH_PREVIEW_LIMIT = 180; var SEARCH_LIMIT = 10; var STORAGE_KEY_POS = "ai_turbo_pill_pos"; var STORAGE_KEY_DOCK = "ai_turbo_hud_dock"; var STORAGE_KEY_CONFIG = "ai_turbo_engine_config"; var VIRTUAL_FILE_THRESHOLD = 1500; var COMPOSER_VISUAL_GAP = 48; var COMPOSER_VISUAL_MAX_DEPTH = 5; var STREAMING_IDLE_DELAY = 1500; var THROTTLE_INTERVAL = 80; var TEXT_INDEX_INTERVAL = 450; var TEXT_INDEX_FRAME_BUDGET = 8; var CODE_SCAN_INTERVAL = 250; var TURN_DISCOVERY_RETRY_INTERVAL = 1e3; var CODE_FENCE = "```"; var VF_TOKEN_START = "[[TURBO_VFILE_START:"; var VF_TOKEN_END = ":TURBO_VFILE_END]]"; var VF_REGEX = /\[\[TURBO_VFILE_START:([^|\r\n]+)\|(\d+)\|(\d+):TURBO_VFILE_END\]\]/; var HANDOFF_STORAGE_KEY = "ai_turbo_handoff_restore"; var TAKEOVER_INTENT_STORAGE_KEY = "ai_turbo_new_chat_takeover"; var PLAIN_HANDOFF_START = "[META]"; var PLAIN_HANDOFF_END = "[END]"; var PLAIN_HANDOFF_SECTIONS = [ "[META]", "[TASK]", "[DECISIONS]", "[PROGRESS]", "[ROLE]", "[CONTEXT]", "[OPEN_ISSUES]", "[KEY_ENTITIES]", "[HANDOFF_NOTES]", "[END]" ]; var PLAIN_HANDOFF_TOLERANCE = 1; var REASONING_SELECTOR = [ "model-thoughts", ".thoughts-container", ".thoughts-content", "[data-test-id*='thought' i]", "[data-testid*='thought' i]", "[data-testid*='reasoning' i]", "[data-testid*='thinking' i]", "[class*='reasoning' i]", "[class*='thinking' i]", "[class*='thought-process' i]", "[aria-label*='reasoning' i]", "[aria-label*='thinking' i]", "[aria-label*='思考']", "[aria-label*='推理']", "[data-type='reasoning']" ].join(", "); var STORAGE_KEY_REASONING = "ai_turbo_reasoning_memory"; var STORAGE_KEY_TOOL_MEMORY = "ai_turbo_tool_memory"; var STORAGE_KEY_YUANBAO_SELECTION = "ai_turbo_yuanbao_selection"; var YUANBAO_MODEL_TRIGGER_SELECTOR = "[data-thinking-mode-switcher-trigger]"; var YUANBAO_MODEL_ROW_SELECTOR = "[aria-label='选择模型']"; var YUANBAO_MODEL_MENU_SELECTOR = "[role='menu'][aria-label='模型列表']"; var YUANBAO_MODE_LABEL_SELECTOR = "[data-input-label='model']"; var REASONING_CONTROL_PATTERN = /深度思考|深度推理|思考|推理|思维链|thinking|reasoning|think harder|effort|智商|extended thinking/i; var REASONING_CONTROL_SELECTOR = [ "button", "[role='button']", "[role='switch']", "[role='checkbox']", "[role='radio']", "[role='menuitemradio']", "[role='menuitem']", "[role='option']", "[aria-pressed]", "[aria-checked]", "[data-state]" ].join(", "); var REASONING_MENU_SELECTOR = "[role='menu'], [role='listbox'], [role='dialog'], [role='radiogroup'], [data-radix-popper-content-wrapper], [data-floating-ui-portal]"; var CHOICE_OPTION_SELECTOR = "[aria-checked], [aria-selected], [role='menuitemradio'], [role='radio'], [role='option'], [role='menuitem'], button, a"; var CHOICE_RADIO_SELECTOR = "[aria-checked], [aria-selected], [role='menuitemradio'], [role='radio']"; var TOOL_TRIGGER_SELECTOR = '[data-new-input-control="add-tools-trigger"]'; var TOOL_TRIGGER_CONTAINER_SELECTOR = '[data-new-input-control="add-tools"]'; var ATOMIC_ACTIONS_SELECTOR = '[data-new-input-control="atomic-actions"]'; var ATOMIC_TOOL_ITEM_SELECTOR = `${ATOMIC_ACTIONS_SELECTOR} [data-application-id]`; var ATOMIC_TOOL_CHIP_SELECTOR = '[data-new-input-control="selected-atomic-action"][data-application-id]'; var ATOMIC_TOOL_MENU_SELECTOR = `${ATOMIC_ACTIONS_SELECTOR} [role='menu']`; var TOOL_POPUP_SELECTOR = [ "[role='menu']", "[role='listbox']", "[role='dialog']", "[role='radiogroup']", "[data-radix-popper-content-wrapper]", "[data-floating-ui-portal]" ].join(", "); var TOOL_ROW_SELECTOR = [ "[role='menuitemcheckbox']", "[role='menuitemradio']", "[role='checkbox']", "[role='option']", "[aria-checked]", "[aria-pressed]", "[aria-selected]", "[data-state='checked']", "[data-state='unchecked']", "button" ].join(", "); var TOOL_TOGGLE_ROW_SELECTOR = [ "[role='menuitemcheckbox']", "[role='menuitemradio']", "[role='checkbox']", "[role='option']", "[aria-checked]", "[aria-pressed]", "[aria-selected]", "[data-state='checked']", "[data-state='unchecked']" ].join(", "); function isToolControlElement(node) { if (!(node instanceof Element)) return false; return Boolean( node.closest(TOOL_TRIGGER_SELECTOR) || node.closest(TOOL_TRIGGER_CONTAINER_SELECTOR) || node.closest(ATOMIC_ACTIONS_SELECTOR) || node.closest(ATOMIC_TOOL_CHIP_SELECTOR) ); } var BLOCK_TEXT_TAGS = /* @__PURE__ */ new Set([ "ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "DD", "DIV", "DL", "DT", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HR", "LI", "MAIN", "NAV", "OL", "P", "SECTION", "TABLE", "TBODY", "TD", "TH", "THEAD", "TR", "UL" ]); var PLATFORMS = { chatgpt: { name: "ChatGPT", newChatShortcut: "/", hosts: ["chatgpt.com", "chat.openai.com"], /* * ChatGPT's sidebar id for the new chat button, declared here rather than * in the shared list because an element id is one site's own convention: * Z.ai reuses this exact id for its Home button, so a shared match would * navigate home instead of opening a conversation there. Keep it scoped * to this host so it can be dropped the day ChatGPT stops shipping it. */ newChatControlSelectors: ["#sidebar-new-chat-button"], shellTurnRoots: true, codeCardChrome: true, sidebar: { selectors: ["aside.app-shell-left-panel"], triggers: [ 'button[aria-label="显示侧边栏"]', 'button[aria-label*="Show sidebar" i]', 'button[aria-label*="Expand sidebar" i]' ], // The expanded panel is mounted but its scroller keeps an inline // display: none !important until the site opens it itself. reveal: ["#app-shell-sidebar > div:nth-child(2) > div:first-child"], // The collapsed rail mounts the expanded list behind an inline // display:none and its renderer writes that rule back on the next // commit, so a reveal alone loses the list again. The peek presses the // site's own expand control: the site then owns the opened state and // the rows keep their data and listeners. nativeExpand: { expand: 'button[aria-label="显示侧边栏"], button[aria-label*="Show sidebar" i], button[aria-label*="Expand sidebar" i]', collapse: 'button[aria-label="隐藏侧边栏"], button[aria-label*="Hide sidebar" i], button[aria-label*="Close sidebar" i]' }, // The rail host grows but the panel column keeps a collapsed width and // its own scroller clips the labels, so both are stretched with it. shells: ["#app-shell-sidebar", "#app-shell-sidebar > div:nth-child(2)"], peekWidth: 340, collapsedMaxWidth: 96 }, turnSelectorGroups: [ [CHATGPT_SHELL_TURN_SELECTOR], [CHATGPT_TRANSCRIPT_MESSAGE_SELECTOR], [ '[data-testid^="conversation-turn-"]', "article[data-turn]", "section[data-turn]" ], [ '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-message-role="user"]', '[data-message-role="assistant"]', '[data-role="user"]', '[data-role="assistant"]' ], [ '[data-content-search-unit-key$=":user"]', '[data-content-search-unit-key$=":assistant"]' ], ["[data-turn-key]"] ], turnSelectors: [ CHATGPT_SHELL_TURN_SELECTOR, CHATGPT_TRANSCRIPT_MESSAGE_SELECTOR, '[data-testid^="conversation-turn-"]', "article[data-turn]", "section[data-turn]", '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-message-role="user"]', '[data-message-role="assistant"]', '[data-role="user"]', '[data-role="assistant"]', '[data-content-search-unit-key$=":user"]', '[data-content-search-unit-key$=":assistant"]', "[data-turn-key]" ], userTurnSelectors: [ '[data-message-author-role="user"]', '[data-role="user"]', '[data-content-search-unit-key$=":user"]', '[data-user-message-bubble="true"]', '[data-testid="collapsible-user-message-root"]', '[data-testid*="user-message"]', '[class*="user-message"]' ], userContentSelectors: [ '[data-testid="collapsible-user-message-root"]', ".whitespace-pre-wrap", '[data-user-message-bubble="true"]', '[data-content-search-unit-key$=":user"]', '[data-message-author-role="user"]' ], codeSelectors: ["pre"], contentSelectors: [ ".markdown", ".prose", '[class*="markdown"]', ".whitespace-pre-wrap", '[data-content-search-unit-key$=":assistant"]', '[data-message-author-role="assistant"]', '[data-testid="message-content"]' ], inputSelectors: [ 'form[data-chatgpt-composer] [contenteditable="true"][role="textbox"]', 'form[data-chatgpt-composer] [contenteditable="true"]', '[data-chatgpt-composer] [contenteditable="true"]', 'div.ProseMirror[contenteditable="true"][role="textbox"]', "#prompt-textarea", 'textarea[name="prompt-textarea"]', 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea" ], sendButtonSelectors: [ 'form[data-chatgpt-composer] button[type="submit"]', 'form[data-chatgpt-composer] button[data-testid*="send" i]', 'form[data-chatgpt-composer] button[aria-label*="Send" i]', 'form[data-chatgpt-composer] button[aria-label*="发送"]', '[data-chatgpt-composer] button[data-testid*="send" i]', '[data-chatgpt-composer] button[aria-label*="Send" i]', 'button[data-testid="send-button"]', 'button[data-testid="fruitjuice-send-button"]', 'button[data-testid="composer-send-button"]', 'button[data-testid*="send-button" i]', 'button[data-testid*="send" i]', 'button[aria-label="Send prompt"]', 'button[aria-label*="Send prompt" i]', 'button[aria-label*="Send message" i]', 'button[aria-label*="Send" i]', 'button[aria-label*="发送"]', 'button[title*="Send" i]', 'button[type="submit"]' ] }, gemini: { name: "Gemini", newChatShortcut: "/app", hosts: ["gemini.google.com"], nativeTurnRoots: true, quietMotion: true, sidebar: { selectors: ["bard-sidenav", ".bard-sidenav", "side-navigation"], triggers: [ '[data-test-id="side-nav-sparkle-button"]', '[data-test-id="side-nav-menu-button"]', ".side-nav-menu-button", 'button[aria-label*="打开边栏"]', 'button[aria-label*="收起边栏"]', 'button[aria-label*="侧边栏"]' ], // Gemini builds its history rows only after the native open control is // pressed; a wider collapsed rail shows the labels but no rows. nativeExpand: { expand: 'button[aria-label*="打开边栏"], button[aria-label*="Open sidebar" i]', collapse: 'button[aria-label*="关闭边栏"], button[aria-label*="Close sidebar" i]' }, // The history container and its scrollport are pinned to the collapsed // width; the native open control alone leaves both at the old size. shells: [ "bard-sidenav", ".sidenav-with-history-container", ".overflow-container" ], // Matches the width the site paints after its own open control runs. // A narrower cap leaves the pointer band short while the panel animates // in, so a cursor already over the visible column reads as outside it. peekWidth: 288, collapsedMaxWidth: 96 }, turnSelectorGroups: [ ["user-query", "model-response"], ['[data-test-id="user-query"]', '[data-test-id="model-response"]'], [ ".user-query", ".model-response", ".user-query-container", ".model-response-container" ] ], turnSelectors: [ "user-query", "model-response", '[data-test-id="user-query"]', '[data-test-id="model-response"]', ".user-query", ".model-response", ".user-query-container", ".model-response-container" ], userTurnSelectors: [ "user-query", '[data-test-id="user-query"]', ".user-query", ".user-query-container" ], codeSelectors: ["code-block", "pre"], contentSelectors: [ ".query-text", ".user-query-text", "[class*='query-content']", ".model-response-text", "message-content", ".message-content", ".markdown", ".md-content", ".response-content" ], inputSelectors: [ "rich-textarea .ql-editor", "rich-textarea div[contenteditable='true']", ".rich-textarea div[contenteditable='true']", "div[contenteditable='true'][role='textbox']", "div[contenteditable='true']", "textarea" ], sendButtonSelectors: [ "button.send-button", 'button[aria-label*="Send message"]', 'button[aria-label*="发送消息"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]', 'button[aria-label*="提交"]', ".send-button-container button", "rich-textarea + * button" ] }, grok: { name: "Grok", newChatShortcut: "/", hosts: ["grok.com"], hostPaths: { "x.com": "/i/grok" }, sidebar: { selectors: ["#app-sidebar", 'aside[aria-label="应用导航"]'], triggers: ['button[aria-label="切换侧边栏"]'], // Grok keeps a zero-width slot until its own toggle runs, and only the // expanded state renders the history rows. The peek presses that toggle // and presses it again on leave. The rail overlays the chat column // instead of pushing it, so no negative margin is needed. nativeExpand: { expand: 'button[aria-label="切换侧边栏"]', collapse: 'button[aria-label="切换侧边栏"]' }, peekWidth: 254, collapsedMaxWidth: 96 }, turnSelectors: [ 'div[data-testid*="message-container"]', 'div[data-testid*="conversation-turn"]', 'div[class*="message-bubble"]' ], codeSelectors: ["pre"], contentSelectors: ['div[class*="message-content"]', 'div[dir="auto"]'], inputSelectors: ["textarea", 'div[contenteditable="true"]'], sendButtonSelectors: [ 'button[aria-label*="Grok"]', 'button[type="submit"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]' ] }, deepseek: { name: "DeepSeek", newChatShortcut: "/", hosts: ["chat.deepseek.com"], /* * DeepSeek renders the new chat button as a bare div with no role, * aria-label, title or text at all, so no shared heuristic and no label * pass can name it. A trusted `click()` on it does open a blank * conversation, but a synthetic click, a synthetic pointer sequence and * a synthetic keypress were each measured to do nothing, so the route * reset below is the only path the engine can drive itself. */ blankRouteReset: true, sidebar: { selectors: [ "div.b8812f16.a2f3d50e", // Fallbacks for a hash rotation. The rail is the second column of the // app row and the only column that owns a direct ds-scroll-area child. // A bare nth-child path used to match the floating toolbar instead, // which is 114x40 and would have been widened as if it were the rail. // The loose variant also caught a transcript body and the small // scroller next to a message, so it also requires the rail's own // buttons: the toolbar and the chat column have none of both. "#root > div > div > div > div:nth-child(2):has(> .ds-scroll-area)", "#root div:has(> .ds-scroll-area):has(.ds-button):not(.ds-scroll-area):not(.ds-markdown):not(:has(textarea))" ], triggers: [ ".ca6d4be1 .ds-button", '#root div[role="button"][aria-label*="边栏"]', '#root > div > div > div > div > div:first-child [role="button"]' ], // The compact top bar is drawn over the hidden rail; once the rail is // revealed the bar covers its logo and would swallow the first presses. suppress: [".ca6d4be1"], // The site keeps the whole rail at display: none, so the peek has to // bring it back and cancel the full native width with a fixed margin. revealRail: true, shift: -261, peekWidth: 261, collapsedMaxWidth: 96 }, turnSelectors: [ ".ds-message", "div[data-um-id]", "div.dad65929", "div._4f9bf79", "div.d29f3d7d", '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-role="user"]', '[data-role="assistant"]' ], userTurnSelectors: [ '[data-message-author-role="user"]', '[data-role="user"]', "div[data-um-id]", "div.d29f3d7d", '[data-testid*="user-message"]', '[class*="user-message"]' ], userContentSelectors: [ "._9663006 .fbb737a4", ".ds-markdown", "div[data-um-id]", '[data-testid*="user-message"]', '[class*="user-message"]' ], codeSelectors: ["pre", "code-block"], contentSelectors: [ ".ds-markdown", ".markdown", ".prose", '[class*="markdown"]', '[class*="answer"]' ], inputSelectors: [ "#chat-input", 'textarea[data-testid="chat-input"]', 'textarea[placeholder*="Send a message" i]', "textarea[placeholder]", 'div[contenteditable="true"][role="textbox"]', "textarea", '[contenteditable="true"]' ], sendButtonSelectors: [ 'button[data-testid="send-button"]', 'button[aria-label="Send message"]', 'button[data-testid*="send"]', 'button[type="submit"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]' ] }, copilot: { name: "Microsoft Copilot", newChatShortcut: "/", hosts: ["copilot.com", "copilot.microsoft.com"], // The rail is a Fluent NavDrawer that the site widens itself. Its width // rule sits in the `application` cascade layer with !important, so the // stylesheet override joins the site's first layer instead. The rail // stays mounted and keeps its own listeners while peeking. Its history // list is only rendered once the drawer's own control opens it, so the // peek presses that control instead of leaving an empty wide column. sidebar: { selectors: [ 'div.fai-CopilotNavDrawer[role="navigation"]', 'div.fui-NavDrawer[role="navigation"]' ], triggers: [ '[data-testid="nav-toggle-button"]', 'button[aria-label="展开边栏"]', 'button[aria-label="折叠边栏"]', 'button[aria-label*="Expand sidebar" i]', 'button[aria-label*="Collapse sidebar" i]' ], nativeExpand: { expand: 'button[aria-label="展开边栏"], button[aria-label*="Expand sidebar" i]', collapse: 'button[aria-label="折叠边栏"], button[aria-label*="Collapse sidebar" i]' }, peekWidth: 256, collapsedMaxWidth: 96 }, turnSelectors: [ "div.fai-UserMessage", "div.fai-CopilotMessage" ], userTurnSelectors: [ "div.fai-UserMessage" ], userContentSelectors: [ 'div.fai-UserMessage [data-testid="chatOutput"]', 'div.fai-UserMessage [class*="user-message"]' ], codeSelectors: ["pre"], contentSelectors: [ ".fai-CopilotMessage__content", ".markdown", ".prose", ".ac-textBlock" ], inputSelectors: [ 'span.fai-EditorInput__input[role="textbox"]', 'span.fai-EditorInput__input[contenteditable="true"]', 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea[placeholder]", "textarea" ], sendButtonSelectors: [ 'button[aria-label="发送"]', "button.fai-SendButton", 'button[aria-label*="Send" i]', 'button[aria-label*="发送"]', 'button[data-testid*="send"]', 'button[type="submit"]' ] }, perplexity: { name: "Perplexity", newChatShortcut: "/", hosts: ["perplexity.ai", "www.perplexity.ai"], sidebar: { selectors: ["div.w-sideBarWidth"], triggers: [ 'button[aria-label="展开侧边栏"]', 'button[aria-label="打开侧边栏"]', 'button[aria-label*="Expand sidebar" i]', 'button[aria-label*="Open sidebar" i]' ], // Perplexity mounts the session list only after its own control opens // the column; a widened shell keeps the compact markup and shows just // the navigation rows. Its control ignores scripted presses in the // builds that were measured, so the press is best effort: when the site // honours it the thread titles appear, and when it does not the rail // still widens without fighting the page. nativeExpand: { expand: 'button[aria-label="展开侧边栏"], button[aria-label*="Expand sidebar" i]', collapse: 'button[aria-label="收起侧边栏"], button[aria-label*="Collapse sidebar" i]' }, // Measured again on the live site: the control stays closed after a // scripted click, so a peek that only pressed it left the rail at 56px // and did nothing. The CSS widening stays the visible path here, and the // press stays best effort for the builds that do honour it. nativeOnly: false, peekWidth: 240, collapsedMaxWidth: 88 }, turnSelectors: [ '[data-testid="chat-message"]', '[data-testid*="chat-message"]', '[data-message-author-role="user"]', '[data-message-author-role="assistant"]' ], userTurnSelectors: [ '[data-testid*="user-message"]', '[data-message-author-role="user"]', '[class*="user-message"]', '[class*="human"]' ], userContentSelectors: [ '[data-testid*="user-message"]', '[class*="user-message"]', ".whitespace-pre-wrap" ], codeSelectors: ["pre"], contentSelectors: [ ".prose", ".markdown", '[class*="prose"]', '[class*="message-content"]' ], inputSelectors: [ "textarea[placeholder]", 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea" ], sendButtonSelectors: [ 'button[data-testid*="send"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]', 'button[type="submit"]' ] }, poe: { name: "Poe", newChatShortcut: "/", hosts: ["poe.com"], sidebar: { selectors: ['aside[class*="SidebarLayout_sidebar"]'], triggers: [ 'button[aria-label="切换侧边栏折叠"]', 'button[aria-label*="Toggle sidebar" i]' ], // Poe's row wrapper keeps the rail in a flex row that clips overflow, // so the growth is cancelled by a fixed margin instead of a // measurement. shift: -180, // The rail only renders its conversation list after the site's own // toggle runs; widening the shell alone leaves the navigation icons. nativeExpand: { expand: 'button[aria-label="切换侧边栏折叠"], button[aria-label*="Toggle sidebar" i]', collapse: 'button[aria-label="切换侧边栏折叠"], button[aria-label*="Toggle sidebar" i]' }, peekWidth: 248, collapsedMaxWidth: 88 }, turnSelectors: [ ".Message", ".ChatMessage", '[data-message-author-role="user"]', '[data-message-author-role="assistant"]' ], userTurnSelectors: [ '[data-message-author-role="user"]', '[data-testid*="user-message"]', '[class*="UserMessage"]', '[class*="humanMessage"]' ], userContentSelectors: [ '[data-testid*="user-message"]', '[class*="UserMessage"]', ".Message" ], codeSelectors: ["pre"], contentSelectors: [ ".markdown", ".MessageContent", '[class*="messageContent"]', '[class*="message-content"]' ], inputSelectors: [ "textarea[placeholder]", 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea" ], sendButtonSelectors: [ 'button[data-testid*="send"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]', 'button[type="submit"]' ] }, doubao: { name: "Doubao", newChatShortcut: "/chat/", hosts: ["doubao.com", "www.doubao.com"], sidebar: { selectors: ["nav.panel-fvxXfj", "#chat-route-main nav"], triggers: [ 'button[aria-label="显示侧栏"]', 'button[aria-label="收起侧栏"]', "[data-sidebar-hover-trigger]" ], // The rail stays in the DOM at full width, slid out of its zero-width // column, so the peek has to undo the transform, the transparency and // the clip on that column. revealRail: true, peekWidth: 280, collapsedMaxWidth: 96 }, turnSelectors: [ '[data-testid="send_message"]', '[data-testid="receive_message"]', '[data-testid="message_text_content"]', '[data-testid="message_content"]', '[data-testid*="message_content"]', '[data-message-author-role="user"]', '[data-message-author-role="assistant"]' ], userTurnSelectors: [ '[data-testid="send_message"]', '[data-testid*="user-message"]', '[data-message-author-role="user"]', '[data-message-role="user"]', '[data-role="user"]', '[class*="user-message"]' ], userContentSelectors: [ '[data-testid="message_text_content"]', '[data-testid="message_content"]', '[data-testid*="user-message"]', '[class*="user-message"]' ], codeSelectors: ["pre"], contentSelectors: [ '[data-testid="message_text_content"]', '[data-testid="message_content"]', '[data-testid*="message_content"]', ".markdown", '[class*="message-content"]' ], inputSelectors: [ '[data-testid="chat_input_input"]', "#chat-input", "textarea[placeholder]", 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea" ], sendButtonSelectors: [ '[data-testid="chat_input_send_button"]', 'button[data-testid*="send"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]', 'button[type="submit"]' ] }, yuanbao: { name: "Tencent Yuanbao / 腾讯元宝", newChatShortcut: "/chat/", hosts: ["yuanbao.tencent.com"], supportsToolMemory: true, /* * Yuanbao wraps its new chat control in a `div[role="button"]` and only * names it through `aria-label`, so the shared `button[aria-label*=...]` * heuristics miss it. The entry is mounted inside the rail only once the * history list has loaded: a collapsed rail keeps the skeleton and no * entry at all, so the shortcut falls back to the `/chat/` route then. * * The fallback route is not a blank conversation: `/chat/`, `/chat/new` * and `/chat?projectId=` each redirect to the most recent conversation, * so a route reset would silently reopen it. The site's own control is * therefore the only reliable path, and it does work from a script: a * plain `.click()` on this element resets the conversation in the store * and pushes the blank route, verified end to end with a real keyboard * from inside a loaded conversation. The control looks inert on a tab * that is already blank, because there is nothing left to reset, which * is what made earlier probing read it as dead. */ newChatControlSelectors: [".yb-new-chat-entry__item"], sidebar: { selectors: [".yb-nav__content-wrapper"], triggers: [ '[aria-label="打开侧栏"]', '.yb-nav [aria-label="收起侧栏"]', '.yb-nav [data-testid*="sidebar"]' ], // Yuanbao hides the whole wrapper with a transform and visibility on a // layer whose width is already laid out, so nothing has to be shifted. // The hidden wrapper only carries a skeleton: the history list is // mounted once the site's own trigger runs, so revealRail keeps showing // the layer while nativeExpand asks the site for the real rows. revealRail: true, nativeExpand: { expand: '[aria-label="打开侧栏"]', collapse: '[aria-label="收起侧栏"]' }, peekWidth: 260, collapsedMaxWidth: 96 }, turnSelectors: [ ".agent-chat__list__item--human", ".agent-chat__list__item--ai", '[data-message-author-role="user"]', '[data-message-author-role="assistant"]' ], userTurnSelectors: [ ".agent-chat__list__item--human", ".agent-chat__bubble--human", '[data-message-author-role="user"]', '[data-role="user"]' ], userContentSelectors: [ ".agent-chat__bubble--human .hyc-content-text", ".agent-chat__bubble--human .agent-chat__bubble__content", ".agent-chat__bubble__content", '[data-message-author-role="user"]' ], codeSelectors: ["pre"], contentSelectors: [ ".hyc-common-markdown-style", ".hyc-content-md-done", ".hyc-content-md", ".agent-chat__speech-text", ".agent-chat__bubble__content", ".hyc-content-text", '[data-message-author-role="assistant"]' ], inputSelectors: [ '.agent-dialogue__content--common__input .ql-editor[contenteditable="true"]', '#search-bar .ql-editor[contenteditable="true"]', '.ql-editor[contenteditable="true"]', 'div[contenteditable="true"][role="textbox"]', "textarea" ], sendButtonSelectors: [ "#yuanbao-send-btn", '.agent-dialogue__content--common__input button[type="submit"]', 'button[aria-label*="发送"]', 'button[aria-label*="Send"]', 'button[type="submit"]' ] }, qwen: { name: "Qwen Chat", newChatShortcut: "/", hosts: ["chat.qwen.ai"], sidebar: { selectors: ["#sidebar.sidebar"], triggers: [ 'button[aria-label="切换侧边栏"]', 'button[aria-label="展开侧边栏"]', 'button[aria-label*="sidebar" i]' ], // Qwen unmounts its history list when the rail collapses: the 60px // rail keeps only two icon buttons, so widening that box shows an empty // panel. The peek presses the site's own toggle, which renders the // rows, and presses the same toggle on leave. nativeExpand: { expand: 'button[aria-label="切换侧边栏"], button[aria-label="展开侧边栏"], button[aria-label*="Toggle sidebar" i]', collapse: 'button[aria-label="切换侧边栏"], button[aria-label="收起侧边栏"], button[aria-label*="Toggle sidebar" i]' }, peekWidth: 240, collapsedMaxWidth: 96 }, turnSelectors: [ ".chat-user-message-container", ".chat-user-message", '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-message-author="user"]', '[data-message-author="assistant"]', '[data-role="user"]', '[data-role="assistant"]', '[data-testid="chat-message"]', '[class*="questionItem"]', '[class*="answerItem"]' ], userTurnSelectors: [ ".chat-user-message-container", ".chat-user-message", '[data-message-author-role="user"]', '[data-message-author="user"]', '[data-role="user"]', '[data-testid="user-message"]', '[class*="questionItem"]', '[class*="user-message"]' ], userContentSelectors: [ ".chat-user-message", ".chat-user-message-container", '[class*="questionItem"]', '[data-message-author-role="user"]', '[data-message-author="user"]', '[data-role="user"]', ".whitespace-pre-wrap" ], codeSelectors: ["pre"], contentSelectors: [ ".markdown-root", ".markdown-body", ".tongyi-markdown", ".markdown", ".prose", '[class*="answerItem"]', '[data-message-author-role="assistant"]', '[data-message-author="assistant"]', '[data-role="assistant"]' ], inputSelectors: [ "textarea#chat-input", '#chat-input[contenteditable="true"]', "textarea.message-input-textarea", 'textarea[placeholder*="Ask Qwen" i]', 'textarea[placeholder*="message" i]', '[contenteditable="true"][role="textbox"]', "textarea", '[contenteditable="true"]' ], sendButtonSelectors: [ ".message-input-right-button-send", 'button[data-testid="send-button"]', 'button[aria-label*="Send"]', 'button[aria-label*="发送"]', 'button[type="submit"]' ] }, qianwen: { name: "Qianwen / 千问", newChatShortcut: "/chat/", hosts: ["qianwen.com", "www.qianwen.com"], sidebar: { selectors: ["aside#new-nav-tab-wrapper"], triggers: [ 'button[aria-label="收起侧边栏"]', '[data-icon-type="qwpcicon-sidebarRight"]', 'button[aria-label*="侧边栏"]' ], // Qianwen collapses the aside to w-0 and keeps the panel absolutely // positioned beside it; the fixed margin keeps the chat column's // measurements untouched. shift: -240, peekWidth: 240, collapsedMaxWidth: 8 }, turnSelectors: [ '[class*="questionItem"]', '[class*="answerItem"]', '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-message-author="user"]', '[data-message-author="assistant"]', '[data-role="user"]', '[data-role="assistant"]' ], userTurnSelectors: [ '[class*="questionItem"]', '[data-message-author-role="user"]', '[data-message-author="user"]', '[data-role="user"]', '[class*="user-message"]' ], userContentSelectors: [ '[class*="questionItem"]', ".bubble-uo23is", '[data-message-author-role="user"]', '[data-message-author="user"]', '[data-role="user"]' ], codeSelectors: ["pre"], contentSelectors: [ ".tongyi-markdown", ".markdown-body", ".markdown", ".prose", '[class*="answerItem"]', '[data-message-author-role="assistant"]', '[data-message-author="assistant"]', '[data-role="assistant"]' ], inputSelectors: [ "textarea#chat-input", "textarea.message-input-textarea", '#chat-input[contenteditable="true"]', 'textarea[placeholder*="问" i]', 'textarea[placeholder*="消息" i]', '[contenteditable="true"][role="textbox"]', "textarea", '[contenteditable="true"]' ], sendButtonSelectors: [ ".message-input-right-button-send", 'button[data-testid="send-button"]', 'button[aria-label*="发送"]', 'button[aria-label*="Send"]', 'button[type="submit"]' ] }, glm: { name: "ChatGLM / 智谱清言", newChatShortcut: "/", hosts: ["chatglm.cn"], sidebar: { selectors: ["aside.el-aside.aside-container"], triggers: [".aside-header .operation-btn"], // The header holds two controls with the same class: the search button // sits first and the collapse toggle second, so pressing the first // painted match opened a search box and left the rail collapsed. The // history rows stay at zero height until that toggle runs. nativeExpand: { expand: ".aside-header .btn-area .operation-btn:not(.search-btn)", collapse: ".aside-header .btn-area .operation-btn:not(.search-btn)" }, // The class carries two controls and the site swaps their handlers as // the panel opens. Widening the rail is the path that was verified here // (40 -> 260 with 40 history rows), so the peek keeps writing geometry // and treats the press as best effort rather than depending on it. nativeOnly: false, peekWidth: 260, collapsedMaxWidth: 88 }, turnSelectors: [ ".question-txt.dots", '[data-message-author="user"]', '[data-message-author="assistant"]', '[data-message-author-role="user"]', '[data-message-author-role="assistant"]', '[data-role="user"]', '[data-role="assistant"]', ".role-user", ".role-assistant", ".message-user", ".message-assistant" ], userTurnSelectors: [ ".question-txt.dots", '[data-message-author="user"]', '[data-message-author-role="user"]', '[data-role="user"]', ".role-user", ".message-user", '[data-testid*="user-message"]' ], userContentSelectors: [ ".question-txt.dots", ".message-user .markdown-body", ".message-user .markdown", ".role-user", ".message-user", '[data-message-author="user"]', '[data-role="user"]' ], codeSelectors: ["pre"], contentSelectors: [ ".role-assistant .markdown-body", ".message-assistant .markdown-body", ".markdown-body", ".markdown", ".prose", '[class*="markdown"]', '[class*="answer"]', '[data-message-author="assistant"]', '[data-role="assistant"]' ], inputSelectors: [ "#chat-input", 'textarea[placeholder*="请输入"]', 'textarea[placeholder*="消息"]', 'div[contenteditable="true"][role="textbox"]', 'div[contenteditable="true"]', "textarea" ], sendButtonSelectors: [ 'button[data-testid="send-button"]', 'button[aria-label*="发送"]', 'button[aria-label*="Send"]', 'button[type="submit"]' ] }, zai: { name: "Z.ai (GLM)", newChatShortcut: "/", // Z.ai serves the same chat app from both hosts: the sidebar markup and the // route to a blank conversation are identical, only the origin differs. hosts: ["chat.z.ai", "zchat.z.ai"], /* * The landing route is the new conversation and the composer on it, and * the draft lives in `chat-input-` rather than in the textarea: a reload * alone restores the typed text, so the key has to go first. The site * renders no new chat control at all, which leaves this reset as the only * route to a blank conversation. */ blankRouteReset: true, draftStorageKeys: ["chat-input-", "chat-input"], sidebar: { selectors: ["#sidebar"], triggers: ['button[aria-label="切换侧边栏"]'], // Z.ai renders the row actions (rename, delete, pin) from its expanded // state only; a widened collapsed rail keeps the compact row markup and // loses those buttons. The peek therefore presses the site's own toggle // and lets the site lay the panel out, which is the same 238px column a // real press produces. nativeExpand: { expand: 'button[aria-label="切换侧边栏"]', collapse: 'button[aria-label="切换侧边栏"]' }, peekWidth: 238, collapsedMaxWidth: 88 }, turnSelectors: [ ".chat-user", ".chat-assistant", '[data-message-author="user"]', '[data-message-author="assistant"]', '[data-role="user"]', '[data-role="assistant"]', ".message-user", ".message-assistant", ".role-user", ".role-assistant" ], userTurnSelectors: [ ".chat-user", '[data-message-author="user"]', '[data-role="user"]', ".message-user", ".role-user", '[data-testid="user-message"]' ], userContentSelectors: [ ".chat-user .flex.justify-end.pb-1", '[data-message-author="user"]', '[data-role="user"]', ".chat-user", ".message-user", ".role-user" ], codeSelectors: ["pre"], contentSelectors: [ ".chat-assistant .markdown-body", ".chat-assistant .markdown-root", ".chat-assistant", ".markdown-body", ".markdown-root", ".markdown", ".prose", '[class*="markdown"]', '[data-message-author="assistant"]', '[data-role="assistant"]', ".message-assistant", ".role-assistant" ], inputSelectors: [ 'div[contenteditable="true"]#chat-input', 'div[contenteditable="true"][data-testid*="input"]', "textarea#chat-input", 'textarea[placeholder="Send a Message"]', 'textarea[placeholder*="message" i]', 'div[contenteditable="true"][role="textbox"]', "textarea", '[contenteditable="true"]' ], sendButtonSelectors: [ 'button[type="submit"]', 'button[aria-label="Send"]', 'button[data-testid="send-button"]', 'button[aria-label*="send" i]', 'button[aria-label*="发送"]' ] } }; var PLATFORM_ENTRIES = Object.entries(PLATFORMS); function hostnameMatches(hostname, domains) { return domains.some( (domain) => hostname === domain || hostname.endsWith("." + domain) ); } function findPlatformForLocation(hostname, pathname) { const host = hostname.toLowerCase(); const path = pathname || "/"; const declaresHost = (declared) => declared.some((candidate) => candidate.toLowerCase() === host); for (const [, platform] of PLATFORM_ENTRIES) { for (const [suffix, prefix] of Object.entries(platform.hostPaths ?? {})) { if (suffix.toLowerCase() === host && path.startsWith(prefix)) { return platform; } } if (declaresHost(platform.hosts)) { return platform; } } return null; } function buildPlatformMatchPatterns() { const patterns = []; const seen = /* @__PURE__ */ new Set(); const add = (pattern) => { if (seen.has(pattern)) return; seen.add(pattern); patterns.push(pattern); }; for (const [, platform] of PLATFORM_ENTRIES) { for (const host of platform.hosts) add(`https://${host}/*`); for (const [host, prefix] of Object.entries(platform.hostPaths ?? {})) { add(`https://${host}${prefix}*`); } } return patterns; } var PLATFORM_MATCH_PATTERNS = buildPlatformMatchPatterns(); // scripts/ai-chat-turbo-engine/src/core/diagnostics.ts var REPORT_LIMIT = 50; var reported = /* @__PURE__ */ new Set(); function reportRecoverableError(scope, error) { const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error); const key = `${scope}\0${detail}`; if (reported.has(key) || reported.size >= REPORT_LIMIT) return; reported.add(key); console.warn(`[AI Chat Turbo] ${scope} skipped: ${detail}`); } // scripts/ai-chat-turbo-engine/src/core/text.ts var TRANSCRIPT_IGNORED_SELECTORS = [ REASONING_SELECTOR, ".ai-turbo-chat-file-row", ".ai-turbo-chat-capsule", ".ai-turbo-code-bar", "#ai-turbo-vf-tray", "#ai-turbo-vf-preview-modal", "button", "[role='toolbar']", "script", "style", "svg", "[hidden]" ].join(", "); var BLOCK_TEXT_LOCAL_NAMES = new Set( Array.from(BLOCK_TEXT_TAGS, (tag) => tag.toLowerCase()) ); var TRANSCRIPT_IGNORED_LOCAL_NAMES = /* @__PURE__ */ new Set([ "button", "model-thoughts", "script", "style", "svg" ]); function normalizeText(sourceText) { return String(sourceText || "").replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim(); } function escapeHtml(text) { return String(text || "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function fastCountLines(text) { if (!text) return 0; let count = 1; for (let i = 0; i < text.length; i++) { if (text.charCodeAt(i) === 10) count++; } return count; } function matchesReasoningElement(element) { if (!(element instanceof Element)) return false; try { return element.matches(REASONING_SELECTOR); } catch (error) { reportRecoverableError("match reasoning element", error); return false; } } function isReasoningElement(element) { if (!(element instanceof Element)) return false; try { return matchesReasoningElement(element) || Boolean(element.closest(REASONING_SELECTOR)); } catch (error) { reportRecoverableError("resolve reasoning ancestor", error); return false; } } function elementToPlainText(rootElement) { if (!(rootElement instanceof Element) || matchesReasoningElement(rootElement)) { return ""; } const chunks = []; const preservedCodeBlocks = []; function walk(node) { if (node.nodeType === Node.TEXT_NODE) { const value = node.nodeValue; if (value) chunks.push(value); return; } if (!(node instanceof Element)) { for (const child of node.childNodes) walk(child); return; } const tag = node.localName; if (node !== rootElement) { if (TRANSCRIPT_IGNORED_LOCAL_NAMES.has(tag) || node.hasAttribute("hidden")) { return; } try { if (node.matches(TRANSCRIPT_IGNORED_SELECTORS)) return; } catch (error) { reportRecoverableError("test ignored transcript selectors", error); } } if (tag === "br") { chunks.push("\n"); return; } if (tag === "pre") { const codeText = node.textContent || ""; const codeChild = node.querySelector("code"); const codeClasses = [ node.className || "", codeChild?.className || "", node.getAttribute("data-language") || "", codeChild?.getAttribute("data-language") || "", codeChild?.getAttribute("lang") || "" ].join(" "); const languageMatch = /language-([a-z0-9+#.-]+)/i.exec(codeClasses); const language = languageMatch ? (languageMatch[1] ?? "text").toLowerCase() : "text"; const token = `TURBO_CODE_${preservedCodeBlocks.length}`; preservedCodeBlocks.push({ token, codeText, language }); chunks.push(` ${CODE_FENCE}${language} ${token} ${CODE_FENCE} `); return; } const isBlock = BLOCK_TEXT_LOCAL_NAMES.has(tag); if (isBlock) chunks.push("\n"); for (const child of node.childNodes) walk(child); if (isBlock) chunks.push("\n"); } walk(rootElement); const text = normalizeText(chunks.join("")); if (preservedCodeBlocks.length === 0) return text; return text.replace(/\uE000TURBO_CODE_(\d+)\uE001/g, (token, rawIndex) => { const block = preservedCodeBlocks[Number(rawIndex)]; return block ? block.codeText : token; }); } // scripts/ai-chat-turbo-engine/src/core/turns.ts function createTurnUtils(platform) { let activeTurnSelectorGroup = null; const renderedCheckCache = /* @__PURE__ */ new Map(); const userTurnSelectorText = (platform.userTurnSelectors || []).join(", "); let cachedTurns = null; function invalidateTurnCache() { cachedTurns = null; } function clearRenderedCache() { renderedCheckCache.clear(); } function isGeminiThoughtElement(element) { if (!platform.nativeTurnRoots || !(element instanceof Element)) return false; return Boolean( element.closest( "model-thoughts, .thoughts-container, .thoughts-content, [data-test-id*='thought']" ) ); } function isUserTurn(turnElement) { if (!(turnElement instanceof Element)) return false; const contentSearchKey = turnElement.getAttribute( "data-content-search-unit-key" ); if (contentSearchKey && /:(user|human)$/i.test(contentSearchKey)) { return true; } if (contentSearchKey && /:(assistant|model|system)$/i.test(contentSearchKey)) { return false; } const roleValues = [ turnElement.getAttribute("data-message-author-role"), turnElement.getAttribute("data-message-author"), turnElement.getAttribute("data-role"), turnElement.getAttribute("data-message-role"), turnElement.getAttribute("data-conversation-role"), turnElement.getAttribute("data-turn") ].filter((role) => typeof role === "string"); if (roleValues.some((role) => /^(user|human)$/i.test(role))) return true; if (roleValues.some((role) => /^(assistant|model|system)$/i.test(role))) { return false; } if (userTurnSelectorText && (turnElement.matches(userTurnSelectorText) || turnElement.querySelector(userTurnSelectorText))) { return true; } let ancestor = turnElement.parentElement; let ancestorDepth = 0; while (ancestor && ancestorDepth < 3) { if (userTurnSelectorText && ancestor.matches(userTurnSelectorText)) { return true; } ancestor = ancestor.parentElement; ancestorDepth++; } if (turnElement.matches( "user-query, [data-test-id='user-query'], .user-query, .user-query-container" ) || turnElement.querySelector( ".user-query-text, .query-text, [class*='query-content']" )) { return true; } if (turnElement.matches("div.font-user-message") || turnElement.querySelector(".font-user-message")) { return true; } if (turnElement.matches('[data-testid*="user"], [class*="user"]') || turnElement.querySelector('[data-testid*="user"]')) { return true; } return false; } function getTurnRole(turnElement) { if (!(turnElement instanceof Element)) return "assistant"; const contentSearchKey = turnElement.getAttribute( "data-content-search-unit-key" ); if (contentSearchKey && /:(user|human)$/i.test(contentSearchKey)) { return "user"; } if (contentSearchKey && /:(assistant|model)$/i.test(contentSearchKey)) { return "assistant"; } const roleValues = [ turnElement.getAttribute("data-message-author-role"), turnElement.getAttribute("data-message-author"), turnElement.getAttribute("data-role"), turnElement.getAttribute("data-message-role"), turnElement.getAttribute("data-conversation-role"), turnElement.getAttribute("data-turn") ].filter((role) => typeof role === "string"); if (roleValues.some((role) => /^(user|human)$/i.test(role))) return "user"; if (roleValues.some((role) => /^(assistant|model)$/i.test(role))) { return "assistant"; } if (userTurnSelectorText && turnElement.matches(userTurnSelectorText)) { return "user"; } return isUserTurn(turnElement) ? "user" : "assistant"; } function uniqueDomOrdered(elements) { const seen = /* @__PURE__ */ new Set(); const unique = []; for (const element of elements) { if (!(element instanceof Element) || seen.has(element)) continue; seen.add(element); unique.push(element); } unique.sort((first, second) => { if (first === second) return 0; const relation = first.compareDocumentPosition(second); if (relation & Node.DOCUMENT_POSITION_FOLLOWING) return -1; if (relation & Node.DOCUMENT_POSITION_PRECEDING) return 1; return 0; }); return unique; } function filterOutNested(elements) { const ordered = uniqueDomOrdered(elements); return filterNestedInDocumentOrder(ordered); } function filterNestedInDocumentOrder(elements) { if (elements.length < 2) return [...elements]; const candidateSet = new Set(elements); return elements.filter((element) => { let parent = element.parentElement; while (parent) { if (candidateSet.has(parent)) return false; parent = parent.parentElement; } return true; }); } function isRenderedChatGPTElement(element) { if (!(element instanceof HTMLElement) || !element.isConnected || element.closest('[hidden], [aria-hidden="true"], [inert]')) { return false; } const cachedResult = renderedCheckCache.get(element); if (cachedResult !== void 0) return cachedResult; const computedStyle = window.getComputedStyle(element); const isRendered2 = computedStyle.display !== "none" && computedStyle.visibility !== "hidden" && computedStyle.visibility !== "collapse" && element.getClientRects().length > 0; renderedCheckCache.set(element, isRendered2); return isRendered2; } function selectChatGPTRootWithMostTurns(roots, turnSelector) { let selectedRoot = null; let largestTurnCount = -1; for (const candidateRoot of roots) { const turnCount = Array.from( candidateRoot.querySelectorAll(turnSelector) ).filter( (turnElement) => turnElement.closest("[data-turn-key]") === turnElement && isRenderedChatGPTElement(turnElement) ).length; if (turnCount >= largestTurnCount) { selectedRoot = candidateRoot; largestTurnCount = turnCount; } } return selectedRoot; } function collectChatGPTShellMessages(conversationRoot) { const messageNodes = []; const seenTurnRoles = /* @__PURE__ */ new Set(); const turnContainers = Array.from( conversationRoot.querySelectorAll("[data-turn-key]") ).filter( (turnContainer) => turnContainer.closest("[data-turn-key]") === turnContainer && isRenderedChatGPTElement(turnContainer) ); const roleSelectors = [ { role: "user", selectors: [ '[data-content-search-unit-key$=":user"]', '[data-user-message-bubble="true"]', '[data-message-role="user"]', '[data-conversation-role="user"]' ] }, { role: "assistant", selectors: [ '[data-content-search-unit-key$=":assistant"]', '[data-message-role="assistant"]', '[data-conversation-role="assistant"]', "[data-chatgpt-agent-turn-start]" ] } ]; for (const turnContainer of turnContainers) { const turnKey = (turnContainer.getAttribute("data-turn-key") || turnContainer.getAttribute("data-turn-id") || turnContainer.id || "").trim(); if (!turnKey) continue; for (const roleConfig of roleSelectors) { const roleIdentity = `${turnKey}:${roleConfig.role}`; if (seenTurnRoles.has(roleIdentity)) continue; let roleElement = null; for (const selector of roleConfig.selectors) { roleElement = Array.from(turnContainer.querySelectorAll(selector)).find( (candidateElement) => candidateElement.closest("[data-turn-key]") === turnContainer && isRenderedChatGPTElement(candidateElement) ) ?? null; if (roleElement) break; } if (!roleElement) continue; seenTurnRoles.add(roleIdentity); messageNodes.push(roleElement); } } return filterOutNested(uniqueDomOrdered(messageNodes)).filter( (element) => !isGeminiThoughtElement(element) && !matchesReasoningElement(element) ); } function getCurrentChatGPTTurns() { if (!platform.shellTurnRoots) return null; const shellRoots = Array.from( document.querySelectorAll(CHATGPT_SHELL_ROOT_SELECTOR) ).filter(isRenderedChatGPTElement); if (shellRoots.length) { const activeShellRoot = selectChatGPTRootWithMostTurns( shellRoots, "[data-turn-key]" ); return activeShellRoot ? collectChatGPTShellMessages(activeShellRoot) : []; } const transcriptRoots = Array.from( document.querySelectorAll(CHATGPT_TRANSCRIPT_ROOT_SELECTOR) ).filter(isRenderedChatGPTElement); if (transcriptRoots.length) { let activeTranscriptRoot = transcriptRoots[0]; let largestMessageCount = -1; for (const candidateRoot of transcriptRoots) { const messageCount = Array.from( candidateRoot.querySelectorAll(":scope > li[data-message-role]") ).filter(isRenderedChatGPTElement).length; if (messageCount >= largestMessageCount) { activeTranscriptRoot = candidateRoot; largestMessageCount = messageCount; } } return Array.from( activeTranscriptRoot.querySelectorAll(":scope > li[data-message-role]") ).filter(isRenderedChatGPTElement); } return null; } function getTurns() { const currentChatGPTTurns = getCurrentChatGPTTurns(); if (currentChatGPTTurns !== null) return currentChatGPTTurns; const cached = cachedTurns; if (cached !== null && cached.every((turn) => turn.isConnected)) { return cached; } const selectors = getActiveTurnSelectors(); if (selectors.length === 0) return []; const collected = Array.from( document.querySelectorAll(selectors.join(",")) ); const resolved = filterNestedInDocumentOrder(collected).filter( (element) => (!platform.shellTurnRoots || isRenderedChatGPTElement(element)) && !isGeminiThoughtElement(element) && !matchesReasoningElement(element) ); cachedTurns = resolved; return resolved; } function findContentElement(turnElement) { const selectorGroups = []; if (isUserTurn(turnElement) && Array.isArray(platform.userContentSelectors)) { selectorGroups.push(platform.userContentSelectors); } selectorGroups.push(platform.contentSelectors || []); for (const selectorGroup of selectorGroups) { for (const selector of selectorGroup) { const match = turnElement.matches(selector) ? turnElement : turnElement.querySelector(selector); if (match && !isGeminiThoughtElement(match)) return match; } } return turnElement; } function extractTurnText(turnElement) { const raw = elementToPlainText(turnElement); const vfIdx = raw.indexOf(VF_TOKEN_START); if (vfIdx === -1) return raw; let userPart = raw.slice(0, vfIdx).replace(/```[a-z]*\s*$/i, "").trim(); if (userPart === "请查阅并分析以下文本内容:" || userPart === "请查阅以下文本:") { userPart = ""; } const match = raw.match(VF_REGEX); const fileName = match ? ` [📎 ${match[1]}]` : " [📎 附件文件]"; return normalizeText((userPart || "附件文本") + fileName); } function getActiveTurnSelectors() { const selectorGroups = platform.turnSelectorGroups; if (!Array.isArray(selectorGroups)) { return platform.turnSelectors; } if (activeTurnSelectorGroup) { return activeTurnSelectorGroup; } for (const selectorGroup of selectorGroups) { if (selectorGroup.some( (selector) => document.querySelector(selector) )) { activeTurnSelectorGroup = selectorGroup; return selectorGroup; } } return platform.turnSelectors; } function invalidateActiveTurnSelectorGroup() { activeTurnSelectorGroup = null; cachedTurns = null; } return { isGeminiThoughtElement, isUserTurn, getTurnRole, filterOutNested, getCurrentChatGPTTurns, getTurns, findContentElement, extractTurnText, getActiveTurnSelectors, invalidateActiveTurnSelectorGroup, invalidateTurnCache, clearRenderedCache }; } // scripts/ai-chat-turbo-engine/src/core/turn-index.ts function createTurnTextIndex(options) { const records = /* @__PURE__ */ new Map(); const pending = /* @__PURE__ */ new Set(); let snapshot = []; function reconcile(turns) { const live = new Set(turns); for (const element of Array.from(records.keys())) { if (live.has(element)) continue; records.delete(element); pending.delete(element); } snapshot = turns.map((element, index) => { let record = records.get(element); if (!record) { record = { id: index, element, text: "" }; records.set(element, record); pending.add(element); } record.id = index; return record; }); } function markDirty(turn) { if (!records.has(turn)) return; pending.add(turn); } function hasTurn(turn) { return records.has(turn); } function getRecords() { return snapshot; } function flush(flushOptions = {}) { const budgetMs = flushOptions.budgetMs; const startedAt = budgetMs === void 0 ? 0 : performance.now(); for (const element of pending) { if (budgetMs !== void 0 && performance.now() - startedAt >= budgetMs) { break; } pending.delete(element); const record = records.get(element); if (!record || !element.isConnected) continue; record.text = options.extract(element); } return pending.size; } function pendingCount() { return pending.size; } function clear() { records.clear(); pending.clear(); snapshot = []; } return { reconcile, markDirty, hasTurn, getRecords, flush, pendingCount, clear }; } // scripts/ai-chat-turbo-engine/src/core/motion-quiet.ts var QUIET_WINDOW_MS = 450; var SIDEBAR_SELECTOR = "bard-sidenav, .bard-sidenav, side-navigation"; var SIDEBAR_TOGGLE_SELECTOR = [ '[data-test-id="side-nav-menu-button"]', 'button[aria-label*="menu" i]', ".side-nav-menu-button", 'button[aria-label*="主菜单"]' ].join(", "); function createMotionQuiet(options = {}) { const durationMs = options.durationMs ?? QUIET_WINDOW_MS; const endListeners = /* @__PURE__ */ new Set(); let timer = null; let quiet = false; let boundDocument = null; if (options.onQuietEnd) endListeners.add(options.onQuietEnd); function clearTimer() { if (timer === null) return; clearTimeout(timer); timer = null; } function finish() { timer = null; quiet = false; for (const listener of Array.from(endListeners)) listener(); } function start(ms = durationMs) { quiet = true; clearTimer(); timer = setTimeout(finish, ms); } function isQuiet() { return quiet; } function onQuietEnd(listener) { endListeners.add(listener); return () => { endListeners.delete(listener); }; } function handleTransitionRun(event) { const target = event.target; if (!(target instanceof Element)) return; if (!target.closest(SIDEBAR_SELECTOR)) return; start(); } function handleClick(event) { const target = event.target; if (!(target instanceof Element)) return; if (!target.closest(SIDEBAR_TOGGLE_SELECTOR)) return; start(); } function bind(doc) { if (boundDocument === doc) return; teardown(); boundDocument = doc; doc.addEventListener("transitionrun", handleTransitionRun, true); doc.addEventListener("click", handleClick, true); } function teardown() { if (boundDocument) { boundDocument.removeEventListener("transitionrun", handleTransitionRun, true); boundDocument.removeEventListener("click", handleClick, true); boundDocument = null; } clearTimer(); quiet = false; } return { start, isQuiet, onQuietEnd, bind, teardown }; } // scripts/ai-chat-turbo-engine/src/core/sidebar-peek.ts var SIDEBAR_PEEK_ATTRIBUTE = "data-ai-turbo-sidebar-peek"; var SIDEBAR_PEEK_HOLD_ATTRIBUTE = "data-ai-turbo-sidebar-peek-hold"; var SIDEBAR_PEEK_WIDTH_VAR = "--ai-turbo-sidebar-peek-width"; var SIDEBAR_PEEK_SHIFT_VAR = "--ai-turbo-sidebar-peek-shift"; var SIDEBAR_PEEK_LANE_PX = 28; var SIDEBAR_PEEK_PROXIMITY_PX = 10; var SIDEBAR_PEEK_POPOVER_HOLD_MS = 3e4; var SIDEBAR_PEEK_WIDTH_RATIO = 0.42; var SIDEBAR_PEEK_TRANSITION_HOLD_MS = 360; var SIDEBAR_PEEK_NAVIGATION_COLLAPSE_MS = 360; var SIDEBAR_PEEK_KEYBOARD_FOCUS_MS = 700; var SIDEBAR_PEEK_OPEN_RETRY_MS = 90; var SIDEBAR_PEEK_OPEN_ATTEMPTS = 8; var SIDEBAR_PEEK_NATIVE_OPEN_CHECK_MS = 320; var SIDEBAR_PEEK_NATIVE_OPEN_CHECKS = 2; var SIDEBAR_PEEK_NATIVE_OPEN_GRACE_MS = 400; var SIDEBAR_PEEK_RELIFT_LIMIT = 4; var SIDEBAR_PEEK_CLICK_RELEASE_MS = 140; var POPOVER_SELECTOR = [ '[role="menu"]', '[role="listbox"]', '[role="dialog"]', ".ant-dropdown", ".ant-modal-root", "[data-radix-popper-content-wrapper]" ].join(", "); var POPOVER_RECHECK_MS = 400; var POINTER_PROBE_INTERVAL_MS = 40; var DEFAULT_PEEK_WIDTH = 248; var DEFAULT_COLLAPSED_MAX_WIDTH = 96; var COLLAPSED_CLASS_TOKENS = /* @__PURE__ */ new Set([ "collapsed", "is-collapsed", "sidenav-collapsed", "rail-collapsed", "side-nav-collapsed" ]); var EXPANDED_CLASS_TOKENS = /* @__PURE__ */ new Set([ "sidenav-open", "is-expanded", "is-open", "expanded" ]); var MOTION_ATTRIBUTES = ["class", "data-collapsed", "data-state", "aria-expanded"]; function createSidebarPeek(options) { const definition = options.sidebar; const hideDelayMs = options.hideDelayMs ?? (() => SIDEBAR_PEEK_HIDE_DELAY_MS); const showDelayMs = options.showDelayMs ?? (() => SIDEBAR_PEEK_SHOW_DELAY_MS); const isUserKey = options.isUserKey ?? ((event) => event.isTrusted); const peekWidth = definition?.peekWidth ?? DEFAULT_PEEK_WIDTH; const collapsedMaxWidth = definition?.collapsedMaxWidth ?? DEFAULT_COLLAPSED_MAX_WIDTH; const sidebarSelectors = definition?.selectors ?? []; const triggerSelector = definition?.triggers?.join(", ") ?? ""; const revealSelector = definition?.reveal?.join(", ") ?? ""; const nativeOnly = definition?.nativeExpand !== void 0 && definition?.nativeOnly !== false; let boundDocument = null; let observer = null; let resolveDocument = null; let resolvedRail = null; let active = null; let widthSnapshot = null; let shiftSnapshot = null; let showTimer = null; let hideTimer = null; let pendingRail = null; let revealTargets = []; let inertTargets = []; let railDisplaySnapshot = null; let railOpacitySnapshot = null; let railTransformSnapshot = null; let railVisibilitySnapshot = null; let suppressTargets = []; let clipTargets = []; let shellTargets = []; let revealShells = []; let revealObserver = null; let reliftTimer = null; let reliftAttempts = 0; let labelTargets = []; let transitionTargets = []; let collapseTarget = null; let appliedHref = ""; let expandedByPeek = false; let pointerX = Number.NaN; let pointerY = Number.NaN; let lastUserKeyMs = Number.NEGATIVE_INFINITY; let activePeekWidth = peekWidth; let activeSide = "left"; let peekBand = null; let suppressShowUntilExit = false; let holdTimer = null; let holdRemainingMs = 0; let rescanNeeded = false; let lastProbeMs = Number.NEGATIVE_INFINITY; let probeTimer = null; let activeShift = 0; let reacquireTimer = null; let reacquireAttempts = 0; let openTimer = null; let openAttempts = 0; let nativeOpenTimer = null; let nativeOpenChecks = 0; let nativeOpenSeq = 0; let nativeOpenPressedAt = Number.NEGATIVE_INFINITY; let transitionHoldTimer = null; let transitionHoldNode = null; let nativeCollapseTimer = null; let clickReleaseTimer = null; const preexistingPopovers = /* @__PURE__ */ new Set(); const hasRail = sidebarSelectors.length > 0; function isEnabled() { return hasRail && (options.enabled?.() ?? true); } function resolveRail() { const doc = boundDocument; if (!isEnabled() || doc === null) return null; if (resolvedRail !== null && resolvedRail.isConnected) return resolvedRail; if (resolveDocument !== doc) { resolveDocument = doc; resolvedRail = null; } resolvedRail = null; for (const selector of sidebarSelectors) { const found = doc.querySelector(selector); if (found instanceof HTMLElement) { resolvedRail = found; break; } } return resolvedRail; } function railFor(node) { const rail = resolveRail(); if (rail === null) return null; if (rail === node || rail.contains(node)) return rail; if (triggerSelector !== "" && node.closest(triggerSelector) !== null) { return rail; } return null; } function hasExpandedToken(node) { for (const token of node.classList) { if (EXPANDED_CLASS_TOKENS.has(token)) return true; } return false; } function isCollapsed(node) { const painted = node.getBoundingClientRect(); if (rectIsOnScreen(node, painted)) { return painted.width <= collapsedMaxWidth; } for (const token of node.classList) { if (COLLAPSED_CLASS_TOKENS.has(token)) return true; if (EXPANDED_CLASS_TOKENS.has(token)) return false; } if (painted.width === 0) return true; if (painted.right <= 1) return true; const viewport = viewportWidthOf(node); if (viewport > 0 && painted.left >= viewport - 1) return true; return painted.width <= collapsedMaxWidth; } function sideOf(node) { const viewport = viewportWidthOf(node); if (viewport <= 0) return "left"; const rect = node.getBoundingClientRect(); return rect.left + rect.width / 2 < viewport / 2 ? "left" : "right"; } function viewportWidthOf(node) { const doc = node.ownerDocument; return doc.documentElement.clientWidth || doc.defaultView?.innerWidth || 0; } function viewportHeightOf(node) { const doc = node.ownerDocument; return doc.documentElement.clientHeight || doc.defaultView?.innerHeight || 0; } function rectIsOnScreen(node, rect) { if (rect.width <= 0 || rect.height <= 0) return false; if (rect.right <= 1) return false; const width = viewportWidthOf(node); if (width > 0 && rect.left >= width - 1) return false; const height = viewportHeightOf(node); return height <= 0 || rect.bottom > 1 && rect.top < height - 1; } function rememberBand(rect) { if (rect.width <= 0 || rect.height <= 0) return; peekBand = { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom }; } function peekWidthFor(node) { const doc = node.ownerDocument; const viewport = doc.documentElement.clientWidth || doc.defaultView?.innerWidth || 0; if (viewport <= 0) return peekWidth; const cap = Math.round(viewport * SIDEBAR_PEEK_WIDTH_RATIO); return Math.max(1, Math.min(peekWidth, cap)); } function nearRail(x, y) { const rail = resolveRail(); if (rail === null) return null; const doc = rail.ownerDocument; const view = doc.defaultView; const viewportWidth = doc.documentElement.clientWidth || view?.innerWidth || 0; const viewportHeight = doc.documentElement.clientHeight || view?.innerHeight || 0; const rect = rail.getBoundingClientRect(); const side = sideOf(rail); const top = (rect.height > 0 ? rect.top : 0) - SIDEBAR_PEEK_PROXIMITY_PX; const bottom = (rect.height > 0 ? rect.bottom : viewportHeight) + SIDEBAR_PEEK_PROXIMITY_PX; if (y < top || y > bottom) return null; const onScreen = rect.width > 0 && rect.right > 1 && rect.left < viewportWidth - 1; if (side === "left") { const end = Math.max(onScreen ? rect.right : 0, SIDEBAR_PEEK_LANE_PX); const start2 = onScreen ? Math.min(rect.left, 0) : 0; return x >= start2 - SIDEBAR_PEEK_PROXIMITY_PX && x <= end + SIDEBAR_PEEK_PROXIMITY_PX ? rail : null; } const start = Math.min( onScreen ? rect.left : viewportWidth, viewportWidth - SIDEBAR_PEEK_LANE_PX ); return x >= start - SIDEBAR_PEEK_PROXIMITY_PX && x <= viewportWidth + SIDEBAR_PEEK_PROXIMITY_PX ? rail : null; } function rectHoldsPointer(rect, x, y) { if (rect.width <= 0 || rect.height <= 0) return false; return x >= rect.left - SIDEBAR_PEEK_PROXIMITY_PX && x <= rect.right + SIDEBAR_PEEK_PROXIMITY_PX && y >= rect.top - SIDEBAR_PEEK_PROXIMITY_PX && y <= rect.bottom + SIDEBAR_PEEK_PROXIMITY_PX; } function withinPeekBand(rail, x, y) { if (nativeOnly) { const current = resolveRail() ?? rail; const live = current.getBoundingClientRect(); if (rectHoldsPointer(live, x, y)) { rememberBand(live); return true; } if (peekBand !== null && boxHoldsPointer(peekBand, x, y)) return true; const reach2 = Math.max(SIDEBAR_PEEK_LANE_PX, activePeekWidth, live.width); const boxTop = live.height > 0 ? live.top : peekBand?.top ?? 0; const boxBottom = live.height > 0 ? live.bottom : peekBand?.bottom ?? viewportHeightOf(current); if (y < boxTop - SIDEBAR_PEEK_PROXIMITY_PX || y > boxBottom + SIDEBAR_PEEK_PROXIMITY_PX) { return false; } if (activeSide === "right") { const viewport = viewportWidthOf(current); return x >= viewport - reach2 - SIDEBAR_PEEK_PROXIMITY_PX && x <= viewport + SIDEBAR_PEEK_PROXIMITY_PX; } return x >= -SIDEBAR_PEEK_PROXIMITY_PX && x <= reach2 + SIDEBAR_PEEK_PROXIMITY_PX; } const rect = rail.getBoundingClientRect(); const side = sideOf(rail); const reach = Math.max(rect.width, activePeekWidth); const top = rect.height > 0 ? rect.top - SIDEBAR_PEEK_PROXIMITY_PX : -Infinity; const bottom = rect.height > 0 ? rect.bottom + SIDEBAR_PEEK_PROXIMITY_PX : Infinity; if (y >= top && y <= bottom) { const inside = side === "left" ? x >= rect.left - SIDEBAR_PEEK_PROXIMITY_PX && x <= rect.left + reach + SIDEBAR_PEEK_PROXIMITY_PX : x <= rect.right + SIDEBAR_PEEK_PROXIMITY_PX && x >= rect.right - reach - SIDEBAR_PEEK_PROXIMITY_PX; if (inside) return true; } for (const shell of shellTargets) { if (rectHoldsPointer(shell.node.getBoundingClientRect(), x, y)) return true; } return false; } function boxHoldsPointer(box, x, y) { return x >= box.left - SIDEBAR_PEEK_PROXIMITY_PX && x <= box.right + SIDEBAR_PEEK_PROXIMITY_PX && y >= box.top - SIDEBAR_PEEK_PROXIMITY_PX && y <= box.bottom + SIDEBAR_PEEK_PROXIMITY_PX; } function measureShift(node, collapsedWidth, width) { const view = node.ownerDocument.defaultView; if (view === null) return 0; if (!Number.isFinite(collapsedWidth) || collapsedWidth <= 0) return 0; const style = view.getComputedStyle(node); if (style.position !== "static" && style.position !== "relative") return 0; const parent = node.parentElement; if (parent === null) return 0; const parentStyle = view.getComputedStyle(parent); const isFlex = parentStyle.display === "flex" || parentStyle.display === "inline-flex"; const isGrid = parentStyle.display === "grid" || parentStyle.display === "inline-grid"; const isBlockFlow = parentStyle.display === "block" || parentStyle.display === "flow-root" || parentStyle.display === "inline-block"; if (!isFlex && !isGrid && !isBlockFlow) return 0; if (isFlex && !parentStyle.flexDirection.startsWith("row")) return 0; if (parentStyle.overflow !== "visible") return 0; const shift = Math.round(collapsedWidth - width); return shift < 0 ? shift : 0; } function readSnapshot(node, property) { return { value: node.style.getPropertyValue(property), priority: node.style.getPropertyPriority(property) }; } function restoreSnapshot(node, property, snapshot) { if (snapshot === null || snapshot.value === "") { node.style.removeProperty(property); return; } node.style.setProperty(property, snapshot.value, snapshot.priority); } function cancelShow() { if (showTimer !== null) { clearTimeout(showTimer); showTimer = null; } pendingRail = null; } function cancelHide() { if (hideTimer !== null) { clearTimeout(hideTimer); hideTimer = null; } } function cancelHold() { if (holdTimer !== null) { clearTimeout(holdTimer); holdTimer = null; } holdRemainingMs = 0; } function cancelOpen() { if (openTimer !== null) { clearTimeout(openTimer); openTimer = null; } openAttempts = 0; } function cancelNativeOpenCheck() { if (nativeOpenTimer !== null) { clearTimeout(nativeOpenTimer); nativeOpenTimer = null; } nativeOpenChecks = 0; } function releaseActive(reason = "hover") { cancelHide(); cancelHold(); cancelOpen(); cancelNativeOpenCheck(); cancelReacquire(); cancelProbe(); cancelClickRelease(); rescanNeeded = false; preexistingPopovers.clear(); const node = active; if (node === null) return; active = null; const held = !nativeOnly && (reason === "hover" || reason === "navigation"); if (held) holdTransitions(node); const releasedWidth = node.getBoundingClientRect().width; let collapse = null; if (expandedByPeek) { expandedByPeek = false; const control = collapseFor(node); if (control !== null && reason !== "adopt" && (reason === "navigation" || stillOwned(node, control))) { collapse = control; } } collapseTarget = null; appliedHref = ""; node.removeAttribute(SIDEBAR_PEEK_ATTRIBUTE); restoreSnapshot(node, SIDEBAR_PEEK_WIDTH_VAR, widthSnapshot); restoreSnapshot(node, SIDEBAR_PEEK_SHIFT_VAR, shiftSnapshot); if (railDisplaySnapshot !== null) { restoreSnapshot(node, "display", railDisplaySnapshot); railDisplaySnapshot = null; } if (railOpacitySnapshot !== null) { restoreSnapshot(node, "opacity", railOpacitySnapshot); railOpacitySnapshot = null; } if (railTransformSnapshot !== null) { restoreSnapshot(node, "transform", railTransformSnapshot); railTransformSnapshot = null; } if (railVisibilitySnapshot !== null) { restoreSnapshot(node, "visibility", railVisibilitySnapshot); railVisibilitySnapshot = null; } widthSnapshot = null; shiftSnapshot = null; restoreInert(); restoreReveal(); restoreSuppress(); restoreClip(); restoreShells(); restoreLabels(); if (held) { void node.getBoundingClientRect(); releaseTransitions(); } if (collapse !== null) { requestNativeCollapse( node, collapse, reason === "navigation" ? SIDEBAR_PEEK_NAVIGATION_COLLAPSE_MS : 0, releasedWidth ); } } function holdTransitions(rail) { finishTransitionHold(); const nodes = [rail]; for (const target of shellTargets) nodes.push(target.node); for (const target of revealShells) nodes.push(target.node); for (const target of labelTargets) nodes.push(target.node); for (const node of nodes) { if (!node.isConnected) continue; if (transitionTargets.some((entry) => entry.node === node)) continue; transitionTargets.push({ node, transition: readSnapshot(node, "transition") }); node.style.setProperty("transition", "none", "important"); } transitionHoldNode = rail; rail.setAttribute(SIDEBAR_PEEK_HOLD_ATTRIBUTE, ""); } function releaseTransitions() { const targets = transitionTargets; transitionTargets = []; for (const target of targets) { if (!target.node.isConnected) continue; restoreSnapshot(target.node, "transition", target.transition); } const held = transitionHoldNode; transitionHoldNode = null; if (held === null) return; if (transitionHoldTimer !== null) clearTimeout(transitionHoldTimer); transitionHoldTimer = setTimeout(() => { transitionHoldTimer = null; transitionHoldNode = null; held.removeAttribute(SIDEBAR_PEEK_HOLD_ATTRIBUTE); }, SIDEBAR_PEEK_TRANSITION_HOLD_MS); } function finishTransitionHold() { if (transitionHoldTimer !== null) { clearTimeout(transitionHoldTimer); transitionHoldTimer = null; } const node = transitionHoldNode; transitionHoldNode = null; if (node !== null) node.removeAttribute(SIDEBAR_PEEK_HOLD_ATTRIBUTE); } function requestNativeCollapse(rail, control, delayMs, releasedWidth) { cancelNativeCollapse(); nativeCollapseTimer = setTimeout(() => { nativeCollapseTimer = null; if (!rail.isConnected) return; if (control.ownerDocument !== rail.ownerDocument) return; if (active === rail) return; const now = rail.getBoundingClientRect().width; if (now <= collapsedMaxWidth) return; if (releasedWidth > collapsedMaxWidth + 8 && now <= releasedWidth - 8) { return; } const target = isPaintedControl(control) ? control : firstPaintedControl(rail, definition?.nativeExpand?.collapse ?? "") ?? (control.isConnected ? control : null); target?.click(); }, delayMs); } function cancelNativeCollapse() { if (nativeCollapseTimer === null) return; clearTimeout(nativeCollapseTimer); nativeCollapseTimer = null; } function cancelClickRelease() { if (clickReleaseTimer === null) return; clearTimeout(clickReleaseTimer); clickReleaseTimer = null; } function collapseFor(rail) { const selector = definition?.nativeExpand?.collapse ?? ""; if (selector === "") return null; const captured = collapseTarget; if (captured !== null && isPaintedControl(captured)) return captured; const scoped = firstPaintedControl(rail, selector); if (scoped !== null) return scoped; if (captured !== null && captured.isConnected) return captured; return firstPaintedControl(rail.ownerDocument, selector); } function isPaintedControl(node) { if (node === null) return false; if (!(node instanceof HTMLElement)) return false; if (!node.isConnected) return false; if (node.closest("[inert]") !== null) return false; if (node.hasAttribute("disabled")) return false; const rect = node.getBoundingClientRect(); return rect.width > 1 && rect.height > 1; } function firstPaintedControl(root, selector) { for (const found of Array.from(root.querySelectorAll(selector))) { if (!(found instanceof HTMLElement)) continue; if (isPaintedControl(found)) return found; } return null; } function pressNativeExpand(rail) { const selector = definition?.nativeExpand?.expand ?? ""; if (selector === "") return true; const expand = firstPaintedControl(rail, selector) ?? firstPaintedControl(rail.ownerDocument, selector); if (expand === null) return false; expandedByPeek = true; nativeOpenPressedAt = performance.now(); nativeOpenSeq += 1; const seq = nativeOpenSeq; expand.click(); collapseTarget = firstPaintedControl( rail.ownerDocument, definition?.nativeExpand?.collapse ?? "" ) ?? (isPaintedControl(expand) ? expand : null); scheduleReacquire(); if (nativeOnly) scheduleNativeOpenCheck(rail, seq); return true; } function nativePanelOpen(node) { if (!node.isConnected) return false; if (node.getBoundingClientRect().width > collapsedMaxWidth + 4) return true; if (hasExpandedToken(node)) return true; const state = node.getAttribute("data-state"); if (state === "expanded" || state === "open") return true; return node.getAttribute("aria-expanded") === "true"; } function nativeOpenIsRecent() { return performance.now() - nativeOpenPressedAt <= SIDEBAR_PEEK_NATIVE_OPEN_GRACE_MS; } function scheduleNativeOpenCheck(rail, seq) { cancelNativeOpenCheck(); const check = () => { nativeOpenTimer = null; if (seq !== nativeOpenSeq) return; if (active === null) return; const current = resolveRail(); if (current !== null && current !== rail) { return; } if (nativePanelOpen(rail)) return; nativeOpenChecks += 1; if (nativeOpenChecks < SIDEBAR_PEEK_NATIVE_OPEN_CHECKS) { nativeOpenTimer = setTimeout(check, SIDEBAR_PEEK_NATIVE_OPEN_CHECK_MS); return; } expandedByPeek = false; collapseTarget = null; releaseActive("lifecycle"); }; nativeOpenTimer = setTimeout(check, SIDEBAR_PEEK_NATIVE_OPEN_CHECK_MS); } function retryNativeExpand(rail) { if (openTimer !== null) return; if (openAttempts >= SIDEBAR_PEEK_OPEN_ATTEMPTS) { releaseActive("lifecycle"); return; } openAttempts += 1; openTimer = setTimeout(() => { openTimer = null; if (active !== rail) return; if (!rail.isConnected) { releaseActive("lifecycle"); return; } if (!pressNativeExpand(rail)) retryNativeExpand(rail); }, SIDEBAR_PEEK_OPEN_RETRY_MS); } function stillOwned(rail, node) { if (!node.isConnected) return false; if (node.ownerDocument !== rail.ownerDocument) return false; const view = rail.ownerDocument.defaultView; if (appliedHref !== "" && view !== null && view.location.href !== appliedHref) { return false; } return true; } function liftInert(rail) { if (nativeOnly) return; for (const found of Array.from(rail.querySelectorAll("[inert]"))) { if (!(found instanceof HTMLElement)) continue; if (inertTargets.includes(found)) continue; inertTargets.push(found); found.removeAttribute("inert"); } } function restoreInert() { if (inertTargets.length === 0) return; const targets = inertTargets; inertTargets = []; for (const node of targets) node.setAttribute("inert", ""); } function liftReveal(rail) { if (nativeOnly) return; if (revealSelector === "") return; const targets = []; for (const found of Array.from(rail.querySelectorAll(revealSelector))) { if (!(found instanceof HTMLElement)) continue; targets.push({ node: found, display: readSnapshot(found, "display") }); found.style.setProperty("display", "flex", "important"); } revealTargets = targets; } function restoreReveal() { if (revealTargets.length === 0) return; const targets = revealTargets; revealTargets = []; for (const target of targets) { restoreSnapshot(target.node, "display", target.display); } } function suppressOverlap() { if (nativeOnly) return; const selectors = definition?.suppress; const doc = boundDocument; if (selectors === void 0 || selectors.length === 0 || doc === null) { return; } const selector = selectors.join(", "); for (const found of Array.from(doc.querySelectorAll(selector))) { if (!(found instanceof HTMLElement)) continue; if (suppressTargets.some((target) => target.node === found)) continue; suppressTargets.push({ node: found, opacity: readSnapshot(found, "opacity"), pointerEvents: readSnapshot(found, "pointer-events") }); found.style.setProperty("opacity", "0", "important"); found.style.setProperty("pointer-events", "none", "important"); } } function restoreSuppress() { if (suppressTargets.length === 0) return; const targets = suppressTargets; suppressTargets = []; for (const target of targets) { restoreSnapshot(target.node, "opacity", target.opacity); restoreSnapshot(target.node, "pointer-events", target.pointerEvents); } } function liftClip(rail) { if (nativeOnly) return; if (definition?.revealRail !== true) return; const doc = boundDocument; const view = rail.ownerDocument.defaultView; if (doc === null || view === null) return; for (let node = rail.parentElement; node !== null && node !== doc.body; node = node.parentElement) { const style = view.getComputedStyle(node); if (style.overflow === "visible") continue; if (node.getBoundingClientRect().width >= activePeekWidth) continue; clipTargets.push({ node, overflowX: readSnapshot(node, "overflow-x"), overflowY: readSnapshot(node, "overflow-y") }); node.style.setProperty("overflow-x", "visible", "important"); node.style.setProperty("overflow-y", "visible", "important"); } } function restoreClip() { if (clipTargets.length === 0) return; const targets = clipTargets; clipTargets = []; for (const target of targets) { restoreSnapshot(target.node, "overflow-x", target.overflowX); restoreSnapshot(target.node, "overflow-y", target.overflowY); } } function liftShells(rail, width) { if (nativeOnly) return; const selectors = definition?.shells; if (selectors === void 0 || selectors.length === 0) return; const seen = /* @__PURE__ */ new Set(); for (const selector of selectors) { for (const found of Array.from(rail.querySelectorAll(selector))) { if (!(found instanceof HTMLElement)) continue; if (found === rail || seen.has(found)) continue; seen.add(found); stretchShell(found, shellWidthFor(rail, found, width)); } } } function shellWidthFor(rail, node, width) { const view = rail.ownerDocument.defaultView; if (view === null) return width; const rect = node.getBoundingClientRect(); if (rect.width <= 0 && rect.height <= 0) return width; const border = parseFloat(view.getComputedStyle(rail).borderRightWidth); const clipRight = rail.getBoundingClientRect().right - (Number.isFinite(border) ? border : 0); const available = Math.floor(clipRight - rect.left) - 1; if (available < 80 || available >= width) return width; return available; } function stretchShell(node, width) { if (!shellTargets.some((target) => target.node === node)) { shellTargets.push({ node, width: readSnapshot(node, "width"), minWidth: readSnapshot(node, "min-width"), maxWidth: readSnapshot(node, "max-width"), boxSizing: readSnapshot(node, "box-sizing") }); } const value = `${width}px`; node.style.setProperty("box-sizing", "border-box", "important"); node.style.setProperty("width", value, "important"); node.style.setProperty("min-width", value, "important"); node.style.setProperty("max-width", value, "important"); } function restoreShells() { stopRevealWatch(); if (revealShells.length > 0) { const reveals = revealShells; revealShells = []; for (const target of reveals) { restoreSnapshot(target.node, "display", target.display); } } if (shellTargets.length === 0) return; const targets = shellTargets; shellTargets = []; for (const target of targets) { restoreSnapshot(target.node, "width", target.width); restoreSnapshot(target.node, "min-width", target.minWidth); restoreSnapshot(target.node, "max-width", target.maxWidth); restoreSnapshot(target.node, "box-sizing", target.boxSizing); } } function liftContentShells(rail, width) { if (nativeOnly) return; const view = rail.ownerDocument.defaultView; if (view === null) return; const rows = Array.from( rail.querySelectorAll('a[href], [role="link"], [role="treeitem"]') ); if (rows.length < 2) return; if (width <= collapsedMaxWidth) return; const counts = /* @__PURE__ */ new Map(); for (const row of rows) { for (let node = row.parentElement; node !== null && node !== rail; node = node.parentElement) { if (!(node instanceof HTMLElement)) continue; counts.set(node, (counts.get(node) ?? 0) + 1); } } const seen = /* @__PURE__ */ new Set(); for (const target of shellTargets) seen.add(target.node); for (const target of revealShells) seen.add(target.node); let lifted = 0; for (const [node, count] of counts) { if (count < 2 || seen.has(node) || lifted >= 32) continue; let style = view.getComputedStyle(node); if (style.display === "none") { const inline = readSnapshot(node, "display"); if (inline.value === "") continue; node.style.removeProperty("display"); style = view.getComputedStyle(node); if (style.display === "none") { restoreSnapshot(node, "display", inline); continue; } revealShells.push({ node, display: inline }); } if (style.display === "contents" || style.display === "inline") { continue; } const rect = node.getBoundingClientRect(); if (rect.width <= 0 && rect.height <= 0) continue; const available = shellWidthFor(rail, node, width); if (rect.width >= available - 2) continue; seen.add(node); lifted += 1; stretchShell(node, available); } if (revealShells.length > 0) watchRevealShells(); } function watchRevealShells() { if (revealObserver !== null) revealObserver.disconnect(); revealObserver = new MutationObserver(handleRevealMutation); for (const target of revealShells) { revealObserver.observe(target.node, { attributes: true, attributeFilter: ["style"] }); } } function stopRevealWatch() { if (revealObserver !== null) { revealObserver.disconnect(); revealObserver = null; } if (reliftTimer !== null) { clearTimeout(reliftTimer); reliftTimer = null; } } function handleRevealMutation() { if (active === null || reliftTimer !== null) return; if (reliftAttempts >= SIDEBAR_PEEK_RELIFT_LIMIT) return; if (!revealShells.some((target) => inlineHidden(target.node))) return; reliftTimer = setTimeout(() => { reliftTimer = null; reliftRevealShells(); }, 0); } function inlineHidden(node) { return node.style.getPropertyValue("display").trim() === "none"; } function reliftRevealShells() { const rail = active; if (rail === null || revealShells.length === 0) return; const view = rail.ownerDocument.defaultView; if (view === null) return; reliftAttempts += 1; const kept = []; for (const target of revealShells) { if (!target.node.isConnected) continue; if (inlineHidden(target.node)) target.node.style.removeProperty("display"); if (view.getComputedStyle(target.node).display === "none") { restoreSnapshot(target.node, "display", target.display); continue; } kept.push(target); } revealShells = kept; if (kept.length === 0) { stopRevealWatch(); return; } liftContentShells(rail, activePeekWidth); liftLabels(rail); } function liftLabels(rail) { if (nativeOnly) return; const view = rail.ownerDocument.defaultView; if (view === null) return; for (const row of Array.from( rail.querySelectorAll('a[href], [role="link"], [role="treeitem"]') )) { const leaves = row.querySelectorAll("span, div, p"); if (leaves.length > 12) continue; for (const leaf of Array.from(leaves)) { if (!(leaf instanceof HTMLElement)) continue; if (leaf.children.length > 0) continue; const text = (leaf.textContent ?? "").trim(); if (text.length < 2) continue; if (labelTargets.some((target) => target.node === leaf)) continue; const style = view.getComputedStyle(leaf); const hidden = style.display === "none" || style.visibility === "hidden" || style.opacity === "0" || parseFloat(style.maxWidth) === 0; if (!hidden) continue; labelTargets.push({ node: leaf, display: readSnapshot(leaf, "display"), visibility: readSnapshot(leaf, "visibility"), opacity: readSnapshot(leaf, "opacity"), maxWidth: readSnapshot(leaf, "max-width") }); if (style.display === "none") { leaf.style.setProperty("display", "block", "important"); } leaf.style.setProperty("visibility", "visible", "important"); leaf.style.setProperty("opacity", "1", "important"); if (parseFloat(style.maxWidth) === 0) { leaf.style.setProperty("max-width", "none", "important"); } } } } function restoreLabels() { if (labelTargets.length === 0) return; const targets = labelTargets; labelTargets = []; for (const target of targets) { restoreSnapshot(target.node, "display", target.display); restoreSnapshot(target.node, "visibility", target.visibility); restoreSnapshot(target.node, "opacity", target.opacity); restoreSnapshot(target.node, "max-width", target.maxWidth); } } function applyPeek(node, adopting = false) { cancelShow(); cancelHide(); cancelOpen(); cancelReacquire(); cancelNativeCollapse(); suppressShowUntilExit = false; if (active === node) { refreshPeek(node); return; } if (adopting && nativeOnly && expandedByPeek && !nativePanelOpen(node) && !nativeOpenIsRecent()) { expandedByPeek = false; collapseTarget = null; releaseActive("navigation"); return; } const carriedExpansion = adopting && expandedByPeek; const carriedCollapse = adopting ? collapseTarget : null; releaseActive(adopting ? "adopt" : "hover"); expandedByPeek = carriedExpansion; collapseTarget = carriedCollapse; const collapsedWidth = node.getBoundingClientRect().width; const width = peekWidthFor(node); activePeekWidth = width; activeSide = sideOf(node); const measured = measureShift(node, collapsedWidth, width); const configuredShift = definition?.shift ?? 0; const fallbackShift = width === peekWidth ? configuredShift : configuredShift + (peekWidth - width); const shift = measured < 0 ? measured : fallbackShift; activeShift = shift; widthSnapshot = readSnapshot(node, SIDEBAR_PEEK_WIDTH_VAR); shiftSnapshot = readSnapshot(node, SIDEBAR_PEEK_SHIFT_VAR); if (!nativeOnly && definition?.revealRail === true) { railDisplaySnapshot = readSnapshot(node, "display"); railOpacitySnapshot = readSnapshot(node, "opacity"); railTransformSnapshot = readSnapshot(node, "transform"); railVisibilitySnapshot = readSnapshot(node, "visibility"); const view2 = node.ownerDocument.defaultView; const display = view2 === null ? "none" : view2.getComputedStyle(node).display; if (display === "none") { node.style.setProperty("display", "flex", "important"); } node.style.setProperty("opacity", "1", "important"); node.style.setProperty("transform", "none", "important"); node.style.setProperty("visibility", "visible", "important"); } active = node; rescanNeeded = true; reliftAttempts = 0; finishTransitionHold(); snapshotPopovers(); if (!nativeOnly) { node.style.setProperty(SIDEBAR_PEEK_WIDTH_VAR, `${width}px`); node.style.setProperty(SIDEBAR_PEEK_SHIFT_VAR, `${shift}px`); node.setAttribute(SIDEBAR_PEEK_ATTRIBUTE, sideOf(node)); } liftReveal(node); liftInert(node); liftClip(node); liftShells(node, width); liftContentShells(node, width); liftLabels(node); suppressOverlap(); if (definition?.nativeExpand !== void 0) { if (carriedExpansion) { collapseTarget = firstPaintedControl(node, definition.nativeExpand.collapse) ?? firstPaintedControl(node.ownerDocument, definition.nativeExpand.collapse); if (nativeOnly) { nativeOpenSeq += 1; scheduleNativeOpenCheck(node, nativeOpenSeq); } } else if (!pressNativeExpand(node) && nativeOnly) { retryNativeExpand(node); } activePeekWidth = Math.max( activePeekWidth, Math.round(node.getBoundingClientRect().width) ); rememberBand(node.getBoundingClientRect()); } const view = node.ownerDocument.defaultView; appliedHref = view?.location.href ?? ""; } function refreshPeek(node) { if (nativeOnly) { const view2 = node.ownerDocument.defaultView; if (view2 !== null && appliedHref === "") appliedHref = view2.location.href; const live = node.getBoundingClientRect(); activePeekWidth = Math.max( activePeekWidth, Math.round(live.width) ); rememberBand(live); return; } const view = node.ownerDocument.defaultView; if (view === null) return; if (node.getAttribute(SIDEBAR_PEEK_ATTRIBUTE) === null) { node.setAttribute(SIDEBAR_PEEK_ATTRIBUTE, sideOf(node)); } node.style.setProperty(SIDEBAR_PEEK_WIDTH_VAR, `${activePeekWidth}px`); node.style.setProperty(SIDEBAR_PEEK_SHIFT_VAR, `${activeShift}px`); liftInert(node); liftShells(node, activePeekWidth); liftContentShells(node, activePeekWidth); liftLabels(node); if (appliedHref === "") appliedHref = view.location.href; } function cancelReacquire() { if (reacquireTimer !== null) { clearTimeout(reacquireTimer); reacquireTimer = null; } reacquireAttempts = 0; } function scheduleReacquire() { if (reacquireTimer !== null) return; reacquireTimer = setTimeout(() => { reacquireTimer = null; reacquireRail(); }, 32); } function reacquireRail() { if (active === null) return; const rail = resolveRail(); if (rail === null) { if (reacquireAttempts < 5) { reacquireAttempts += 1; scheduleReacquire(); return; } releaseActive("navigation"); return; } reacquireAttempts = 0; if (rail === active) { refreshPeek(rail); return; } applyPeek(rail, true); } function scheduleShow(rail) { cancelHide(); if (active === rail) return; if (suppressShowUntilExit) return; if (pendingRail === rail && showTimer !== null) return; cancelShow(); pendingRail = rail; showTimer = setTimeout(() => { showTimer = null; const target = pendingRail; pendingRail = null; if (target === null || !target.isConnected) return; if (!isCollapsed(target)) return; applyPeek(target); }, showDelayMs()); } function scheduleHide(rail) { if (pendingRail === rail) cancelShow(); if (active !== rail) return; cancelHide(); hideTimer = setTimeout(() => { hideTimer = null; if (active !== rail) return; if (pointerStillOverRail(rail)) return; if (popoverUnderPointer() !== null) { holdForPopover(rail); return; } releaseActive(); }, hideDelayMs()); } function popoverUnderPointer() { const doc = boundDocument; if (doc === null) return null; if (!Number.isFinite(pointerX) || !Number.isFinite(pointerY)) return null; if (typeof doc.elementFromPoint !== "function") return null; const hit = doc.elementFromPoint(pointerX, pointerY); return hit instanceof Element ? popoverFor(hit) : null; } function isVisiblePopover(node, view) { if (node.hidden) return false; if (node.getAttribute("aria-hidden") === "true") return false; if (node.closest("[inert]") !== null) return false; const style = view.getComputedStyle(node); if (style.display === "none" || style.visibility === "hidden") { return false; } const rect = node.getBoundingClientRect(); return rect.width > 1 && rect.height > 1; } function popoverFor(target) { const view = boundDocument?.defaultView ?? null; if (view === null) return null; const found = target.closest(POPOVER_SELECTOR); if (!(found instanceof HTMLElement)) return null; if (!found.isConnected) return null; if (isPreexistingPopover(found)) return null; const rail = resolvedRail; if (rail !== null && (rail.contains(found) || found.contains(rail))) { return null; } return isVisiblePopover(found, view) ? found : null; } function snapshotPopovers() { preexistingPopovers.clear(); const doc = boundDocument; const view = doc?.defaultView ?? null; if (doc === null || view === null) return; for (const found of Array.from(doc.querySelectorAll(POPOVER_SELECTOR))) { if (!(found instanceof HTMLElement)) continue; if (!isVisiblePopover(found, view)) continue; preexistingPopovers.add(found); } } function visiblePopovers() { const found = /* @__PURE__ */ new Set(); const doc = boundDocument; const view = doc?.defaultView ?? null; if (doc === null || view === null) return found; for (const node of Array.from(doc.querySelectorAll(POPOVER_SELECTOR))) { if (!(node instanceof HTMLElement)) continue; if (!isVisiblePopover(node, view)) continue; found.add(node); } return found; } function isPreexistingPopover(node) { if (preexistingPopovers.size === 0) return false; for (const known of preexistingPopovers) { if (!known.isConnected) continue; if (known === node || known.contains(node)) return true; } return false; } function holdForPopover(rail) { if (holdTimer !== null) { clearTimeout(holdTimer); holdTimer = null; } if (holdRemainingMs <= 0) holdRemainingMs = SIDEBAR_PEEK_POPOVER_HOLD_MS; const step = Math.min(POPOVER_RECHECK_MS, holdRemainingMs); holdRemainingMs -= step; holdTimer = setTimeout(() => { holdTimer = null; if (active !== rail) return; const popover = popoverUnderPointer(); if (popover !== null && holdRemainingMs > 0) { holdForPopover(rail); return; } holdRemainingMs = 0; if (pointerStillOverRail(rail)) return; releaseActive(); }, step); } function pointerStillOverRail(rail) { if (!Number.isFinite(pointerX) || !Number.isFinite(pointerY)) return false; const doc = rail.ownerDocument; if (typeof doc.elementFromPoint !== "function") return false; const current = nativeOnly ? resolveRail() ?? rail : rail; const hit = doc.elementFromPoint(pointerX, pointerY); if (hit instanceof Element) { if (current.contains(hit) || rail.contains(hit)) return true; if (triggerSelector !== "" && hit.closest(triggerSelector) !== null) { return true; } } return withinPeekBand(current, pointerX, pointerY); } function isMousePointer(event) { const pointerType = event.pointerType; return pointerType === void 0 || pointerType === "" || pointerType === "mouse"; } function handlePointerOver(event) { if (!isMousePointer(event)) return; pointerX = event.clientX; pointerY = event.clientY; const target = event.target; if (!(target instanceof Element)) return; const rail = railFor(target); if (rail === null) return; if (active === rail) { liftInert(rail); if (rescanNeeded) { rescanNeeded = false; suppressOverlap(); } } scheduleShow(rail); } function handlePointerMove(event) { if (!isMousePointer(event)) return; const mouse = event; pointerX = mouse.clientX; pointerY = mouse.clientY; const target = event.target; if (target instanceof Element) { const overRail = railFor(target); if (overRail !== null) { if (active === overRail) cancelHide(); else scheduleShow(overRail); return; } } if (!pointerNearEdge()) { suppressShowUntilExit = false; cancelProbe(); if (active !== null) requestHide(active); else if (pendingRail !== null) cancelShow(); return; } scheduleProbe(); } function cancelProbe() { if (probeTimer !== null) { clearTimeout(probeTimer); probeTimer = null; } } function scheduleProbe() { const now = performance.now(); const wait = lastProbeMs + POINTER_PROBE_INTERVAL_MS - now; if (wait > 0) { if (probeTimer === null) { probeTimer = setTimeout(() => { probeTimer = null; runProbe(); }, wait); } return; } runProbe(); } function runProbe() { lastProbeMs = performance.now(); if (!Number.isFinite(pointerX) || !Number.isFinite(pointerY)) return; if (!pointerNearEdge()) { suppressShowUntilExit = false; if (active !== null) requestHide(active); else if (pendingRail !== null) cancelShow(); return; } const open = active; if (open !== null) { if (pointerStillOverRail(open)) { cancelHide(); return; } if (popoverUnderPointer() !== null) { holdForPopover(open); return; } requestHide(open); return; } const rail = nearRail(pointerX, pointerY); if (rail === null) { if (pendingRail !== null) cancelShow(); return; } scheduleShow(rail); } function handlePointerOut(event) { if (!isMousePointer(event)) return; pointerX = event.clientX; pointerY = event.clientY; const target = event.target; if (!(target instanceof Element)) return; const rail = railFor(target); if (rail === null) return; const related = event.relatedTarget; if (related instanceof Element && railFor(related) === rail) return; scheduleHide(rail); } function handlePointerLeave(event) { if (!isMousePointer(event)) return; pointerX = Number.NaN; pointerY = Number.NaN; suppressShowUntilExit = false; cancelProbe(); cancelShow(); if (active !== null) scheduleHide(active); } function requestHide(rail) { if (hideTimer !== null) return; scheduleHide(rail); } function handleClick(event) { const rail = active; if (rail === null) return; const target = event.target; if (!(target instanceof Element)) return; if (!rail.contains(target)) return; if (keepsPeek(target)) return; const anchor = target.closest("a[href]"); const view = rail.ownerDocument.defaultView; if (view !== null && anchor instanceof HTMLAnchorElement) { if (anchor.href === view.location.href) return; } const before = visiblePopovers(); cancelClickRelease(); clickReleaseTimer = setTimeout(() => { clickReleaseTimer = null; if (active !== rail) return; for (const popup of visiblePopovers()) { if (before.has(popup)) continue; holdForPopover(rail); return; } releaseActive("navigation"); suppressShowUntilExit = true; }, SIDEBAR_PEEK_CLICK_RELEASE_MS); } function keepsPeek(target) { if (target.closest( 'input, textarea, select, [contenteditable=""], [contenteditable="true"], [role="menu"], [role="dialog"], [aria-haspopup], [aria-expanded]' ) !== null) { return true; } const nativeExpand = definition?.nativeExpand; if (nativeExpand !== void 0) { for (const selector of [nativeExpand.expand, nativeExpand.collapse]) { if (target.closest(selector) !== null) return true; } } if (collapseTarget !== null && collapseTarget.contains(target)) { return true; } return false; } function handleNavigation() { cancelShow(); if (active !== null) { releaseActive("navigation"); suppressShowUntilExit = true; } } function handlePointerDown(event) { const target = event.target; if (!(target instanceof Element)) return; if (active !== null && popoverFor(target) !== null) { cancelHide(); holdForPopover(active); return; } const rail = railFor(target); if (rail === null) { cancelShow(); releaseActive(); return; } if (active === rail && !rail.contains(target)) { if (triggerSelector !== "" && target.closest(triggerSelector) !== null) { expandedByPeek = false; } releaseActive(); } } function handleFocusIn(event) { const target = event.target; if (!(target instanceof Element)) return; if (performance.now() - lastUserKeyMs > SIDEBAR_PEEK_KEYBOARD_FOCUS_MS) { return; } const rail = railFor(target); if (rail === null) return; if (active === rail) return; if (!isCollapsed(rail)) return; applyPeek(rail); } function handleKeyDown(event) { if (!isUserKey(event)) return; lastUserKeyMs = performance.now(); const key = event.key; if (key === "Escape") { cancelShow(); releaseActive(); return; } if (active === null || key !== "Enter" && key !== " ") return; const target = event.target; if (!(target instanceof Element)) return; if (triggerSelector === "" || target.closest(triggerSelector) === null) { return; } cancelShow(); expandedByPeek = false; releaseActive(); } function handleMutations() { const node = active; if (node === null) return; if (!node.isConnected) { if (expandedByPeek && pointerNearEdge()) { scheduleReacquire(); return; } releaseActive("navigation"); return; } const view = node.ownerDocument.defaultView; if (appliedHref !== "" && view !== null && view.location.href !== appliedHref) { releaseActive("navigation"); return; } rescanNeeded = true; if (node.getAttribute(SIDEBAR_PEEK_ATTRIBUTE) === null) { refreshPeek(node); } if (expandedByPeek) return; if (hasExpandedToken(node)) releaseActive(); } function pointerNearEdge() { if (!Number.isFinite(pointerX) || !Number.isFinite(pointerY)) return false; const doc = boundDocument; if (doc === null) return false; const viewport = doc.documentElement.clientWidth || doc.defaultView?.innerWidth || 0; if (viewport <= 0) return false; const band = Math.max( 120, collapsedMaxWidth + SIDEBAR_PEEK_PROXIMITY_PX, SIDEBAR_PEEK_LANE_PX + SIDEBAR_PEEK_PROXIMITY_PX ); return pointerX <= band || pointerX >= viewport - band; } function bind(doc) { if (boundDocument === doc) return; teardown(); if (!hasRail) return; boundDocument = doc; doc.addEventListener("pointerover", handlePointerOver); doc.addEventListener("pointermove", handlePointerMove); doc.addEventListener("pointerout", handlePointerOut); doc.addEventListener("pointerleave", handlePointerLeave); doc.addEventListener("pointerdown", handlePointerDown); doc.addEventListener("focusin", handleFocusIn); doc.addEventListener("keydown", handleKeyDown); doc.addEventListener("click", handleClick, true); const win = doc.defaultView; if (win !== null) { win.addEventListener("popstate", handleNavigation); win.addEventListener("hashchange", handleNavigation); } const root = doc.documentElement ?? doc.body; if (root !== null) { observer = new MutationObserver(handleMutations); observer.observe(root, { attributes: true, attributeFilter: MOTION_ATTRIBUTES, childList: true, subtree: true }); } } function teardown() { cancelShow(); cancelHide(); cancelNativeCollapse(); releaseActive("lifecycle"); peekBand = null; suppressShowUntilExit = false; releaseTransitions(); finishTransitionHold(); stopRevealWatch(); if (observer !== null) { observer.disconnect(); observer = null; } if (boundDocument !== null) { boundDocument.removeEventListener("pointerover", handlePointerOver); boundDocument.removeEventListener("pointermove", handlePointerMove); boundDocument.removeEventListener("pointerout", handlePointerOut); boundDocument.removeEventListener("pointerleave", handlePointerLeave); boundDocument.removeEventListener("pointerdown", handlePointerDown); boundDocument.removeEventListener("focusin", handleFocusIn); boundDocument.removeEventListener("keydown", handleKeyDown); boundDocument.removeEventListener("click", handleClick, true); const win = boundDocument.defaultView; if (win !== null) { win.removeEventListener("popstate", handleNavigation); win.removeEventListener("hashchange", handleNavigation); } boundDocument = null; } resolveDocument = null; resolvedRail = null; } return { bind, teardown, syncEnabled: () => { if (isEnabled()) return; cancelShow(); releaseActive(); }, isPeeking: () => active !== null }; } // scripts/ai-chat-turbo-engine/src/core/mutation-classify.ts function classifyMutations(records, context) { const dirtyTurns = /* @__PURE__ */ new Set(); const codeRoots = /* @__PURE__ */ new Set(); let requestUpdate = false; let turnStructureChanged = false; const matchesTurn = (element) => { if (!context.turnSelector) return false; try { return element.matches(context.turnSelector); } catch { return false; } }; for (const record of records) { const target = record.target; if (target instanceof Element && context.isIgnoredTarget(target)) { continue; } const indexedTurn = context.findTurnAncestor(target); if (record.type === "attributes") { const attributeName = record.attributeName ?? ""; if (!TURN_MARKER_ATTRIBUTES.has(attributeName)) continue; if (indexedTurn) continue; turnStructureChanged = true; requestUpdate = true; continue; } if (indexedTurn) { dirtyTurns.add(indexedTurn); const codeRoot = target instanceof Element ? target : target.parentElement; if (codeRoot) codeRoots.add(codeRoot); continue; } if (record.type === "characterData") { requestUpdate = true; continue; } requestUpdate = true; for (const node of record.addedNodes) { if (!(node instanceof Element)) continue; if (matchesTurn(node)) turnStructureChanged = true; codeRoots.add(node); } for (const node of record.removedNodes) { if (!(node instanceof Element)) continue; if (matchesTurn(node)) turnStructureChanged = true; } } return { requestUpdate, turnStructureChanged, dirtyTurns, codeRoots }; } // scripts/ai-chat-turbo-engine/src/core/navigation.ts function navigationKey(location2) { return `${location2.pathname}${location2.search}`; } function createNavigationTracker(initialLocation) { let lastKey = navigationKey(initialLocation); return { observe(location2) { const nextKey = navigationKey(location2); if (nextKey === lastKey) return false; lastKey = nextKey; return true; } }; } // shared/storage/keyValue.ts var DEFAULT_MESSAGES = { read: "[shared/storage] read failed", write: "[shared/storage] write failed", remove: "[shared/storage] remove failed", parse: "[shared/storage] invalid JSON" }; function reportFailure(options, operation, error) { if (options.onError !== void 0) { options.onError({ operation, error }); return; } console.error(DEFAULT_MESSAGES[operation], error); } function createStringStorage(storage, options = {}) { const memory = /* @__PURE__ */ new Map(); const useCache = options.cache !== false; const read = (key) => { if (useCache) { const cached = memory.get(key); if (cached !== void 0) return cached; } try { const value = storage.getItem(key); if (useCache && value !== null) memory.set(key, value); return value; } catch (error) { reportFailure(options, "read", error); return null; } }; const write = (key, value) => { if (useCache) memory.set(key, value); try { storage.setItem(key, value); return true; } catch (error) { reportFailure(options, "write", error); return false; } }; const remove = (key) => { if (useCache) memory.delete(key); try { storage.removeItem(key); return true; } catch (error) { reportFailure(options, "remove", error); return false; } }; return { read, write, readJson: (key, fallback) => { const raw = read(key); if (raw === null) return fallback; try { return JSON.parse(raw); } catch (error) { reportFailure(options, "parse", error); return fallback; } }, writeJson: (key, value) => { let serialized; try { serialized = JSON.stringify(value); } catch (error) { reportFailure(options, "write", error); return false; } return write(key, serialized); }, remove }; } function isStorageArea(value) { if (typeof value !== "object" || value === null) return false; return "getItem" in value && "setItem" in value && "removeItem" in value; } function resolveArea(kind) { const area = kind === "localStorage" ? window.localStorage : window.sessionStorage; if (!isStorageArea(area)) { throw new Error(kind + " is unavailable in this frame"); } return area; } function getBrowserStorage(kind, options = {}) { return createStringStorage( { getItem: (key) => resolveArea(kind).getItem(key), setItem: (key, value) => resolveArea(kind).setItem(key, value), removeItem: (key) => resolveArea(kind).removeItem(key) }, options ); } // scripts/ai-chat-turbo-engine/src/storage/reported.ts function createReportedStorage(kind, report) { return getBrowserStorage(kind, { cache: false, onError: report }); } // scripts/ai-chat-turbo-engine/src/state.ts var DEFAULT_PERSISTED_CONFIG = { pruneEnabled: true, keepTurns: 8, messageLimit: DEFAULT_MESSAGE_LIMIT, collapseCode: true, virtualFileEnabled: true, sidebarPeekEnabled: true, sidebarPeekDelayMs: SIDEBAR_PEEK_SHOW_DELAY_MS, sidebarPeekHideDelayMs: SIDEBAR_PEEK_HIDE_DELAY_MS, newChatShortcutLock: true, rememberReasoning: true, rememberTools: true, hudTheme: "auto" }; var configStore = createReportedStorage("localStorage", (failure) => { const scope = failure.operation === "write" || failure.operation === "remove" ? "save engine config" : "load saved engine config"; reportRecoverableError(scope, failure.error); }); function clampSidebarPeekDelay(rawDelay, fallback) { const numericDelay = Number(rawDelay); if (!Number.isFinite(numericDelay)) return fallback; return Math.min( SIDEBAR_PEEK_DELAY_MAX, Math.max(SIDEBAR_PEEK_DELAY_MIN, Math.round(numericDelay)) ); } function normalizeSidebarPeekDelay(rawDelay) { return clampSidebarPeekDelay(rawDelay, SIDEBAR_PEEK_SHOW_DELAY_MS); } function normalizeSidebarPeekHideDelay(rawDelay) { return clampSidebarPeekDelay(rawDelay, SIDEBAR_PEEK_HIDE_DELAY_MS); } function createEngineState() { return { ...DEFAULT_PERSISTED_CONFIG, hudOpen: false, totalTurns: 0, hiddenCount: 0, foldedCodeCount: 0, indexedTurns: [] }; } function normalizeMessageLimit(rawLimit) { const numericLimit = Number(rawLimit); if (!Number.isFinite(numericLimit)) return DEFAULT_MESSAGE_LIMIT; return Math.min( MESSAGE_LIMIT_MAX, Math.max(MESSAGE_LIMIT_MIN, Math.round(numericLimit)) ); } function isSavedConfig(value) { return typeof value === "object" && value !== null; } function loadSavedConfig(state) { try { const raw = configStore.read(STORAGE_KEY_CONFIG); if (raw === null || raw === "") return; const parsed = JSON.parse(raw); if (!isSavedConfig(parsed)) return; if (typeof parsed.keepTurns === "number" && !isNaN(parsed.keepTurns)) { state.keepTurns = Math.max(2, Math.min(50, parsed.keepTurns)); } if (typeof parsed.messageLimit === "number" && Number.isFinite(parsed.messageLimit)) { state.messageLimit = normalizeMessageLimit(parsed.messageLimit); } if (typeof parsed.pruneEnabled === "boolean") { state.pruneEnabled = parsed.pruneEnabled; } if (typeof parsed.collapseCode === "boolean") { state.collapseCode = parsed.collapseCode; } if (typeof parsed.virtualFileEnabled === "boolean") { state.virtualFileEnabled = parsed.virtualFileEnabled; } if (typeof parsed.sidebarPeekEnabled === "boolean") { state.sidebarPeekEnabled = parsed.sidebarPeekEnabled; } if (typeof parsed.sidebarPeekDelayMs === "number" && Number.isFinite(parsed.sidebarPeekDelayMs)) { state.sidebarPeekDelayMs = normalizeSidebarPeekDelay( parsed.sidebarPeekDelayMs ); } if (typeof parsed.sidebarPeekHideDelayMs === "number" && Number.isFinite(parsed.sidebarPeekHideDelayMs)) { state.sidebarPeekHideDelayMs = normalizeSidebarPeekHideDelay( parsed.sidebarPeekHideDelayMs ); } if (typeof parsed.newChatShortcutLock === "boolean") { state.newChatShortcutLock = parsed.newChatShortcutLock; } if (typeof parsed.rememberReasoning === "boolean") { state.rememberReasoning = parsed.rememberReasoning; } if (typeof parsed.rememberTools === "boolean") { state.rememberTools = parsed.rememberTools; } if (parsed.hudTheme === "auto" || parsed.hudTheme === "light" || parsed.hudTheme === "dark") { state.hudTheme = parsed.hudTheme; } } catch (error) { reportRecoverableError("load saved engine config", error); } } function resetPersistedConfig(state) { Object.assign(state, DEFAULT_PERSISTED_CONFIG); } function saveCurrentConfig(state) { try { const config = { keepTurns: state.keepTurns, messageLimit: state.messageLimit, pruneEnabled: state.pruneEnabled, collapseCode: state.collapseCode, virtualFileEnabled: state.virtualFileEnabled, sidebarPeekEnabled: state.sidebarPeekEnabled, sidebarPeekDelayMs: state.sidebarPeekDelayMs, sidebarPeekHideDelayMs: state.sidebarPeekHideDelayMs, newChatShortcutLock: state.newChatShortcutLock, rememberReasoning: state.rememberReasoning, rememberTools: state.rememberTools, hudTheme: state.hudTheme }; configStore.write(STORAGE_KEY_CONFIG, JSON.stringify(config)); } catch (error) { reportRecoverableError("save engine config", error); } } // scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts function createCodeBlockUtils(deps) { const { currentPlatform, state, el, withSelfMutation, filterOutNested, isGeminiThoughtElement, requestUpdate } = deps; const codeState = /* @__PURE__ */ new Map(); const dirtyCodeBlocks = /* @__PURE__ */ new Set(); const observedCodeBlocks = /* @__PURE__ */ new Set(); const pendingCodeRoots = /* @__PURE__ */ new Set(); const watchedCodeBlocks = /* @__PURE__ */ new Set(); const viewportReadyCodeBlocks = /* @__PURE__ */ new Set(); let codeScanRequested = true; let codeResizeObserver = null; let codeViewportObserver = null; let barsDirty = false; const codeSelectorText = (currentPlatform.codeSelectors || ["pre"]).join( "," ); const userTurnSelectorText = (currentPlatform.userTurnSelectors || []).join( "," ); const CODE_VIEWPORT_MARGIN = "800px 0px"; function normalizeCodeElement(candidate) { if (!(candidate instanceof HTMLElement)) return null; const geminiBlock = candidate.closest("code-block"); if (geminiBlock instanceof HTMLElement) return geminiBlock; if (candidate.matches("code")) { return candidate.parentElement?.matches("pre") ? candidate.parentElement : candidate; } return candidate; } function isInsideUserTurn(candidate) { if (!userTurnSelectorText) return false; try { return candidate.matches(userTurnSelectorText) || Boolean(candidate.closest(userTurnSelectorText)); } catch (error) { reportRecoverableError("test code card boundary", error); return false; } } function toCodeElement(candidate) { if (candidate.closest(".ai-turbo-dehydrated")) return null; const belongsToUserTurn = isInsideUserTurn(candidate); if (candidate.classList.contains("ai-turbo-chat-folded-target") || belongsToUserTurn || candidate.closest( ".ai-turbo-chat-folded-target, .ai-turbo-chat-capsule, user-query, [data-message-author-role='user'], [data-content-search-unit-key$=':user'], [data-user-message-bubble='true'], [data-testid='collapsible-user-message-root'], .font-user-message" )) { return null; } const codeElement = normalizeCodeElement(candidate); if (!codeElement) return null; if (isGeminiThoughtElement(codeElement)) return null; return codeElement; } function collectCodeElements(rootNode) { const collected = []; const nearest = rootNode.closest(codeSelectorText); if (nearest) { const codeElement = toCodeElement(nearest); if (codeElement) collected.push(codeElement); } rootNode.querySelectorAll(codeSelectorText).forEach((candidate) => { const codeElement = toCodeElement(candidate); if (codeElement) collected.push(codeElement); }); return filterOutNested(collected).filter( (element) => element instanceof HTMLElement ); } function getCodeBlocks(rootNode = document) { const collected = []; rootNode.querySelectorAll(codeSelectorText).forEach((candidate) => { const codeElement = toCodeElement(candidate); if (codeElement) collected.push(codeElement); }); return filterOutNested(collected).filter( (element) => element instanceof HTMLElement ); } function getCodeText(codeElement) { const sourceElement = codeElement.querySelector("pre code") || codeElement.querySelector("pre") || codeElement.querySelector("code") || codeElement; return typeof sourceElement.textContent === "string" ? sourceElement.textContent : ""; } function getCodeLanguage(codeElement) { const langElem = codeElement.querySelector( 'code[class*="language-"], [class*="language-"]' ); if (langElem) { const match = String(langElem.className || "").match( /language-([a-z0-9+#.-]+)/i ); if (match) return (match[1] ?? "").toUpperCase(); } const decElem = codeElement.querySelector( ".code-block-decoration, [data-testid*='language']" ); const decText = decElem?.textContent?.trim(); if (decText && decText.length < 24) return decText.toUpperCase(); const attrLang = codeElement.getAttribute("data-language") || codeElement.getAttribute("lang"); if (attrLang) return attrLang.toUpperCase(); return "代码"; } function getCodeElementHeight(codeElement) { const rectHeight = Math.round(codeElement.getBoundingClientRect().height); if (rectHeight > 0) return rectHeight; const pre = codeElement.querySelector("pre"); return Math.max( codeElement.scrollHeight || 0, codeElement.offsetHeight || 0, pre?.scrollHeight || 0, pre?.offsetHeight || 0 ); } function applyFoldStyles(entry, codeElement) { withSelfMutation(() => { if (entry.expanded) { codeElement.classList.remove("ai-turbo-folded"); codeElement.classList.add("ai-turbo-expanded"); codeElement.style.removeProperty("max-height"); codeElement.style.removeProperty("overflow"); } else { codeElement.classList.remove("ai-turbo-expanded"); codeElement.classList.add("ai-turbo-folded"); codeElement.style.setProperty("display", "block", "important"); codeElement.style.setProperty( "max-height", `${CODE_PREVIEW_HEIGHT}px`, "important" ); codeElement.style.setProperty("overflow", "hidden", "important"); } }); } function updateCodeMeta(entry, codeElement) { if (!entry || !codeElement?.isConnected) return; if (entry.renderedStaticOnce && !entry.isDisplayingStreaming && !dirtyCodeBlocks.has(codeElement)) { return; } const currentText = getCodeText(codeElement); const currentLen = currentText.length; const now = Date.now(); if (currentLen !== entry.lastLength) { entry.lastLength = currentLen; entry.lastMutationTime = now; entry.renderedStaticOnce = false; } const isActivelyStreaming = entry.lastMutationTime > 0 && now - entry.lastMutationTime < STREAMING_IDLE_DELAY; if (isActivelyStreaming) { if (!entry.isDisplayingStreaming) { entry.isDisplayingStreaming = true; entry.langLabel.textContent = getCodeLanguage(codeElement); entry.linesLabel.textContent = ""; entry.linesLabel.appendChild( el("span", { className: "ai-turbo-streaming-badge" }, [ "● 正在输出..." ]) ); entry.toggleButton.textContent = entry.expanded ? "收起代码" : "展开代码"; } if (entry.streamingTimer) clearTimeout(entry.streamingTimer); entry.streamingTimer = setTimeout(() => { updateCodeMeta(entry, codeElement); }, STREAMING_IDLE_DELAY + 50); return; } entry.isDisplayingStreaming = false; entry.renderedStaticOnce = true; const lineCount = fastCountLines(currentText); entry.langLabel.textContent = getCodeLanguage(codeElement); entry.linesLabel.textContent = lineCount ? `${lineCount.toLocaleString()} 行` : ""; entry.toggleButton.textContent = entry.expanded ? "收起代码" : `展开 ${lineCount ? `${lineCount.toLocaleString()} 行` : "代码"}`; entry.toggleButton.setAttribute("aria-expanded", String(entry.expanded)); } function observeCodeElement(codeElement) { if (!codeResizeObserver || observedCodeBlocks.has(codeElement)) return; observedCodeBlocks.add(codeElement); codeResizeObserver.observe(codeElement); } function unobserveCodeElement(codeElement) { if (!observedCodeBlocks.delete(codeElement)) return; codeResizeObserver?.unobserve(codeElement); } function supportsViewportObservation() { return "IntersectionObserver" in window; } function observeCodeViewport(codeElement) { if (!codeViewportObserver || watchedCodeBlocks.has(codeElement)) return; watchedCodeBlocks.add(codeElement); codeViewportObserver.observe(codeElement); } function unobserveCodeViewport(codeElement) { viewportReadyCodeBlocks.delete(codeElement); if (!watchedCodeBlocks.delete(codeElement)) return; codeViewportObserver?.unobserve(codeElement); } function ensureCodeViewportObserver() { if (codeViewportObserver || !supportsViewportObservation()) return; codeViewportObserver = new IntersectionObserver( (entries) => { let queued = false; for (const viewportEntry of entries) { if (!viewportEntry.isIntersecting) continue; const target = viewportEntry.target; if (!(target instanceof HTMLElement)) continue; unobserveCodeViewport(target); if (!target.isConnected) continue; dirtyCodeBlocks.add(normalizeCodeElement(target) ?? target); viewportReadyCodeBlocks.add(target); queued = true; } if (queued) requestUpdate(); }, { rootMargin: CODE_VIEWPORT_MARGIN, threshold: 0 } ); } function releaseCodeViewportWatchers() { for (const watched of Array.from(watchedCodeBlocks)) { unobserveCodeViewport(watched); } codeViewportObserver?.disconnect(); codeViewportObserver = null; watchedCodeBlocks.clear(); viewportReadyCodeBlocks.clear(); } function unmountCodeControls(codeElement) { const entry = codeState.get(codeElement); if (!entry) return; if (entry.streamingTimer) clearTimeout(entry.streamingTimer); withSelfMutation(() => { entry.bar?.remove(); codeElement.classList.remove( "ai-turbo-code-target", "ai-turbo-folded", "ai-turbo-expanded" ); codeElement.style.removeProperty("max-height"); codeElement.style.removeProperty("overflow"); codeElement.style.removeProperty("display"); }); codeState.delete(codeElement); dirtyCodeBlocks.delete(codeElement); unobserveCodeElement(codeElement); unobserveCodeViewport(codeElement); barsDirty = true; } function isNativeCodeHeaderNode(node) { if (!(node instanceof HTMLElement)) return false; try { if (node.matches(CHATGPT_CODE_HEADER_MARKER_SELECTOR) || node.querySelector(CHATGPT_CODE_HEADER_MARKER_SELECTOR)) { return true; } } catch (error) { reportRecoverableError("inspect native code header", error); return false; } const className = typeof node.className === "string" ? node.className : ""; const markerText = [ className, node.getAttribute("data-testid") || "", node.getAttribute("aria-label") || "", node.getAttribute("title") || "" ].join(" "); if (/(?:code|language).*(?:header|toolbar|decoration)|(?:header|toolbar).*(?:code|language)/i.test( markerText )) { return true; } if (node.querySelector("button") && !node.querySelector("pre, code")) { const headerText = (node.textContent || "").trim(); if (headerText.length > 0 && headerText.length <= 64 && (/^(?:[a-z0-9_+#.-]+)$/i.test(headerText) || /copy|复制|运行代码|code block/i.test(headerText))) { return true; } } return false; } function getChatGPTCodeCardAnchor(codeElement) { let branch = codeElement; let parent = codeElement.parentElement; let classBasedFallback = null; let depth = 0; while (parent instanceof HTMLElement && depth < CHATGPT_CODE_CARD_MAX_ANCESTORS) { if (parent.matches(CHATGPT_CODE_CARD_BOUNDARY_SELECTOR)) break; let precedingSibling = branch.previousElementSibling; while (precedingSibling) { if (isNativeCodeHeaderNode(precedingSibling)) { return parent.contains(codeElement) ? parent : null; } precedingSibling = precedingSibling.previousElementSibling; } const className = typeof parent.className === "string" ? parent.className : ""; const cardMarker = [ className, parent.getAttribute("data-testid") || "", parent.getAttribute("data-role") || "" ].join(" "); if (/(?:code[-_ ]?(?:block|card|container)|(?:block|card)[-_ ]?code|group\/code)/i.test( cardMarker )) { classBasedFallback = parent; } branch = parent; parent = parent.parentElement; depth++; } return classBasedFallback instanceof HTMLElement && classBasedFallback.isConnected && classBasedFallback.contains(codeElement) ? classBasedFallback : null; } function getCodeControlAnchor(codeElement) { if (!currentPlatform.codeCardChrome) return codeElement; return getChatGPTCodeCardAnchor(codeElement); } function positionCodeControl(entry, codeElement) { const anchor = getCodeControlAnchor(codeElement); if (!(anchor instanceof HTMLElement) || anchor === codeElement) { unmountCodeControls(codeElement); return false; } if (entry.anchor === anchor && entry.bar.isConnected && entry.bar.nextElementSibling === anchor) { return true; } withSelfMutation(() => { entry.bar.remove(); anchor.insertAdjacentElement("beforebegin", entry.bar); entry.anchor = anchor; }); return true; } function flashCopyState(button, label) { button.textContent = label; window.setTimeout(() => { if (button.isConnected) button.textContent = "复制"; }, 1200); } function copyCodeText(button, codeElement) { const text = getCodeText(codeElement); if (!navigator.clipboard?.writeText) { flashCopyState(button, "不可用"); return; } navigator.clipboard.writeText(text).then( () => flashCopyState(button, "已复制"), () => flashCopyState(button, "复制失败") ); } function mountCodeControls(codeElement) { if (!state.collapseCode || !codeElement.isConnected || codeState.has(codeElement)) return; if (codeElement.parentElement?.closest(".ai-turbo-code-target")) return; const measuredH = getCodeElementHeight(codeElement); if (measuredH <= CODE_COLLAPSE_HEIGHT) return; const anchor = getCodeControlAnchor(codeElement); if (currentPlatform.codeCardChrome && (!(anchor instanceof HTMLElement) || anchor === codeElement)) { return; } let sibling = codeElement.previousElementSibling; while (sibling && sibling.classList.contains("ai-turbo-code-bar")) { const toRemove = sibling; sibling = sibling.previousElementSibling; toRemove.remove(); } const initialText = getCodeText(codeElement); const langLabel = el("span", { className: "ai-turbo-code-lang" }); const linesLabel = el("span", { className: "ai-turbo-code-lines" }); const metaWrap = el("div", { className: "ai-turbo-code-bar-meta" }, [ langLabel, linesLabel ]); const toggleButton = el("button", { type: "button", className: "ai-turbo-code-toggle", "aria-expanded": "false" }); const copyButton = el("button", { type: "button", className: "ai-turbo-code-copy", "aria-label": "复制整段代码" }); copyButton.textContent = "复制"; copyButton.addEventListener("click", () => { copyCodeText(copyButton, codeElement); }); const actionsWrap = el("div", { className: "ai-turbo-code-bar-actions" }, [ copyButton, toggleButton ]); const bar = el( "div", { className: currentPlatform.codeCardChrome ? "ai-turbo-code-bar ai-turbo-code-bar-chatgpt" : "ai-turbo-code-bar" }, [metaWrap, actionsWrap] ); const entry = { bar, anchor, langLabel, linesLabel, toggleButton, expanded: false, lastLength: initialText.length, lastMutationTime: 0, streamingTimer: null, isDisplayingStreaming: false, renderedStaticOnce: false }; if (!(anchor instanceof HTMLElement)) return; codeState.set(codeElement, entry); withSelfMutation(() => { codeElement.classList.add("ai-turbo-code-target"); anchor.insertAdjacentElement("beforebegin", bar); }); toggleButton.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); entry.expanded = !entry.expanded; applyFoldStyles(entry, codeElement); entry.renderedStaticOnce = false; updateCodeMeta(entry, codeElement); if (!entry.expanded) { bar.scrollIntoView({ block: "nearest", behavior: "smooth" }); } }); applyFoldStyles(entry, codeElement); updateCodeMeta(entry, codeElement); observeCodeElement(codeElement); barsDirty = true; } function sweepOrphanBars() { const activeBars = new Set( Array.from(codeState.values(), (entry) => entry.bar) ); document.querySelectorAll(".ai-turbo-code-bar").forEach((bar) => { if (!activeBars.has(bar)) { bar.remove(); return; } if (bar.classList.contains("ai-turbo-code-bar-chatgpt")) return; const next = bar.nextElementSibling; const nextEntry = next instanceof HTMLElement ? codeState.get(next) : void 0; if (!(next instanceof HTMLElement) || !nextEntry || nextEntry.bar !== bar) { bar.remove(); } }); } function expandPendingCodeRoots() { if (pendingCodeRoots.size === 0) return []; const expanded = []; for (const root of pendingCodeRoots) { if (!root.isConnected) continue; if (root.closest(".ai-turbo-dehydrated")) continue; expanded.push(...collectCodeElements(root)); } pendingCodeRoots.clear(); return expanded; } function syncCodeBlocks(forceScan, dirtyCandidates) { const queuedRootCandidates = expandPendingCodeRoots(); if (!state.collapseCode) { for (const [codeElement] of codeState) { unmountCodeControls(codeElement); } state.foldedCodeCount = 0; codeScanRequested = false; dirtyCodeBlocks.clear(); queuedRootCandidates.length = 0; releaseCodeViewportWatchers(); sweepOrphanBars(); return; } for (const [codeElement] of codeState) { if (!codeElement.isConnected) { unmountCodeControls(codeElement); } } const rawCandidates = [ ...forceScan ? getCodeBlocks() : [], ...queuedRootCandidates, ...Array.from(dirtyCandidates).map(normalizeCodeElement).filter( (elem) => elem instanceof HTMLElement && elem.isConnected && !elem.closest(".ai-turbo-dehydrated") ) ]; const candidates = filterOutNested(rawCandidates).filter( (element) => element instanceof HTMLElement ); for (const codeElement of candidates) { const entry = codeState.get(codeElement); if (entry) { if (currentPlatform.codeCardChrome && !positionCodeControl(entry, codeElement)) { continue; } updateCodeMeta(entry, codeElement); } else if (codeViewportObserver && !viewportReadyCodeBlocks.has(codeElement)) { observeCodeViewport(codeElement); } else { viewportReadyCodeBlocks.delete(codeElement); mountCodeControls(codeElement); } } if (barsDirty) { sweepOrphanBars(); barsDirty = false; } state.foldedCodeCount = Array.from(codeState.values()).filter( (entry) => !entry.expanded ).length; codeScanRequested = false; dirtyCodeBlocks.clear(); } function observeCodeLayout() { ensureCodeViewportObserver(); if (!("ResizeObserver" in window)) return; codeResizeObserver?.disconnect(); observedCodeBlocks.clear(); codeResizeObserver = new ResizeObserver((entries) => { for (const resizeEntry of entries) { const normalized = normalizeCodeElement(resizeEntry.target); if (normalized instanceof HTMLElement) { dirtyCodeBlocks.add(normalized); } } if (entries.length) requestUpdate(); }); for (const codeElement of codeState.keys()) { observeCodeElement(codeElement); } } function flushCodeBlockScan() { syncCodeBlocks(codeScanRequested, dirtyCodeBlocks); } function unmountAllCodeControls() { for (const codeElement of Array.from(codeState.keys())) { unmountCodeControls(codeElement); } pendingCodeRoots.clear(); dirtyCodeBlocks.clear(); releaseCodeViewportWatchers(); } function disconnectCodeLayoutObserver() { codeResizeObserver?.disconnect(); codeResizeObserver = null; observedCodeBlocks.clear(); pendingCodeRoots.clear(); dirtyCodeBlocks.clear(); releaseCodeViewportWatchers(); } function requestCodeScan() { codeScanRequested = true; } function markCodeBlockDirty(codeElement) { if (codeElement.closest(".ai-turbo-dehydrated")) return; dirtyCodeBlocks.add(codeElement); } function requestCodeScanForTurn(turnElement) { if (!state.collapseCode) return; if (turnElement.closest(".ai-turbo-dehydrated")) return; let queued = false; for (const codeElement of collectCodeElements(turnElement)) { dirtyCodeBlocks.add(codeElement); queued = true; } if (queued) requestUpdate(); } function suspendTurnCodeBlocks(turnElement) { for (const codeElement of Array.from(codeState.keys())) { if (codeElement === turnElement || turnElement.contains(codeElement)) { unmountCodeControls(codeElement); } } for (const codeElement of Array.from(dirtyCodeBlocks)) { if (codeElement === turnElement || turnElement.contains(codeElement)) { dirtyCodeBlocks.delete(codeElement); } } for (const watched of Array.from(watchedCodeBlocks)) { if (watched === turnElement || turnElement.contains(watched)) { unobserveCodeViewport(watched); } } for (const root of Array.from(pendingCodeRoots)) { if (root === turnElement || turnElement.contains(root)) { pendingCodeRoots.delete(root); } } state.foldedCodeCount = Array.from(codeState.values()).filter( (entry) => !entry.expanded ).length; } function markCodeSubtreesDirty(roots) { for (const root of roots) { if (!root.isConnected) continue; if (root.closest(".ai-turbo-dehydrated")) continue; pendingCodeRoots.add(root); } } function isCodeScanPending() { return codeScanRequested || dirtyCodeBlocks.size > 0 || pendingCodeRoots.size > 0; } return { normalizeCodeElement, flushCodeBlockScan, unmountAllCodeControls, observeCodeLayout, disconnectCodeLayoutObserver, requestCodeScan, requestCodeScanForTurn, suspendTurnCodeBlocks, markCodeSubtreesDirty, markCodeBlockDirty, isCodeScanPending }; } // scripts/ai-chat-turbo-engine/src/core/auth.ts var AUTH_ROUTE_SEGMENTS = /* @__PURE__ */ new Set([ "auth", "auth0", "authorize", "authorization", "oauth", "oauth2", "openid", "sso", "saml", "login", "log-in", "signin", "sign-in", "sign_in", "signup", "sign-up", "sign_up", "register", "registration", "callback", "magic-link", "magiclink", "verify", "verification", "mfa", "2fa", "otp", "account", "accounts", "account-chooser", "choose-account", "switch-account", "challenge", "captcha", "consent", "redirect", "recover", "recovery", "reset-password", "forgot-password", "password" ]); var AUTH_HOSTNAME_PREFIXES = [ "auth.", "auth0.", "login.", "signin.", "accounts.", "sso." ]; var engineActive = false; function setEngineActive(active) { engineActive = active; } function isEngineActive() { return engineActive; } function isAuthOrRedirectRoute(locationLike) { const source = locationLike || window.location; if (!source) return false; const hostname = String(source.hostname || "").toLowerCase(); if (AUTH_HOSTNAME_PREFIXES.some((prefix) => hostname.startsWith(prefix))) { return true; } const pathname = String(source.pathname || "").toLowerCase(); if (!pathname) return false; return pathname.split("/").filter(Boolean).some( (segment) => AUTH_ROUTE_SEGMENTS.has(segment.replace(/\.(?:html?|php|aspx?)$/, "")) ); } function isEngineDormant() { return !engineActive || isAuthOrRedirectRoute(); } function detectPlatform() { return findPlatformForLocation( window.location.hostname, window.location.pathname ); } // scripts/ai-chat-turbo-engine/src/core/restore-coordination.ts function createRestoreCoordinator() { let active = null; const pending = { reasoning: false, tools: false }; return { setPending(owner, value) { pending[owner] = value; }, isPending(owner) { return pending[owner]; }, tryAcquire(owner) { if (active === null || active === owner) { active = owner; return true; } return false; }, release(owner) { if (active === owner) active = null; }, activeOwner() { return active; } }; } // scripts/ai-chat-turbo-engine/src/storage/reasoning-memory.ts var memoryStore = createReportedStorage("localStorage", (failure) => { const scope = failure.operation === "write" || failure.operation === "remove" ? "save reasoning memory" : "load reasoning memory"; reportRecoverableError(scope, failure.error); }); function isObjectRecord(value) { return typeof value === "object" && value !== null; } function toReasoningRecord(value) { if (!isObjectRecord(value)) return null; const mode = value["mode"]; if (mode !== "choice" && mode !== "toggle") return null; const record = { mode }; const key = value["key"]; if (typeof key === "string") record.key = key; const controlLabel = value["controlLabel"]; if (typeof controlLabel === "string") record.controlLabel = controlLabel; const option = value["option"]; if (typeof option === "string") record.option = option; const hint = value["hint"]; if (typeof hint === "string") record.hint = hint; const resultLabel = value["resultLabel"]; if (typeof resultLabel === "string") record.resultLabel = resultLabel; const label = value["label"]; if (typeof label === "string") record.label = label; const on = value["on"]; if (typeof on === "boolean") record.on = on; const ts = value["ts"]; if (typeof ts === "number") record.ts = ts; const path = value["path"]; if (Array.isArray(path)) { record.path = path.filter((part) => typeof part === "string"); } return record; } function loadReasoningMemory() { try { const raw = memoryStore.read(STORAGE_KEY_REASONING); const parsed = raw === null || raw === "" ? {} : JSON.parse(raw); if (!isObjectRecord(parsed)) return {}; const memory = {}; for (const [scope, entry] of Object.entries(parsed)) { const record = toReasoningRecord(entry); if (record) memory[scope] = record; } return memory; } catch (error) { reportRecoverableError("load reasoning memory", error); return {}; } } function saveReasoningMemory(memory) { memoryStore.writeJson(STORAGE_KEY_REASONING, memory); } function reasoningScope() { const account = location.pathname.match(/^\/u\/(\d+)(?:\/|$)/); return account ? `${location.hostname}#u${account[1]}` : location.hostname; } function readReasoningRecord(memory) { const all = memory ?? loadReasoningMemory(); const scoped = all[reasoningScope()]; if (scoped) return scoped; return all[location.hostname] ?? null; } function writeReasoningRecord(record) { const memory = loadReasoningMemory(); const scope = reasoningScope(); memory[scope] = record; if (scope !== location.hostname) delete memory[location.hostname]; saveReasoningMemory(memory); return record; } function clearReasoningRecord() { const memory = loadReasoningMemory(); delete memory[reasoningScope()]; delete memory[location.hostname]; saveReasoningMemory(memory); } // scripts/ai-chat-turbo-engine/src/storage/yuanbao-selection.ts var selectionStore = createReportedStorage("localStorage", (failure) => { const scope = failure.operation === "write" || failure.operation === "remove" ? "save Yuanbao selection" : "load Yuanbao selection"; reportRecoverableError(scope, failure.error); }); var MAX_LABEL = 120; function cleanLabel(raw) { if (typeof raw !== "string") return ""; return raw.replace(/\s+/g, " ").trim().slice(0, MAX_LABEL); } function toSelectionRecord(value) { if (!isObjectRecord(value)) return null; const model = cleanLabel(value["model"]); const mode = cleanLabel(value["mode"]); if (!model && !mode) return null; const record = {}; if (model) record.model = model; if (mode) record.mode = mode; const ts = value["ts"]; if (typeof ts === "number" && Number.isFinite(ts)) record.ts = ts; return record; } function loadYuanbaoSelectionMemory() { try { const raw = selectionStore.read(STORAGE_KEY_YUANBAO_SELECTION); const parsed = raw === null || raw === "" ? {} : JSON.parse(raw); if (!isObjectRecord(parsed)) return {}; const memory = {}; for (const [scope, entry] of Object.entries(parsed)) { const record = toSelectionRecord(entry); if (record) memory[scope] = record; } return memory; } catch (error) { reportRecoverableError("load Yuanbao selection", error); return {}; } } function saveYuanbaoSelectionMemory(memory) { selectionStore.writeJson(STORAGE_KEY_YUANBAO_SELECTION, memory); } function readYuanbaoSelectionRecord(memory) { const all = memory ?? loadYuanbaoSelectionMemory(); return all[reasoningScope()] ?? all[location.hostname] ?? null; } function writeYuanbaoSelectionRecord(record) { const memory = loadYuanbaoSelectionMemory(); const scope = reasoningScope(); memory[scope] = record; if (scope !== location.hostname) delete memory[location.hostname]; saveYuanbaoSelectionMemory(memory); return record; } function clearYuanbaoSelectionRecord() { const memory = loadYuanbaoSelectionMemory(); delete memory[reasoningScope()]; delete memory[location.hostname]; saveYuanbaoSelectionMemory(memory); } // scripts/ai-chat-turbo-engine/src/core/reasoning.ts function createReasoningUtils(deps) { const { el, state, toolScope, withSelfMutation, triggerSendButton, requestUpdate, markRestoredTurn, requestFullTurnSync, restoreCoordinator: providedCoordinator } = deps; const restoreCoordinator = providedCoordinator ?? createRestoreCoordinator(); let reasoningStatusNode = null; let reasoningRestoreTimer = 0; let reasoningRestoreAttempts = 0; let reasoningRestoreDone = false; let reasoningRestorePending = false; let yuanbaoMissingTriggerAttempts = 0; let applyingReasoning = false; let restoreToken = 0; const correctedToggleAttempts = /* @__PURE__ */ new Set(); const choiceRestoreAttempts = /* @__PURE__ */ new Map(); const popupCloseTimers = []; const yuanbaoRecordTimers = []; let conversationKey = `${location.origin}${location.pathname}`; let reasoningSettleTimer = 0; let reasoningMenuTrigger = null; let reasoningMenuTriggerAt = 0; let reasoningMenuTriggerLabel = ""; let yuanbaoActionStatus = ""; let yuanbaoAppliedKey = ""; let yuanbaoAppliedAt = 0; const YUANBAO_APPLIED_WINDOW_MS = 15e3; function setReasoningPending(value) { reasoningRestorePending = value; restoreCoordinator.setPending("reasoning", value); } function releaseReasoningRestore() { setReasoningPending(false); restoreCoordinator.release("reasoning"); } function isInsideTurboUI3(node) { if (!(node instanceof Element)) return false; return Boolean(node.closest("[id^='ai-turbo-'], .ai-turbo-code-bar")); } function controlLabel(control) { const visible = String(control.innerText || "").replace(/\s+/g, " ").trim(); const raw = visible || control.getAttribute("aria-label") || control.getAttribute("title") || control.textContent || ""; return raw.replace(/\s+/g, " ").trim().slice(0, 60); } function hasPopupSemantics(control) { if (control.hasAttribute("aria-expanded")) return true; const popup = control.getAttribute("aria-haspopup"); if (popup !== null && popup !== "false") return true; if (control.hasAttribute("gemmenutrigger")) return true; if (control.hasAttribute("cdkoverlayorigin")) return true; if (control.matches("[data-radix-menu-trigger], .mat-mdc-menu-trigger")) { return true; } return false; } function explicitToggleState(control) { if (control instanceof HTMLInputElement) { if (control.type !== "checkbox" && control.type !== "radio") return null; return control.checked === true; } const input = control.querySelector( 'input[type="checkbox"], input[type="radio"]' ); if (input instanceof HTMLInputElement) return input.checked === true; const pressed = control.getAttribute("aria-pressed"); if (pressed === "true" || pressed === "false") return pressed === "true"; const checked = control.getAttribute("aria-checked"); if (checked === "true" || checked === "false") return checked === "true"; const dataState = control.getAttribute("data-state"); if (dataState === "on" || dataState === "checked" || dataState === "active") { return true; } if (dataState === "off" || dataState === "unchecked" || dataState === "inactive") { return false; } return null; } function controlOnState(control) { const explicit = explicitToggleState(control); if (explicit !== null) return explicit; if (hasPopupSemantics(control)) return null; const dataState = control.getAttribute("data-state"); if (dataState !== null && dataState !== "") { return /^(selected|true)$/i.test(dataState) ? true : null; } const cls = control.className; if (/(^|[\s_-])(active|selected|checked|is-on)([\s_-]|$)/i.test(cls)) return true; return null; } function controlKey(control) { const raw = control.getAttribute("data-test-id") || control.getAttribute("data-testid") || control.id || control.getAttribute("aria-label") || ""; return String(raw).replace(/\s+/g, " ").trim().slice(0, 60); } function toggleAttemptKey(control, desired) { const identity = controlKey(control) || controlLabel(control) || "reasoning-toggle"; return `${conversationKey}|${identity}|${desired ? "on" : "off"}`; } function choiceAttemptKey(control, saved) { const path = Array.isArray(saved.path) ? saved.path.join(">") : ""; return `${conversationKey}|${controlKey(control)}|${saved.option || ""}|${path}`; } function syncConversationScope() { const nextKey = `${location.origin}${location.pathname}`; if (nextKey === conversationKey) return; conversationKey = nextKey; correctedToggleAttempts.clear(); choiceRestoreAttempts.clear(); } function clickControlOnce(control) { try { control.click(); return true; } catch (error) { reportRecoverableError("restore reasoning control", error); return false; } } function hoverControlOnce(control) { try { const rect = control.getBoundingClientRect(); const init = { bubbles: true, cancelable: true, clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 }; control.dispatchEvent(new MouseEvent("mouseover", init)); control.dispatchEvent(new MouseEvent("mousemove", init)); return true; } catch (error) { reportRecoverableError("hover reasoning control", error); return false; } } function beginRestore() { restoreToken += 1; applyingReasoning = false; return restoreToken; } function restoreIsStale(token) { return token !== restoreToken; } function settleToggleCorrection(control, desired, token) { let attempts = 0; const check = () => { reasoningSettleTimer = 0; if (restoreIsStale(token)) return; attempts += 1; const current = controlOnState(control); if (current === desired || attempts >= 8 || !control.isConnected) { applyingReasoning = false; return; } reasoningSettleTimer = window.setTimeout(check, 100); }; check(); } function isDropdownTrigger(control) { if (control.hasAttribute("aria-expanded")) return true; const popup = control.getAttribute("aria-haspopup"); if (popup !== null && popup !== "false") return true; if (control.hasAttribute("gemmenutrigger") || control.hasAttribute("cdkoverlayorigin")) return true; if (control.matches("[data-state], [data-radix-menu-trigger], .mat-mdc-menu-trigger")) return true; const label = control.getAttribute("aria-label") || ""; return /^(open|选择|打开).{0,20}(picker|menu|mode|model)/i.test(label.trim()); } function dispatchEscape() { const esc = new KeyboardEvent("keydown", { key: "Escape", code: "Escape", keyCode: 27, bubbles: true, cancelable: true }); if (document.activeElement) document.activeElement.dispatchEvent(esc); document.dispatchEvent(esc); } function closeOpenPopup(control = null) { dispatchEscape(); const trigger = control ?? reasoningMenuTrigger; if (!trigger || !trigger.isConnected) return; const settle = (remaining) => { if (!trigger.isConnected) return; if (trigger.getAttribute("aria-expanded") !== "true") return; if (!clickControlOnce(trigger)) return; if (remaining <= 1) return; const timer2 = window.setTimeout(() => { const index = popupCloseTimers.indexOf(timer2); if (index >= 0) popupCloseTimers.splice(index, 1); settle(remaining - 1); }, 160); popupCloseTimers.push(timer2); }; const timer = window.setTimeout(() => { const index = popupCloseTimers.indexOf(timer); if (index >= 0) popupCloseTimers.splice(index, 1); settle(3); }, 120); popupCloseTimers.push(timer); } function popupRootFor(control) { const id = control.getAttribute("aria-controls"); const byId = id ? document.getElementById(id) : null; if (byId) return byId; const owner = control.closest(REASONING_MENU_SELECTOR); return owner instanceof HTMLElement ? owner : null; } function hasVisibleMenu() { return Array.from(document.querySelectorAll(REASONING_MENU_SELECTOR)).some( (node) => !isInsideTurboUI3(node) && nodeVisible3(node) ); } function rowScopedText(node, selector) { if (!(node instanceof Element)) return ""; const part = Array.from( node.querySelectorAll(selector) ).find((candidate) => { if (isInsideTurboUI3(candidate) || !nodeVisible3(candidate)) return false; const owner = candidate.closest( "gem-menu-item, [role='menuitem'], [role='menuitemradio'], [role='option'], [role='radio']" ); return owner === node; }); return part ? String(part.innerText || "").replace(/\s+/g, " ").trim() : ""; } function rowLabel(node) { const structured = rowScopedText(node, ".label"); if (structured) return structured; const line = (node.innerText || "").split("\n").find((part) => part.trim()); return line ? line.replace(/\s+/g, " ").trim() : ""; } function rowHint(node) { const structured = rowScopedText(node, ".sublabel"); if (structured) return structured; const lines = (node.innerText || "").split("\n").map((part) => part.replace(/\s+/g, " ").trim()).filter(Boolean); return lines[1] || ""; } function choiceRowSelected(node) { if (!(node instanceof Element)) return null; const checked = node.getAttribute("aria-checked"); if (checked !== null && checked !== "") return checked === "true"; const selected = node.getAttribute("aria-selected"); if (selected !== null && selected !== "") return selected === "true"; const dataState = node.getAttribute("data-state"); if (dataState === "checked" || dataState === "selected" || dataState === "on") return true; if (dataState === "unchecked" || dataState === "unselected" || dataState === "off") return false; if (node.matches(".selected, .checked")) return true; if (node.querySelector( ".selected, .checked, [aria-label='Selected'], [aria-label='selected'], [aria-label='已选中'], [data-state='checked'], [data-mat-icon-name='check']" )) { return true; } return null; } function menuHasSelectionState(menu) { if (!menu) return false; return Boolean( menu.querySelector( "[aria-checked], [aria-selected], [role='menuitemradio'], [role='radio'], .selected, .checked, [aria-label='Selected'], [aria-label='已选中'], [data-mat-icon-name='check']" ) ); } function nodeVisible3(node) { if (!(node instanceof HTMLElement)) return false; const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; } function choiceRowIsSelected(row) { const explicit = choiceRowSelected(row); if (explicit !== null) return explicit; const menu = row.closest(REASONING_MENU_SELECTOR); return menu && menuHasSelectionState(menu) ? false : null; } function choicePathForRow(row) { const path = []; let menu = row.closest(REASONING_MENU_SELECTOR); let depth = 0; while (menu && depth < 5) { const menuId = menu.id; if (!menuId) break; const parent = Array.from( document.querySelectorAll("[aria-controls]") ).find( (node) => { if (isInsideTurboUI3(node) || !nodeVisible3(node)) return false; if (node.getAttribute("aria-controls") !== menuId) return false; const popup = node.getAttribute("aria-haspopup"); if (popup === null || popup === "false") return false; const owner2 = node.closest(REASONING_MENU_SELECTOR); return Boolean(owner2 && owner2 !== menu); } ); if (!parent) break; const owner = parent.closest(REASONING_MENU_SELECTOR); if (!owner || owner === menu) break; const label = rowLabel(parent); if (label) path.unshift(label); menu = owner; depth += 1; } return path; } function choiceRowForTarget(target) { const row = target.closest( "gem-menu-item, [role='menuitem'], [role='menuitemradio'], [role='option'], [aria-checked], [aria-selected]" ); if (!(row instanceof HTMLElement) || !row.closest(REASONING_MENU_SELECTOR)) { return null; } const popup = row.getAttribute("aria-haspopup"); if (popup !== null && popup !== "false") return null; return rowLabel(row) ? row : null; } function findPathParent(menu, label) { if (!menu || !label) return null; const parents = Array.from( menu.querySelectorAll("[aria-haspopup]:not([aria-haspopup='false'])") ).filter((node) => { if (!(node instanceof HTMLElement)) return false; if (isInsideTurboUI3(node) || !nodeVisible3(node)) return false; const owner = node.closest("[role='menu']"); if (owner && owner !== menu && menu.contains(owner)) return false; return rowLabel(node) === label; }); return parents[0] || null; } function findExactChoiceRow(menu, option) { if (!menu || !option) return null; const rows = Array.from( menu.querySelectorAll(CHOICE_OPTION_SELECTOR) ).filter( (node) => { if (isInsideTurboUI3(node) || !nodeVisible3(node)) return false; if (node.closest(REASONING_MENU_SELECTOR) !== menu) return false; const popup = node.getAttribute("aria-haspopup"); if (popup !== null && popup !== "false") return false; return rowLabel(node) === option; } ); return rows.reduce((deepest, node) => { if (!deepest) return node; return deepest.contains(node) ? node : deepest; }, null); } function submenuForParent(parent) { const id = parent.getAttribute("aria-controls"); const menu = id ? document.getElementById(id) : null; return menu && nodeVisible3(menu) ? menu : null; } function choiceLooksApplied(saved, control) { const label = controlLabel(control).toLowerCase(); if (!label) return false; if (saved.resultLabel && label === String(saved.resultLabel).toLowerCase()) { return true; } const option = String(saved.option || "").trim(); if (!option) return false; if (/\bcurrently\s+/i.test(option)) { const tail = option.replace(/^.*\bcurrently\s+/i, "").trim().toLowerCase(); return Boolean(tail) && (label === tail || label.endsWith(` ${tail}`)); } const expected = option.toLowerCase(); return label === expected || label.endsWith(` ${expected}`); } function choiceTokens(saved) { const option = String(saved.option || "").trim(); if (Array.isArray(saved.path) && saved.path.length) { return [...saved.path, option].map((part) => String(part).trim()).filter(Boolean); } const currentValue = option.replace(/^.*\bcurrently\s+/i, "").trim(); return currentValue.split(/\s+/).filter(Boolean); } function upgradeChoiceRecord(saved, control, info) { const stableKey = controlKey(control); if (!stableKey || !info || !info.option) return; const samePath = JSON.stringify(Array.isArray(saved.path) ? saved.path : []) === JSON.stringify(info.path); if (saved.key === stableKey && saved.option === info.option && samePath) return; const labelNow = controlLabel(control); writeReasoningRecord({ mode: "choice", key: stableKey, controlLabel: saved.controlLabel || "", path: info.path, option: info.option, hint: info.hint || "", resultLabel: labelNow || saved.resultLabel || "", ts: Date.now() }); renderReasoningStatus(); } function findRowIn(root, token) { if (!root || !token) return null; const rows = Array.from( root.querySelectorAll(CHOICE_OPTION_SELECTOR) ).filter((node) => { if (isInsideTurboUI3(node)) return false; const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; }); const exact = rows.filter((node) => rowLabel(node) === token); if (exact.length) { return exact.reduce((best, node) => best.contains(node) ? node : best); } const tail = rows.filter((node) => rowLabel(node).endsWith(token)); if (tail.length === 1) return tail[0]; const head = rows.filter((node) => rowLabel(node).startsWith(`${token} `)); return head.length === 1 ? head[0] : null; } function interactiveTarget(node) { if (node.matches("button, a, [role='menuitemradio'], [role='radio']")) return node; const inner = node.querySelector("button, a"); return inner instanceof HTMLElement ? inner : node; } function findRowInOpenMenus(token) { const menus = Array.from( document.querySelectorAll(REASONING_MENU_SELECTOR) ).filter((node) => { if (isInsideTurboUI3(node) || toolScope.isInside(node)) return false; const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; }); for (let i = menus.length - 1; i >= 0; i -= 1) { const row = findRowIn(menus[i], token); if (row) return row; } return null; } function findSubmenuParent(root, token) { if (!root) return null; const parents = Array.from( root.querySelectorAll("[aria-haspopup]:not([aria-haspopup='false'])") ).filter((node) => { if (!(node instanceof HTMLElement)) return false; if (isInsideTurboUI3(node)) return false; const owner = node.closest("[role='menu']"); if (owner && owner !== root && root.contains(owner)) return false; const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; }); if (!parents.length) return null; const loaded = parents.find((parent) => { const sub = document.getElementById(parent.getAttribute("aria-controls") || ""); return sub ? Boolean(findRowIn(sub, token)) : false; }); return loaded || (parents.length === 1 ? parents[0] : null); } function choiceRowInfo(row) { if (!row || !row.isConnected) return null; const option = rowLabel(row); if (!option) return null; return { option, hint: rowHint(row), path: choicePathForRow(row) }; } function restorePathChoice(saved, control, onSettled, token) { const path = (Array.isArray(saved.path) ? saved.path : []).map((part) => String(part).trim()).filter(Boolean); const option = String(saved.option || "").trim(); if (!option) { onSettled(false, false); return; } let settled = false; let lastRow = null; const finish = (ok, conclusive) => { if (settled) return; settled = true; if (restoreIsStale(token)) return; const info = ok ? choiceRowInfo(lastRow) : null; window.setTimeout(() => closeOpenPopup(control), 100); if (info) { window.setTimeout(() => { if (control.isConnected) upgradeChoiceRecord(saved, control, info); }, 300); } applyingReasoning = false; onSettled(ok, conclusive === true); }; const waitForSubmenu = (parent, done, attempt) => { if (settled || restoreIsStale(token)) return; const sub = submenuForParent(parent); if (sub) { done(sub); return; } if (attempt >= 10) { done(null); return; } window.setTimeout(() => waitForSubmenu(parent, done, attempt + 1), 180); }; const walk = (menu, index, done, fail) => { if (settled || restoreIsStale(token)) return; if (!menu) { fail(false); return; } if (index >= path.length) { const row = findExactChoiceRow(menu, option); if (row) done(row); else fail(true); return; } const parent = findPathParent(menu, path[index]); if (!parent) { fail(true); return; } parent.dispatchEvent( new PointerEvent("pointerover", { bubbles: true, cancelable: true, view: window }) ); parent.dispatchEvent(new MouseEvent("mouseenter", { view: window })); triggerSendButton(interactiveTarget(parent)); waitForSubmenu(parent, (sub) => { if (!sub) { fail(false); return; } walk(sub, index + 1, done, fail); }, 0); }; const openRoot = (done, attempt) => { if (settled || restoreIsStale(token)) return; const root = popupRootFor(control); if (root && nodeVisible3(root)) { done(root); return; } const fallback = Array.from( document.querySelectorAll(REASONING_MENU_SELECTOR) ).find((node) => !isInsideTurboUI3(node) && nodeVisible3(node)); if (fallback) { done(fallback); return; } if (attempt >= 10) { finish(false, false); return; } if (attempt === 0) triggerSendButton(interactiveTarget(control)); window.setTimeout(() => openRoot(done, attempt + 1), 180); }; const verifySelection = () => { window.setTimeout(() => { if (settled) return; if (restoreIsStale(token)) return; closeOpenPopup(control); window.setTimeout(() => { if (settled) return; openRoot((menu) => { walk( menu, 0, (row) => { lastRow = row; const selected = choiceRowIsSelected(row); if (selected === true) finish(true); else if (selected === false) finish(false); else finish(choiceLooksApplied(saved, control)); }, (conclusive) => finish(false, conclusive === true) ); }, 0); }, 220); }, 260); }; applyingReasoning = true; openRoot((menu) => { walk( menu, 0, (row) => { lastRow = row; const selected = choiceRowIsSelected(row); if (selected === true) { finish(true); return; } if (selected === null && choiceLooksApplied(saved, control)) { finish(true); return; } triggerSendButton(interactiveTarget(row)); verifySelection(); }, (conclusive) => finish(false, conclusive === true) ); }, 0); } function restoreChoice(saved, control, onSettled, restoreId) { const tokens = choiceTokens(saved); if (!tokens.length) { onSettled(false, false); return; } let index = 0; let settled = false; let lastRow = null; const finish = (ok, conclusive) => { if (settled) return; settled = true; if (restoreIsStale(restoreId)) return; const info = ok ? choiceRowInfo(lastRow) : null; window.setTimeout(() => closeOpenPopup(control), 100); if (info) { window.setTimeout(() => { if (control.isConnected) upgradeChoiceRecord(saved, control, info); }, 300); } applyingReasoning = false; onSettled(ok, conclusive === true); }; const step = (attempt) => { if (settled || restoreIsStale(restoreId)) return; const token = tokens[index]; const root = popupRootFor(control); const hit = findRowIn(root, token) || findRowInOpenMenus(token); if (hit) { lastRow = hit; triggerSendButton(interactiveTarget(hit)); next(); return; } const parent = findSubmenuParent(root, token); if (parent) { parent.dispatchEvent( new PointerEvent("pointerover", { bubbles: true, cancelable: true, view: window }) ); parent.dispatchEvent(new MouseEvent("mouseenter", { view: window })); triggerSendButton(interactiveTarget(parent)); const lookInSub = (deep) => { if (settled || restoreIsStale(restoreId)) return; const sub = document.getElementById(parent.getAttribute("aria-controls") || ""); const row = findRowIn(sub, token) || findRowIn(popupRootFor(control), token) || findRowInOpenMenus(token); if (row) { lastRow = row; triggerSendButton(interactiveTarget(row)); next(); return; } if (deep >= 6) { closeOpenPopup(control); finish(false, true); return; } window.setTimeout(() => lookInSub(deep + 1), 200); }; window.setTimeout(() => lookInSub(0), 250); return; } if (attempt >= 8) { const menuWasOpen = hasVisibleMenu(); closeOpenPopup(control); finish(false, menuWasOpen); return; } window.setTimeout(() => step(attempt + 1), 250); }; const next = () => { index += 1; if (index >= tokens.length) { finish(true); return; } closeOpenPopup(control); window.setTimeout(() => { triggerSendButton(interactiveTarget(control)); window.setTimeout(() => step(0), 350); }, 200); }; applyingReasoning = true; triggerSendButton(interactiveTarget(control)); window.setTimeout(() => step(0), 350); } function observeControlChoice(control, labelBefore, startedAt) { [400, 900, 1600, 2600].forEach((delay) => { window.setTimeout(() => { if (applyingReasoning || !control.isConnected) return; const labelNow = controlLabel(control); if (!labelNow || labelNow === labelBefore) return; const memory = loadReasoningMemory(); const saved = readReasoningRecord(memory); if (saved && saved.mode === "choice") { if (startedAt && saved.ts && saved.ts >= startedAt) return; if (saved.option === labelNow) return; } const root = popupRootFor(control); if (!hasVisibleMenu() && !(root && nodeVisible3(root))) return; writeReasoningRecord({ mode: "choice", key: controlKey(control), controlLabel: labelBefore, option: labelNow, ts: Date.now() }); renderReasoningStatus(); }, delay); }); } function captureChoiceResult(trigger, record) { [300, 700, 1400, 2400].forEach((delay) => { window.setTimeout(() => { if (applyingReasoning || !trigger.isConnected) return; const labelNow = controlLabel(trigger); if (!labelNow || labelNow === record.controlLabel) return; const memory = loadReasoningMemory(); const saved = readReasoningRecord(memory); if (!saved || saved.mode !== "choice" || saved.ts !== record.ts) return; if (saved.resultLabel === labelNow) return; saved.resultLabel = labelNow; saveReasoningMemory(memory); renderReasoningStatus(); }, delay); }); } function pairOptionClick(target) { if (isToolControlElement(target) || toolScope.isInside(target)) return false; const row = choiceRowForTarget(target); if (!row) return false; const trigger = reasoningMenuTrigger; if (!trigger || !trigger.isConnected) return false; if (Date.now() - reasoningMenuTriggerAt > 2e4) return false; if (row === trigger || row.contains(trigger)) return false; const optionText = rowLabel(row); if (!optionText) return false; const menu = row.closest(REASONING_MENU_SELECTOR); const path = choicePathForRow(row); const explicitChoice = row.matches(CHOICE_RADIO_SELECTOR); if (!explicitChoice && !(path.length && menuHasSelectionState(menu))) { return false; } const triggerLabel = reasoningMenuTriggerLabel; const hint = rowHint(row); const ts = Date.now(); const record = { mode: "choice", key: controlKey(trigger), controlLabel: triggerLabel, path, option: optionText, hint, ts }; window.setTimeout(() => { if (applyingReasoning) return; writeReasoningRecord(record); renderReasoningStatus(); captureChoiceResult(trigger, record); }, 0); return true; } function handleReasoningClick(event) { if (isEngineDormant()) return; if (!state.rememberReasoning || applyingReasoning) return; const target = event.target; if (!(target instanceof Element) || isInsideTurboUI3(target)) return; if (isYuanbaoHost()) { if (isToolControlElement(target) || toolScope.isInside(target)) return; if (handleYuanbaoSelectionClick(target)) return; } if (isToolControlElement(target) || toolScope.isInside(target)) return; if (pairOptionClick(target)) return; if (target.closest(REASONING_MENU_SELECTOR)) return; const control = target.closest(REASONING_CONTROL_SELECTOR); if (!(control instanceof HTMLElement)) return; const startedAt = Date.now(); const labelBefore = controlLabel(control); if (!labelBefore) return; const keywordMatch = REASONING_CONTROL_PATTERN.test(labelBefore); if (!keywordMatch && !isDropdownTrigger(control)) return; reasoningMenuTrigger = control; reasoningMenuTriggerAt = Date.now(); reasoningMenuTriggerLabel = labelBefore; if (keywordMatch) { window.setTimeout(() => { if (applyingReasoning || !control.isConnected) return; const on = controlOnState(control); if (on === null) return; writeReasoningRecord({ mode: "toggle", label: labelBefore, on, ts: Date.now() }); renderReasoningStatus(); }, 0); } if (keywordMatch && explicitToggleState(control) !== null) return; observeControlChoice(control, labelBefore, startedAt); } function handleDehydratedClick(event) { if (isEngineDormant()) return; const target = event.target; if (!(target instanceof Element)) return; const turnElement = target.closest(".ai-turbo-dehydrated"); if (!(turnElement instanceof HTMLElement)) return; markRestoredTurn(turnElement); withSelfMutation(() => { turnElement.classList.remove("ai-turbo-dehydrated"); turnElement.style.removeProperty("--turbo-cached-h"); }); requestFullTurnSync(); requestUpdate(); } function renderReasoningStatus() { if (!reasoningStatusNode) return; reasoningStatusNode.textContent = ""; if (!state.rememberReasoning) { reasoningStatusNode.textContent = "推理记忆:已关闭"; return; } if (isYuanbaoHost() || readYuanbaoSelectionRecord()) { const saved2 = readYuanbaoSelectionRecord(); if (!saved2) { reasoningStatusNode.textContent = "推理记忆:未记录(在模型菜单里选择模型或模式即可)"; return; } const shown2 = [saved2.model, saved2.mode].filter(Boolean).join(" + "); reasoningStatusNode.textContent = `推理记忆:${shown2 || "未记录"} `; if (yuanbaoActionStatus) { reasoningStatusNode.appendChild( el("span", {}, [`· ${yuanbaoActionStatus} `]) ); } reasoningStatusNode.appendChild( el( "button", { type: "button", onclick: () => { clearReasoningRestoreTimer(); clearYuanbaoSelectionRecord(); clearReasoningRecord(); yuanbaoActionStatus = ""; reasoningRestoreDone = true; renderReasoningStatus(); } }, ["清除"] ) ); return; } const saved = readReasoningRecord(); if (!saved || !saved.mode) { reasoningStatusNode.textContent = "推理记忆:未记录(在页面里点一次强度/模型选项即可)"; return; } const pathText = saved.mode === "choice" && Array.isArray(saved.path) && saved.path.length ? `${saved.path.join(" / ")} / ` : ""; const shown = saved.mode === "choice" ? `${saved.controlLabel || "控件"} → ${pathText}${saved.option}` : `${saved.label}(${saved.on ? "开" : "关"})`; reasoningStatusNode.textContent = `推理记忆:${shown} `; reasoningStatusNode.appendChild( el( "button", { type: "button", onclick: () => { clearReasoningRecord(); renderReasoningStatus(); } }, ["清除"] ) ); } function findRememberedControl(saved) { const visible = Array.from( document.querySelectorAll(REASONING_CONTROL_SELECTOR) ).filter( (node) => !isInsideTurboUI3(node) && !toolScope.isInside(node) && !isToolControlElement(node) && nodeVisible3(node) ); if (saved.key) { const byKey = visible.find((node) => controlKey(node) === saved.key); if (byKey) return byKey; } if (/,\s*currently\b/i.test(saved.key || "")) { const prefix = String(saved.key).split(/,\s*currently\b/i)[0].trim(); const byAccessibleName = visible.find((node) => { const ariaLabel = node.getAttribute("aria-label") || ""; return ariaLabel === saved.key || ariaLabel.startsWith(`${prefix},`); }); if (byAccessibleName) return byAccessibleName; } if (saved.controlLabel) { const byLabel = visible.find((node) => controlLabel(node) === saved.controlLabel); if (byLabel) return byLabel; const byLabelPrefix = visible.find( (node) => controlLabel(node).startsWith(`${saved.controlLabel} `) ); if (byLabelPrefix) return byLabelPrefix; } return visible.find((node) => REASONING_CONTROL_PATTERN.test(controlLabel(node))) || null; } function isYuanbaoHost() { if (hostnameMatches(location.hostname.toLowerCase(), [ "yuanbao.tencent.com" ])) { return true; } return Array.from( document.querySelectorAll(YUANBAO_MODEL_TRIGGER_SELECTOR) ).some((node) => !isInsideTurboUI3(node)); } function cleanSelectionText(raw) { return raw.replace(/\s+/g, " ").trim().slice(0, 120); } function selectionMatches(actual, expected) { return actual.toLowerCase().replace(/\s+/g, " ").trim() === expected.toLowerCase().replace(/\s+/g, " ").trim(); } function yuanbaoTrigger() { return Array.from( document.querySelectorAll(YUANBAO_MODEL_TRIGGER_SELECTOR) ).find((node) => !isInsideTurboUI3(node) && nodeVisible3(node)) ?? null; } function yuanbaoPanelOpen(trigger) { return trigger.getAttribute("aria-expanded") === "true"; } function yuanbaoSelectionKey(record) { return `${conversationKey}|${record.model || ""}|${record.mode || ""}`; } function yuanbaoSelectionApplied(record, trigger) { if (!trigger || !yuanbaoAppliedKey) return false; if (yuanbaoAppliedKey !== yuanbaoSelectionKey(record)) return false; if (Date.now() - yuanbaoAppliedAt > YUANBAO_APPLIED_WINDOW_MS) return false; if (yuanbaoPanelOpen(trigger) || yuanbaoMainMenu() || yuanbaoModelMenu()) { return false; } return !record.mode || selectionMatches(yuanbaoModeValue(trigger), record.mode); } function yuanbaoMainMenu() { const rows = Array.from( document.querySelectorAll(YUANBAO_MODEL_ROW_SELECTOR) ).filter((row) => !isInsideTurboUI3(row) && nodeVisible3(row)); for (const row of rows) { const menu = row.closest(REASONING_MENU_SELECTOR); if (menu instanceof HTMLElement && menu.getAttribute("aria-label") !== "模型列表" && nodeVisible3(menu)) { return menu; } } return null; } function yuanbaoModelMenu() { return Array.from( document.querySelectorAll(YUANBAO_MODEL_MENU_SELECTOR) ).find((node) => !isInsideTurboUI3(node) && nodeVisible3(node)) ?? null; } function yuanbaoLeafTexts(row) { const leaves = Array.from(row.querySelectorAll("span")).filter( (node) => !isInsideTurboUI3(node) && nodeVisible3(node) && node.querySelector("span") === null ).map((node) => cleanSelectionText(node.textContent || "")).filter(Boolean); if (leaves.length) return leaves; return (row.innerText || row.textContent || "").split("\n").map(cleanSelectionText).filter(Boolean); } function yuanbaoRowTitle(row) { return yuanbaoLeafTexts(row)[0] || ""; } function yuanbaoModeValue(trigger) { if (!trigger) return ""; const label = trigger.querySelector(YUANBAO_MODE_LABEL_SELECTOR); if (label instanceof HTMLElement) { const text = cleanSelectionText(label.textContent || ""); if (text) return text; } const main = yuanbaoMainMenu(); if (main) { const selected = yuanbaoModeRows(main).find( (row) => choiceRowIsSelected(row) === true ); if (selected) return yuanbaoRowTitle(selected); } return ""; } function yuanbaoModeRows(menu) { return Array.from( menu.querySelectorAll(CHOICE_RADIO_SELECTOR) ).filter((row) => { if (isInsideTurboUI3(row) || !nodeVisible3(row)) return false; if (row.closest(REASONING_MENU_SELECTOR) !== menu) return false; return !row.matches(YUANBAO_MODEL_ROW_SELECTOR); }); } function yuanbaoModelRow(menu) { return Array.from( menu.querySelectorAll(YUANBAO_MODEL_ROW_SELECTOR) ).find((row) => row.closest(REASONING_MENU_SELECTOR) === menu) ?? null; } function yuanbaoModelValue(menu) { if (menu) { const row = yuanbaoModelRow(menu); if (row) { const parts = yuanbaoLeafTexts(row); if (parts.length >= 2) return parts[1]; } } const modelMenu = yuanbaoModelMenu(); if (modelMenu) { const selected = Array.from( modelMenu.querySelectorAll(CHOICE_RADIO_SELECTOR) ).find( (row) => row.closest(REASONING_MENU_SELECTOR) === modelMenu && choiceRowIsSelected(row) === true ); if (selected) return yuanbaoRowTitle(selected); } return ""; } function yuanbaoSelectionRow(menu, expected) { return Array.from( menu.querySelectorAll(CHOICE_RADIO_SELECTOR) ).find( (row) => row.closest(REASONING_MENU_SELECTOR) === menu && selectionMatches(yuanbaoRowTitle(row), expected) ) ?? null; } function yuanbaoModelConflicts(model, mode) { if (!model || !mode) return false; return /^hy4\b/i.test(model) && !selectionMatches(mode, "专家模式"); } function closeYuanbaoPanel(trigger, done, token, attempt = 0) { if (restoreIsStale(token)) return; if (!trigger.isConnected) { done(); return; } const expanded = yuanbaoPanelOpen(trigger); const mounted = yuanbaoMainMenu() !== null || yuanbaoModelMenu() !== null; if (!expanded && !mounted) { done(); return; } if (attempt >= 8) { done(); return; } if (attempt === 0) { clickControlOnce(trigger); } else if (attempt === 4 && expanded) { clickControlOnce(trigger); } window.setTimeout(() => { closeYuanbaoPanel(trigger, done, token, attempt + 1); }, 160); } function waitForYuanbao(read, done, token, attempt = 0) { if (restoreIsStale(token)) return; const node = read(); if (node || attempt >= 12) { done(node); return; } window.setTimeout(() => { waitForYuanbao(read, done, token, attempt + 1); }, 160); } function openYuanbaoPanel(trigger, done, token) { if (restoreIsStale(token)) return; const open = yuanbaoMainMenu(); if (open) { done(open); return; } if (trigger.getAttribute("aria-expanded") !== "true") { if (!clickControlOnce(trigger)) { done(null); return; } } waitForYuanbao( yuanbaoMainMenu, (menu) => { if (restoreIsStale(token)) return; done(menu); }, token ); } function waitYuanbaoSelection(read, expected, done, token, attempt = 0) { if (restoreIsStale(token)) return; const actual = read(); if (actual && selectionMatches(actual, expected)) { done(true); return; } if (attempt >= 10) { done(false); return; } window.setTimeout( () => waitYuanbaoSelection(read, expected, done, token, attempt + 1), 160 ); } function openYuanbaoModelSubmenu(parent, done, token, attempt = 0) { if (restoreIsStale(token)) return; const opened = yuanbaoModelMenu(); if (opened) { done(opened); return; } if (attempt >= 8) { done(null); return; } hoverControlOnce(parent); if (attempt >= 3) clickControlOnce(interactiveTarget(parent)); window.setTimeout(() => { openYuanbaoModelSubmenu(parent, done, token, attempt + 1); }, 180); } function restoreYuanbaoModel(saved, trigger, token, done) { if (!saved.model) { done(true, false); return; } openYuanbaoPanel( trigger, (menu) => { if (!menu) { done(false, false); return; } const current = yuanbaoModelValue(menu); if (current && selectionMatches(current, saved.model || "")) { done(true, false); return; } const choose = (modelMenu2) => { const row = yuanbaoSelectionRow(modelMenu2, saved.model || ""); if (!row) { done(false, true); return; } if (choiceRowIsSelected(row) === true) { done(true, false); return; } if (!clickControlOnce(interactiveTarget(row))) { done(false, false); return; } window.setTimeout(() => { if (restoreIsStale(token)) return; openYuanbaoPanel( trigger, (currentMenu) => { if (!currentMenu) { done(false, false); return; } waitYuanbaoSelection( () => yuanbaoModelValue(currentMenu), saved.model || "", (ok) => done(ok, !ok), token ); }, token ); }, 220); }; const modelMenu = yuanbaoModelMenu(); if (modelMenu) { choose(modelMenu); return; } const parent = yuanbaoModelRow(menu); if (!parent) { done(false, true); return; } openYuanbaoModelSubmenu( parent, (sub) => { if (restoreIsStale(token)) return; if (!sub) { done(false, false); return; } choose(sub); }, token ); }, token ); } function restoreYuanbaoMode(saved, trigger, token, done) { if (!saved.mode) { done(true, false); return; } openYuanbaoPanel( trigger, (menu) => { if (!menu) { done(false, false); return; } const current = yuanbaoModeValue(trigger); if (current && selectionMatches(current, saved.mode || "")) { done(true, false); return; } const row = yuanbaoSelectionRow(menu, saved.mode || ""); if (!row) { done(false, true); return; } if (choiceRowIsSelected(row) === true) { done(true, false); return; } if (!clickControlOnce(interactiveTarget(row))) { done(false, false); return; } waitYuanbaoSelection( () => yuanbaoModeValue(trigger), saved.mode || "", (ok) => done(ok, !ok), token ); }, token ); } function migrateYuanbaoReasoningRecord(trigger) { const legacy = readReasoningRecord(); const option = cleanSelectionText(legacy?.option || legacy?.label || ""); if (!option) return null; const mode = yuanbaoModeValue(trigger); let record = null; if (/^(?:hy\s?\d|hy[0-9]|deepseek|混元)/i.test(option)) { record = { model: option }; } else if (/快速|深度|专家|expert|think/i.test(option)) { record = { mode: option }; } if (!record) return null; if (mode && !record.mode) record.mode = mode; record.ts = Date.now(); writeYuanbaoSelectionRecord(record); return record; } function restoreYuanbaoSelection() { const trigger = yuanbaoTrigger(); const stored = readYuanbaoSelectionRecord(); const saved = stored ?? migrateYuanbaoReasoningRecord(trigger); if (!saved) { reasoningRestoreDone = true; releaseReasoningRestore(); return; } if (yuanbaoSelectionApplied(saved, trigger)) { reasoningRestoreDone = true; releaseReasoningRestore(); return; } if (applyingReasoning) return; setReasoningPending(true); if (!trigger) { yuanbaoMissingTriggerAttempts += 1; if (yuanbaoMissingTriggerAttempts >= 20) { reasoningRestoreDone = true; yuanbaoActionStatus = "未找到模型菜单,已停止恢复"; releaseReasoningRestore(); renderReasoningStatus(); } return; } yuanbaoMissingTriggerAttempts = 0; if (!restoreCoordinator.tryAcquire("reasoning")) return; if (yuanbaoModelConflicts(saved.model || "", saved.mode || "")) { yuanbaoActionStatus = "模型与模式组合不兼容,已停止恢复"; reasoningRestoreDone = true; releaseReasoningRestore(); renderReasoningStatus(); return; } const token = beginRestore(); applyingReasoning = true; setReasoningPending(true); let settled = false; let modelConfirmed = !saved.model; const finish = (ok) => { if (settled) return; settled = true; applyingReasoning = false; reasoningRestoreDone = true; releaseReasoningRestore(); yuanbaoActionStatus = ok ? "已恢复模型与模式" : "未能恢复模型与模式"; if (ok) { yuanbaoAppliedKey = yuanbaoSelectionKey(saved); yuanbaoAppliedAt = Date.now(); } renderReasoningStatus(); }; const settleAfter = (ok, conclusive, next) => { if (settled || restoreIsStale(token)) return; if (!ok) { closeYuanbaoPanel(trigger, () => finish(false), token); return; } if (conclusive) { closeYuanbaoPanel(trigger, () => finish(false), token); return; } next(); }; const verifyAndClose = () => { if (settled || restoreIsStale(token)) return; openYuanbaoPanel( trigger, (menu) => { const modeOk = !saved.mode || selectionMatches(yuanbaoModeValue(trigger), saved.mode); const modelOk = !saved.model || modelConfirmed && (!menu || selectionMatches(yuanbaoModelValue(menu), saved.model)); closeYuanbaoPanel(trigger, () => finish(modeOk && modelOk), token); }, token ); }; restoreYuanbaoModel( saved, trigger, token, (modelOk, modelConclusive) => { if (modelOk && !modelConclusive) modelConfirmed = true; settleAfter(modelOk, modelConclusive, () => { restoreYuanbaoMode( saved, trigger, token, (modeOk, modeConclusive) => { settleAfter(modeOk, modeConclusive, verifyAndClose); } ); }); } ); } function mergeYuanbaoSelection(next) { const previous = readYuanbaoSelectionRecord(); const merged = { ...previous || {}, ...next.model ? { model: next.model } : {}, ...next.mode ? { mode: next.mode } : {}, ts: Date.now() }; if (!merged.model && !merged.mode) return null; writeYuanbaoSelectionRecord(merged); yuanbaoAppliedKey = yuanbaoSelectionKey(merged); yuanbaoAppliedAt = Date.now(); return merged; } function cancelYuanbaoRecordTimers() { for (const timer of yuanbaoRecordTimers.splice(0)) { window.clearTimeout(timer); } } function scheduleYuanbaoRecordSync(intent) { cancelYuanbaoRecordTimers(); for (const delay of [120, 420, 900]) { yuanbaoRecordTimers.push( window.setTimeout(() => { syncYuanbaoSelection(intent); }, delay) ); } } function syncYuanbaoSelection(intent) { if (applyingReasoning) return; const trigger = yuanbaoTrigger(); const main = yuanbaoMainMenu(); const modelMenu = yuanbaoModelMenu(); const model = modelMenu ? (() => { const selected = Array.from( modelMenu.querySelectorAll(CHOICE_RADIO_SELECTOR) ).find( (row) => row.closest(REASONING_MENU_SELECTOR) === modelMenu && choiceRowIsSelected(row) === true ); return selected ? yuanbaoRowTitle(selected) : ""; })() : main ? yuanbaoModelValue(main) : ""; const mode = yuanbaoModeValue(trigger); const previous = readYuanbaoSelectionRecord(); const next = { model: intent === "model" ? previous?.model || "" : model || previous?.model || "", mode: intent === "mode" ? previous?.mode || "" : mode || previous?.mode || "", ts: Date.now() }; if (!next.model && !next.mode) return; if (previous && previous.model === next.model && previous.mode === next.mode) { return; } writeYuanbaoSelectionRecord(next); renderReasoningStatus(); } function handleYuanbaoSelectionClick(target) { if (!isYuanbaoHost()) return false; const trigger = yuanbaoTrigger(); if (!trigger) return false; const main = yuanbaoMainMenu(); const modelMenu = yuanbaoModelMenu(); const inPicker = target.closest(YUANBAO_MODEL_TRIGGER_SELECTOR) !== null || main !== null && main.contains(target) || modelMenu !== null && modelMenu.contains(target); if (!inPicker) return false; if (target.closest(YUANBAO_MODEL_TRIGGER_SELECTOR)) return true; const modelRow = modelMenu instanceof HTMLElement ? Array.from( modelMenu.querySelectorAll(CHOICE_RADIO_SELECTOR) ).find( (row) => row.closest(REASONING_MENU_SELECTOR) === modelMenu && (row === target || row.contains(target)) ) ?? null : null; if (modelRow) { const model = yuanbaoRowTitle(modelRow); if (!model) return true; mergeYuanbaoSelection({ model, mode: yuanbaoModeValue(trigger) }); renderReasoningStatus(); scheduleYuanbaoRecordSync("model"); return true; } if (!main) return false; const modeRow = Array.from(main.querySelectorAll(CHOICE_RADIO_SELECTOR)).find( (row) => row.closest(REASONING_MENU_SELECTOR) === main && !row.matches(YUANBAO_MODEL_ROW_SELECTOR) && (row === target || row.contains(target)) ) ?? null; if (!modeRow) return main.contains(target); const mode = yuanbaoRowTitle(modeRow); if (!mode) return true; mergeYuanbaoSelection({ model: yuanbaoModelValue(main), mode }); renderReasoningStatus(); scheduleYuanbaoRecordSync("mode"); return true; } function applyReasoningMemory() { syncConversationScope(); if (isEngineDormant()) { reasoningRestoreDone = true; releaseReasoningRestore(); return; } if (isYuanbaoHost() || readYuanbaoSelectionRecord()) { restoreYuanbaoSelection(); return; } const saved = readReasoningRecord(); if (!saved || !saved.mode) { reasoningRestoreDone = true; return; } const control = findRememberedControl(saved); if (!control) return; if (applyingReasoning) return; const stableKey = controlKey(control); if (saved.mode === "choice" && stableKey && saved.key !== stableKey) { saved.key = stableKey; writeReasoningRecord(saved); } if (saved.mode === "choice" && /,\s*currently\b/i.test(saved.option || "")) { const normalized = String(saved.option).replace(/^.*\bcurrently\s+/i, "").trim(); if (normalized) { saved.option = normalized; writeReasoningRecord(saved); } } if (saved.mode === "choice" && saved.option) { if (choiceLooksApplied(saved, control)) { reasoningRestoreDone = true; return; } const attemptKey2 = choiceAttemptKey(control, saved); const attempts = choiceRestoreAttempts.get(attemptKey2) ?? 0; if (attempts >= 2) { reasoningRestoreDone = true; return; } choiceRestoreAttempts.set(attemptKey2, attempts + 1); const token2 = beginRestore(); const restore = Array.isArray(saved.path) ? restorePathChoice : restoreChoice; restore(saved, control, (ok, conclusive) => { reasoningRestoreDone = ok || conclusive === true; if (attempts + 1 >= 2) reasoningRestoreDone = true; if (reasoningRestoreDone) { restoreCoordinator.release("reasoning"); } }, token2); return; } reasoningRestoreDone = true; if (saved.mode !== "toggle") return; const now = controlOnState(control); if (now === null || now === (saved.on === true)) return; const desired = saved.on === true; const attemptKey = toggleAttemptKey(control, desired); if (correctedToggleAttempts.has(attemptKey)) return; correctedToggleAttempts.add(attemptKey); const token = beginRestore(); applyingReasoning = true; if (!clickControlOnce(control)) { applyingReasoning = false; return; } settleToggleCorrection(control, desired, token); } function clearReasoningRestoreTimer() { window.clearInterval(reasoningRestoreTimer); reasoningRestoreTimer = 0; window.clearTimeout(reasoningSettleTimer); reasoningSettleTimer = 0; for (const timer of popupCloseTimers.splice(0)) window.clearTimeout(timer); cancelYuanbaoRecordTimers(); restoreToken += 1; applyingReasoning = false; yuanbaoMissingTriggerAttempts = 0; if (reasoningRestorePending) releaseReasoningRestore(); } function scheduleReasoningRestore() { clearReasoningRestoreTimer(); syncConversationScope(); reasoningRestoreDone = false; reasoningRestoreAttempts = 0; if (isEngineDormant()) return; if (!state.rememberReasoning) return; const yuanbaoRecord = readYuanbaoSelectionRecord(); if (!yuanbaoRecord && !readReasoningRecord()) return; if (yuanbaoRecord && isYuanbaoHost() && yuanbaoSelectionApplied(yuanbaoRecord, yuanbaoTrigger())) { reasoningRestoreDone = true; releaseReasoningRestore(); return; } if (isYuanbaoHost() || yuanbaoRecord) setReasoningPending(true); reasoningRestoreTimer = window.setInterval(() => { reasoningRestoreAttempts += 1; if (!reasoningRestoreDone) applyReasoningMemory(); if (reasoningRestoreDone || reasoningRestoreAttempts >= 120) { clearReasoningRestoreTimer(); } }, 500); } function attachStatusNode(node) { reasoningStatusNode = node; } return { handleReasoningClick, handleDehydratedClick, renderReasoningStatus, applyReasoningMemory, clearReasoningRestoreTimer, scheduleReasoningRestore, isRestorePending: () => restoreCoordinator.isPending("reasoning"), attachStatusNode }; } // scripts/ai-chat-turbo-engine/src/storage/tool-memory.ts var toolStore = createReportedStorage("localStorage", (failure) => { const scope = failure.operation === "write" || failure.operation === "remove" ? "save tool memory" : "load tool memory"; reportRecoverableError(scope, failure.error); }); var MAX_TOOLS = 40; var MAX_LABEL2 = 120; var MAX_APPLICATION_ID = 120; function cleanLabel2(raw) { if (typeof raw !== "string") return ""; return raw.replace(/\s+/g, " ").trim().slice(0, MAX_LABEL2); } function toToolRecord(value) { if (!isObjectRecord(value)) return null; const key = cleanLabel2(value["key"]); const applicationId = cleanLabel2(value["applicationId"]).slice(0, MAX_APPLICATION_ID); const label = cleanLabel2(value["label"]); const selectedRaw = value["selected"]; const legacyLabels = []; if (Array.isArray(selectedRaw)) { for (const entry of selectedRaw) { const legacy = cleanLabel2(entry); if (!legacy || legacyLabels.includes(legacy)) continue; legacyLabels.push(legacy); if (legacyLabels.length >= MAX_TOOLS) break; } } if (!key || !applicationId && !label && !legacyLabels.length) return null; const controlLabel = cleanLabel2(value["controlLabel"]); const ts = value["ts"]; return { key, controlLabel, applicationId, label: label || legacyLabels[0] || "", legacyLabels, ts: typeof ts === "number" && Number.isFinite(ts) ? ts : 0 }; } function loadToolMemory() { try { const raw = toolStore.read(STORAGE_KEY_TOOL_MEMORY); const parsed = raw === null || raw === "" ? {} : JSON.parse(raw); if (!isObjectRecord(parsed)) return {}; const memory = {}; for (const [scope, entry] of Object.entries(parsed)) { const record = toToolRecord(entry); if (record) memory[scope] = record; } return memory; } catch (error) { reportRecoverableError("load tool memory", error); return {}; } } function saveToolMemory(memory) { toolStore.writeJson(STORAGE_KEY_TOOL_MEMORY, memory); } function readToolRecord(memory) { const all = memory ?? loadToolMemory(); const scoped = all[reasoningScope()]; if (scoped) return scoped; return all[location.hostname] ?? null; } function writeToolRecord(record) { const memory = loadToolMemory(); const scope = reasoningScope(); memory[scope] = record; if (scope !== location.hostname) delete memory[location.hostname]; saveToolMemory(memory); return record; } function clearToolRecord() { const memory = loadToolMemory(); delete memory[reasoningScope()]; delete memory[location.hostname]; saveToolMemory(memory); } // scripts/ai-chat-turbo-engine/src/core/tool-memory.ts var POLL_INTERVAL = 350; var MAX_POLLS = 80; var MENU_WAIT_INTERVAL = 120; var MENU_WAIT_ATTEMPTS = 12; var MAX_RESTORE_ATTEMPTS = 6; var RECORD_DELAYS = [120, 320, 700, 1200]; var VERIFY_DELAYS = [150, 400, 800, 1400]; function cleanText(raw) { return raw.replace(/\s+/g, " ").trim().slice(0, 120); } function nodeVisible(node) { const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; } function isInsideTurboUI(node) { return Boolean(node.closest("[id^='ai-turbo-'], .ai-turbo-code-bar")); } function applicationIdOf(node) { return cleanText(node.getAttribute("data-application-id") || ""); } function toolLabel(node) { const aria = cleanText(node.getAttribute("aria-label") || ""); if (aria) return aria; const visible = node.querySelector("[data-input-label='tools']"); if (visible instanceof HTMLElement) { const label = cleanText(visible.textContent || ""); if (label) return label; } return cleanText(node.textContent || ""); } function chipRecord(node) { if (!nodeVisible(node)) return null; const applicationId = applicationIdOf(node); if (!applicationId) return null; const labelNode = node.querySelector("span > span"); const label = labelNode instanceof HTMLElement ? cleanText(labelNode.textContent || "") : ""; return { applicationId, label, node }; } function currentChip() { const chips = Array.from( document.querySelectorAll(ATOMIC_TOOL_CHIP_SELECTOR) ).filter((node) => !isInsideTurboUI(node) && nodeVisible(node)); for (const chip of chips) { const record = chipRecord(chip); if (record) return record; } return null; } function matchesSaved(tool, saved) { if (saved.applicationId) return tool.applicationId === saved.applicationId; const expected = saved.label || saved.legacyLabels[0] || ""; return Boolean(expected) && tool.label === expected; } function collectTools(nodes) { const tools = []; for (const node of nodes) { if (isInsideTurboUI(node) || !nodeVisible(node)) continue; const applicationId = applicationIdOf(node); if (!applicationId) continue; tools.push({ applicationId, label: toolLabel(node), node }); } return tools; } function inlineTools() { const items = Array.from( document.querySelectorAll(ATOMIC_TOOL_ITEM_SELECTOR) ).filter((node) => !node.closest("[role='menu']")); return collectTools(items); } function menuTools() { return collectTools( document.querySelectorAll( `${ATOMIC_TOOL_MENU_SELECTOR} [role='menuitem'][data-application-id]` ) ); } function overflowTrigger() { const actions = document.querySelectorAll(ATOMIC_ACTIONS_SELECTOR); for (const action of actions) { if (isInsideTurboUI(action) || !nodeVisible(action)) continue; const candidates = Array.from( action.querySelectorAll("button[aria-expanded]") ).filter((node) => !node.hasAttribute("data-application-id")); const trigger = candidates.find((node) => nodeVisible(node)); if (trigger) return trigger; } return null; } function atomicToolbarPresent() { return Array.from( document.querySelectorAll(ATOMIC_ACTIONS_SELECTOR) ).some((node) => !isInsideTurboUI(node) && nodeVisible(node)); } function findTool(tools, saved) { if (saved.applicationId) { const byId = tools.find((tool) => tool.applicationId === saved.applicationId); if (byId) return byId; } const expected = saved.label || saved.legacyLabels[0] || ""; if (!expected) return null; return tools.find((tool) => tool.label === expected) ?? null; } function createToolMemoryUtils(deps) { const { el, state, triggerSendButton, restoreCoordinator: providedCoordinator } = deps; const restoreCoordinator = providedCoordinator ?? createRestoreCoordinator(); let statusNode = null; let pollTimer = 0; let pollCount = 0; let stepTimer = 0; const recordTimers = []; const verifyTimers = []; let restoreToken = 0; let restoring = false; let restoreDone = false; let restoreAttempts = 0; let openedOverflow = null; let actionStatus = ""; function stopPolling() { window.clearInterval(pollTimer); pollTimer = 0; pollCount = 0; } function clearTimers(list) { for (const timer of list.splice(0)) window.clearTimeout(timer); } function click(control, scope) { try { return triggerSendButton(control); } catch (error) { reportRecoverableError(scope, error); return false; } } function closeOverflow() { const trigger = openedOverflow; openedOverflow = null; if (!trigger || !trigger.isConnected) return; if (trigger.getAttribute("aria-expanded") !== "true") return; click(trigger, "close tool overflow menu"); } function endRestoreAttempt() { restoring = false; restoreCoordinator.setPending("tools", false); restoreCoordinator.release("tools"); } function finishRestore(token, status) { if (token !== restoreToken) return; endRestoreAttempt(); restoreDone = true; closeOverflow(); actionStatus = status; renderStatus(); } function persistChip(tool) { if (!tool) { clearToolRecord(); actionStatus = "当前没有选中任何工具"; renderStatus(); return; } const saved = readToolRecord(); if (saved && saved.applicationId === tool.applicationId && saved.label === tool.label) { return; } writeToolRecord({ key: "atomic-actions", controlLabel: "工具", applicationId: tool.applicationId, label: tool.label, legacyLabels: tool.label ? [tool.label] : [], ts: Date.now() }); actionStatus = tool.label ? `已记录 ${tool.label}` : `已记录 ${tool.applicationId}`; renderStatus(); } function scheduleRecordCapture(applicationId, label, removing) { clearTimers(recordTimers); let confirmed = false; for (const [index, delay] of RECORD_DELAYS.entries()) { const timer = window.setTimeout(() => { const position = recordTimers.indexOf(timer); if (position >= 0) recordTimers.splice(position, 1); if (isEngineDormant() || !state.rememberTools || confirmed) return; const chip = currentChip(); if (!removing && chip) { if (chip.applicationId === applicationId || index === RECORD_DELAYS.length - 1) { confirmed = true; persistChip(chip); } return; } if (removing && !chip) { confirmed = true; persistChip(null); return; } if (index === RECORD_DELAYS.length - 1) { actionStatus = label ? `未确认 ${label} 的选择,已保留原记录` : "未确认工具选择,已保留原记录"; renderStatus(); } }, delay); recordTimers.push(timer); } } function handleToolClick(event) { if (isEngineDormant()) return; const target = event.target; if (!(target instanceof Element) || isInsideTurboUI(target)) return; const chip = target.closest(ATOMIC_TOOL_CHIP_SELECTOR); if (chip instanceof HTMLElement) { if (restoring || !target.closest("button")) return; const info = chipRecord(chip); scheduleRecordCapture(info?.applicationId || "", info?.label || "", true); return; } if (restoring || !state.rememberTools) return; const item = target.closest(ATOMIC_TOOL_ITEM_SELECTOR); if (!(item instanceof HTMLElement)) return; const applicationId = applicationIdOf(item); if (!applicationId) return; scheduleRecordCapture(applicationId, toolLabel(item), false); } function verifyRestored(token, saved, attemptsLeft) { clearTimers(verifyTimers); for (const [index, delay] of VERIFY_DELAYS.entries()) { const timer = window.setTimeout(() => { const position = verifyTimers.indexOf(timer); if (position >= 0) verifyTimers.splice(position, 1); if (token !== restoreToken) return; const chip = currentChip(); if (chip && matchesSaved(chip, saved)) { clearTimers(verifyTimers); writeToolRecord({ key: "atomic-actions", controlLabel: "工具", applicationId: chip.applicationId, label: chip.label || saved.label, legacyLabels: chip.label ? [chip.label] : saved.legacyLabels, ts: Date.now() }); finishRestore( token, `已恢复 ${chip.label || saved.label || saved.applicationId}` ); return; } if (index !== VERIFY_DELAYS.length - 1) return; endRestoreAttempt(); closeOverflow(); if (attemptsLeft > 1) return; finishRestore(token, "未能恢复已记录的工具"); }, delay); verifyTimers.push(timer); } } function tryRestore(saved, token) { restoreAttempts += 1; const chip = currentChip(); if (chip && matchesSaved(chip, saved)) { finishRestore(token, `已恢复 ${chip.label || saved.label || saved.applicationId}`); return; } const attemptsLeft = MAX_RESTORE_ATTEMPTS - restoreAttempts + 1; const inline = findTool(inlineTools(), saved); if (inline) { if (!click(inline.node, "select atomic tool")) { endRestoreAttempt(); return; } verifyRestored(token, saved, attemptsLeft); return; } const openMenuTool = findTool(menuTools(), saved); if (openMenuTool) { if (!click(openMenuTool.node, "select atomic overflow tool")) { endRestoreAttempt(); return; } verifyRestored(token, saved, attemptsLeft); return; } const trigger = overflowTrigger(); if (!trigger) { endRestoreAttempt(); return; } if (trigger.getAttribute("aria-expanded") !== "true") { openedOverflow = trigger; if (!click(trigger, "open atomic tool overflow")) { openedOverflow = null; endRestoreAttempt(); return; } } let attempt = 0; const wait = () => { stepTimer = 0; if (token !== restoreToken) return; const menuTool = findTool(menuTools(), saved); if (menuTool) { if (!click(menuTool.node, "select atomic overflow tool")) { endRestoreAttempt(); closeOverflow(); return; } verifyRestored(token, saved, attemptsLeft); return; } attempt += 1; if (attempt >= MENU_WAIT_ATTEMPTS) { endRestoreAttempt(); closeOverflow(); return; } stepTimer = window.setTimeout(wait, MENU_WAIT_INTERVAL); }; stepTimer = window.setTimeout(wait, MENU_WAIT_INTERVAL); } function maybeRestore() { if (restoreDone || restoring) return; if (restoreCoordinator.isPending("reasoning")) return; if (isEngineDormant() || !state.rememberTools) { restoreDone = true; return; } const saved = readToolRecord(); if (!saved || !saved.applicationId && !saved.label && !saved.legacyLabels.length) { restoreDone = true; return; } const chip = currentChip(); if (chip && matchesSaved(chip, saved)) { finishRestore(restoreToken, `已恢复 ${chip.label || saved.label || saved.applicationId}`); return; } if (!chip && !atomicToolbarPresent()) return; if (restoreAttempts >= MAX_RESTORE_ATTEMPTS) { finishRestore(restoreToken, "找不到已记录的工具"); return; } if (!restoreCoordinator.tryAcquire("tools")) return; restoreCoordinator.setPending("tools", true); restoring = true; restoreToken += 1; tryRestore(saved, restoreToken); } function clearTimer() { stopPolling(); window.clearTimeout(stepTimer); stepTimer = 0; clearTimers(recordTimers); clearTimers(verifyTimers); restoreToken += 1; endRestoreAttempt(); restoreDone = false; restoreAttempts = 0; closeOverflow(); } function scheduleRestore() { clearTimer(); if (isEngineDormant() || !state.rememberTools) return; const saved = readToolRecord(); if (!saved) return; restoreDone = false; pollTimer = window.setInterval(() => { if (restoreCoordinator.isPending("reasoning")) return; pollCount += 1; maybeRestore(); if (restoreDone || pollCount >= MAX_POLLS) stopPolling(); }, POLL_INTERVAL); } function renderStatus() { if (!statusNode) return; statusNode.textContent = ""; statusNode.title = actionStatus; if (!state.rememberTools) { statusNode.textContent = "工具记忆:已关闭"; return; } const saved = readToolRecord(); if (!saved) { statusNode.textContent = actionStatus || "工具记忆:未记录(在工具按钮里选择一个工具即可)"; return; } const shown = saved.label || saved.applicationId || "已记录工具"; statusNode.textContent = "工具记忆:" + shown + " "; if (actionStatus) { statusNode.appendChild(el("span", {}, ["· " + actionStatus + " "])); } statusNode.appendChild( el( "button", { type: "button", onclick: () => { clearToolRecord(); actionStatus = ""; clearTimer(); renderStatus(); } }, ["清除"] ) ); } function attachStatusNode(node) { statusNode = node; } function teardown() { clearTimer(); statusNode = null; } return { handleToolClick, maybeRestore, scheduleRestore, renderStatus, clearTimer, teardown, attachStatusNode }; } // scripts/ai-chat-turbo-engine/src/core/tool-scope.ts var TOOL_POPUP_TTL = 3e4; function isInsideTurboUI2(node) { if (!(node instanceof Element)) return false; return Boolean(node.closest("[id^='ai-turbo-'], .ai-turbo-code-bar")); } function nodeVisible2(node) { const rect = node.getBoundingClientRect(); return rect.width >= 1 && rect.height >= 1; } function visiblePopups() { return Array.from( document.querySelectorAll(TOOL_POPUP_SELECTOR) ).filter((node) => !isInsideTurboUI2(node) && nodeVisible2(node)); } function popupOwnedByToolTrigger(popup) { if (popup.closest(TOOL_TRIGGER_CONTAINER_SELECTOR)) return true; const popupId = popup.id; if (!popupId) return false; const containers = document.querySelectorAll(TOOL_TRIGGER_CONTAINER_SELECTOR); for (const container of containers) { const controls = container.querySelectorAll("[aria-controls]"); for (const control of controls) { if (control.getAttribute("aria-controls") === popupId) return true; } } return false; } function escapePopup() { const escape = new KeyboardEvent("keydown", { key: "Escape", code: "Escape", keyCode: 27, bubbles: true, cancelable: true }); document.activeElement?.dispatchEvent(escape); document.dispatchEvent(escape); } function createToolPopupScope() { const registered = []; function prune(now) { for (let index = registered.length - 1; index >= 0; index -= 1) { const entry = registered[index]; if (!entry.popup.isConnected || entry.until <= now) { registered.splice(index, 1); } } } function register(control, popup) { const now = Date.now(); prune(now); const existing = registered.find((entry) => entry.popup === popup); if (existing) { existing.control = control; existing.until = now + TOOL_POPUP_TTL; return; } registered.push({ control, popup, until: now + TOOL_POPUP_TTL }); } function snapshot() { return new Set(visiblePopups()); } function note(control, before) { const added = visiblePopups().filter( (popup2) => popup2 !== control && !before.has(popup2) ); const preferredId = control.getAttribute("aria-controls"); const preferred = preferredId ? added.find((popup2) => popup2.id === preferredId) : void 0; const popup = preferred ?? added[added.length - 1]; if (popup) { register(control, popup); return popup; } if (!preferredId) return null; const fallback = document.getElementById(preferredId); if (!(fallback instanceof HTMLElement) || !nodeVisible2(fallback)) { return null; } register(control, fallback); return fallback; } function active(control) { prune(Date.now()); for (let index = registered.length - 1; index >= 0; index -= 1) { const entry = registered[index]; if (entry.control === control && nodeVisible2(entry.popup)) { return entry.popup; } } return null; } function resolve(control) { const known = active(control); if (known) return known; const popupId = control.getAttribute("aria-controls"); if (!popupId) return null; const popup = document.getElementById(popupId); if (!(popup instanceof HTMLElement) || !nodeVisible2(popup)) return null; register(control, popup); return popup; } function popupFor(node) { if (!(node instanceof Element)) return null; prune(Date.now()); for (let index = registered.length - 1; index >= 0; index -= 1) { const entry = registered[index]; if (entry.popup === node || entry.popup.contains(node)) return entry.popup; } const closest = node.closest(TOOL_POPUP_SELECTOR); if (!(closest instanceof HTMLElement)) return null; return popupOwnedByToolTrigger(closest) ? closest : null; } function isInside(node) { return popupFor(node) !== null; } return { snapshot, note, active, resolve, popupFor, isInside, close: escapePopup }; } // scripts/ai-chat-turbo-engine/src/core/composer.ts function createComposerUtils(deps) { const { currentPlatform } = deps; function getChatInput() { const selectors = [ ...currentPlatform.inputSelectors || [], 'form[data-chatgpt-composer] [contenteditable="true"][role="textbox"]', 'div.ProseMirror[contenteditable="true"][role="textbox"]', "rich-textarea div[contenteditable='true']", 'div[contenteditable="true"][role="textbox"]', "textarea", '[contenteditable="true"]' ]; for (const selector of [...new Set(selectors)]) { const candidates = document.querySelectorAll(selector); for (const candidate of candidates) { if (!(candidate instanceof HTMLElement) || !candidate.isConnected || candidate.closest("#" + HUD_ID) || candidate.offsetParent === null && candidate.getClientRects().length === 0) { continue; } if (candidate.matches( 'input[type="hidden"], textarea[aria-hidden="true"]' ) || candidate.getAttribute("aria-hidden") === "true") { continue; } return candidate; } } return null; } function isSendControlForInput(sendControl, inputElement) { if (!(sendControl instanceof HTMLElement) || !(inputElement instanceof HTMLElement)) { return false; } const inputForm = inputElement.closest("form"); const sendForm = sendControl.closest("form"); if (inputForm && sendForm) { return inputForm === sendForm; } const composerSelectors = [ "[data-chatgpt-composer]", ".input-area", ".input-area-container", "rich-textarea", "[class*='composer-parent']", "[class*='input-area']", "[class*='composer']", "[class*='input-container']", "fieldset" ]; const sharesComposerContainer = composerSelectors.some((selector) => { const inputContainer = inputElement.closest(selector); return Boolean( inputContainer && inputContainer === sendControl.closest(selector) ); }); if (sharesComposerContainer) return true; let ancestor = inputElement.parentElement; let depth = 0; while (ancestor && depth < 5 && ancestor !== document.body) { if (ancestor.contains(sendControl)) return true; ancestor = ancestor.parentElement; depth++; } return false; } function isSendLikeButton(btn) { if (!(btn instanceof HTMLElement) || btn.tagName !== "BUTTON") return false; const label = [ btn.getAttribute("aria-label") || "", btn.getAttribute("title") || "", btn.getAttribute("data-testid") || "", btn.getAttribute("data-tooltip") || "" ].join(" ").toLowerCase(); if (/\bstop\b|停止|cancel|abort|中止|取消/.test(label)) return false; return /send|submit|发送|提交|prompt|ask/.test(label); } function isButtonUsable(btn) { if (!(btn instanceof HTMLElement) || !btn.isConnected) return false; if (btn.closest(`#${HUD_ID}, #ai-turbo-vf-tray, #ai-turbo-vf-preview-modal`)) return false; const style = window.getComputedStyle(btn); if (style.display === "none" || style.visibility === "hidden") return false; return btn.getClientRects().length > 0; } function isButtonDisabled(btn) { if (!(btn instanceof HTMLElement)) return true; if (btn.hasAttribute("disabled")) return true; if (btn instanceof HTMLButtonElement && btn.disabled === true) return true; if (btn instanceof HTMLInputElement && btn.disabled === true) return true; if (btn.getAttribute("aria-disabled") === "true") return true; return false; } function findSendControl(inputElement, { allowDisabled = false } = {}) { if (!inputElement) return null; const usable = (btn) => isButtonUsable(btn) && (allowDisabled || !isButtonDisabled(btn)); for (const sel of currentPlatform.sendButtonSelectors || []) { let matches; try { matches = document.querySelectorAll(sel); } catch (error) { reportRecoverableError("query platform send selector", error); continue; } for (const btn of matches) { if (usable(btn) && isSendControlForInput(btn, inputElement) && btn instanceof HTMLElement) { return btn; } } } const form = inputElement.closest("form"); if (form) { for (const btn of form.querySelectorAll( 'button[type="submit"], button:not([type="button"]):not([type="reset"])' )) { if (usable(btn) && isSendLikeButton(btn) && btn instanceof HTMLElement) return btn; } for (const btn of form.querySelectorAll("button")) { if (usable(btn) && isSendLikeButton(btn) && btn instanceof HTMLElement) return btn; } } const composerSelectors = [ "[data-chatgpt-composer]", ".input-area-container", "[class*='composer']", "[class*='input-area']", "[class*='input-container']", "[class*='query-bar']", "rich-textarea", "fieldset" ]; for (const sel of composerSelectors) { let container = null; try { container = inputElement.closest(sel); } catch (error) { reportRecoverableError("query composer container", error); } if (!container) continue; for (const btn of container.querySelectorAll("button")) { if (usable(btn) && isSendLikeButton(btn) && btn instanceof HTMLElement) return btn; } } let ancestor = inputElement.parentElement; let depth = 0; while (ancestor && depth < 8 && ancestor !== document.body && ancestor !== document.documentElement) { for (const btn of ancestor.querySelectorAll("button")) { if (usable(btn) && isSendLikeButton(btn) && btn instanceof HTMLElement) return btn; } ancestor = ancestor.parentElement; depth++; } return null; } function triggerSendButton(btn) { if (!(btn instanceof HTMLElement)) return false; try { btn.focus({ preventScroll: true }); } catch (error) { reportRecoverableError("focus send control", error); } const opts = { bubbles: true, cancelable: true, view: window, button: 0 }; try { btn.dispatchEvent( new PointerEvent("pointerdown", { ...opts, buttons: 1, pointerId: 1, pointerType: "mouse", isPrimary: true }) ); } catch (error) { reportRecoverableError("dispatch pointerdown", error); } try { btn.dispatchEvent(new MouseEvent("mousedown", { ...opts, buttons: 1 })); } catch (error) { reportRecoverableError("dispatch mousedown", error); } try { btn.dispatchEvent( new PointerEvent("pointerup", { ...opts, buttons: 0, pointerId: 1, pointerType: "mouse", isPrimary: true }) ); } catch (error) { reportRecoverableError("dispatch pointerup", error); } try { btn.dispatchEvent(new MouseEvent("mouseup", { ...opts, buttons: 0 })); } catch (error) { reportRecoverableError("dispatch mouseup", error); } try { btn.click(); } catch (error) { reportRecoverableError("click send control", error); return false; } return true; } function fallbackKeyboardSubmit(inputElement) { if (!inputElement) return false; try { inputElement.focus({ preventScroll: true }); } catch (error) { reportRecoverableError("focus composer", error); } const form = inputElement.closest("form"); if (form && typeof form.requestSubmit === "function") { try { form.requestSubmit(); return true; } catch (error) { reportRecoverableError("submit composer form", error); } } const enterOpts = { key: "Enter", code: "Enter", keyCode: 13, which: 13, bubbles: true, cancelable: true, composed: true }; const enterEvt = new KeyboardEvent("keydown", enterOpts); try { Object.defineProperty(enterEvt, "keyCode", { get: () => 13 }); Object.defineProperty(enterEvt, "which", { get: () => 13 }); } catch (error) { reportRecoverableError("emulate legacy Enter key", error); } inputElement.dispatchEvent(enterEvt); inputElement.dispatchEvent(new KeyboardEvent("keyup", enterOpts)); return true; } function getInputContainer(input) { if (!input) return null; const candidates = [ "form[data-chatgpt-composer]", "[data-chatgpt-composer]", "infinite-scroller > .input-area-container", "infinite-scroller > .input-area", "ms-autosize-textarea", "ms-chunk-input-container", ".input-area-container", "form", ".input-area", "[class*='composer-parent']", "[class*='composer']", "[class*='input-area']", "[class*='input-container']", "rich-textarea", "fieldset" ]; const inputRect = input.getBoundingClientRect(); if (!inputRect.width || !inputRect.height) { return input.parentElement; } let best = null; let bestArea = Infinity; for (const selector of candidates) { let matched = null; try { matched = input.closest(selector); } catch (error) { reportRecoverableError("query input container", error); continue; } if (!(matched instanceof HTMLElement) || matched === input) continue; const rect = matched.getBoundingClientRect(); if (rect.height < 20 || rect.width < 40) continue; if (rect.top > inputRect.top + 2) continue; if (rect.bottom < inputRect.bottom - 2) continue; if (rect.width < inputRect.width * 0.75) continue; const area = rect.width * rect.height; if (area < bestArea) { bestArea = area; best = matched; } } return best || input.parentElement; } function getComposerVisualBounds(input, anchor) { const baseRect = (anchor || input).getBoundingClientRect(); const bounds = { top: baseRect.top, left: baseRect.left, right: baseRect.right, width: baseRect.width }; let node = anchor || input; let depth = 0; while (node && depth < COMPOSER_VISUAL_MAX_DEPTH) { const nodeRect = node.getBoundingClientRect(); let cursorTop = Math.min(nodeRect.top, bounds.top); let sibling = node.previousElementSibling; let guard = 0; while (sibling && guard < 24) { guard++; if (sibling.id === "ai-turbo-vf-tray" || sibling.id === HUD_ID || sibling.id === "ai-turbo-vf-preview-modal") { sibling = sibling.previousElementSibling; continue; } const siblingRect = sibling.getBoundingClientRect(); const isVisible = siblingRect.width > 0 && siblingRect.height > 0; if (!isVisible) { sibling = sibling.previousElementSibling; continue; } const siblingStyle = window.getComputedStyle(sibling); if (siblingStyle.position === "fixed" || siblingStyle.position === "sticky") { sibling = sibling.previousElementSibling; continue; } if (sibling.matches('button, [role="button"]') && !sibling.querySelector( 'input, textarea, [contenteditable="true"], [role="textbox"]' )) { sibling = sibling.previousElementSibling; continue; } if (siblingRect.top < 8) { break; } const maxSiblingHeight = Math.max(baseRect.height * 3, 320); if (siblingRect.height > maxSiblingHeight) { break; } const overlap = Math.min(bounds.right, siblingRect.right) - Math.max(bounds.left, siblingRect.left); const minOverlap = Math.min(bounds.width, siblingRect.width) * 0.35; const gap = cursorTop - siblingRect.bottom; if (overlap > minOverlap && gap >= -1 && gap <= COMPOSER_VISUAL_GAP) { bounds.top = Math.min(bounds.top, siblingRect.top); bounds.left = Math.min(bounds.left, siblingRect.left); bounds.right = Math.max(bounds.right, siblingRect.right); bounds.width = bounds.right - bounds.left; cursorTop = siblingRect.top; sibling = sibling.previousElementSibling; continue; } break; } const parent = node.parentElement; if (!parent || parent === document.body || parent === document.documentElement) { break; } node = parent; depth++; } return bounds; } function insertTextAtomic(inputElement, text) { if (inputElement instanceof HTMLTextAreaElement || inputElement instanceof HTMLInputElement) { const proto = inputElement instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set; if (setter) setter.call(inputElement, text); else inputElement.value = text; inputElement.dispatchEvent(new Event("input", { bubbles: true })); inputElement.dispatchEvent(new Event("change", { bubbles: true })); return; } inputElement.focus(); try { const range = document.createRange(); range.selectNodeContents(inputElement); const sel = window.getSelection(); sel?.removeAllRanges(); sel?.addRange(range); } catch (error) { reportRecoverableError("select composer text", error); try { document.execCommand("selectAll"); } catch (fallbackError) { reportRecoverableError("select composer text fallback", fallbackError); } } const singleContainer = `