From f221789a7643b1dea3129af0317aacd635a95ed3 Mon Sep 17 00:00:00 2001 From: Yoko Date: Fri, 4 Dec 2026 19:07:30 +0800 Subject: [PATCH 1/4] fix(ai-chat-turbo-engine): keep the sidebar peek on a history row menu The peek only knew the rail subtree and the popover selector. History row menus are portaled next to the panel with no role annotation, so walking onto one counted as leaving and the hide delay collapsed the panel mid gesture; the submenu that hangs off that menu lost it one level deeper. The peek now adopts the out-of-flow wrapper the pointer reaches straight from the panel, within a bounded 500ms hand-off measured from the last contact with the rail or an adopted layer, so a flyout the user walks into long afterwards still belongs to the page. Viewport-sized fixed shells are rejected so page content never pins the peek, and an adopted layer is dropped as soon as the site tears it down. --- .../src/core/sidebar-peek.ts | 195 ++++++++++++- tests/ai-chat-turbo-sidebar-peek.test.ts | 270 ++++++++++++++++++ 2 files changed, 456 insertions(+), 9 deletions(-) diff --git a/scripts/ai-chat-turbo-engine/src/core/sidebar-peek.ts b/scripts/ai-chat-turbo-engine/src/core/sidebar-peek.ts index 1ee8f15..cfbd6e2 100644 --- a/scripts/ai-chat-turbo-engine/src/core/sidebar-peek.ts +++ b/scripts/ai-chat-turbo-engine/src/core/sidebar-peek.ts @@ -119,6 +119,16 @@ const POPOVER_SELECTOR = [ /** How often a held peek re-checks whether the site menu is still open. */ const POPOVER_RECHECK_MS = 400; +/** + * How long after the pointer last rested on the peek a flyout it mounts still + * belongs to that peek. History row menus are mounted next to the panel, + * outside the rail's own subtree, and most sites annotate them with no role at + * all, so the hand-off from a rail row into that menu is the only reliable + * link between them. The window is bounded because a flyout the user walks + * into long afterwards belongs to the page, not to the hover that ended. + */ +export const SIDEBAR_PEEK_HANDOFF_MS = 500; + /** * Minimum gap between pointer-move probes. The hover intent delay is longer * than this, so throttling loses no approach; it only keeps a cursor swept @@ -339,6 +349,21 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { * belong to the page, not to the hovered rail, so they can never hold it. */ const preexistingPopovers = new Set(); + /** + * Floating boxes the peek adopted because the pointer walked into them from + * the panel: a history row menu, and the submenu that hangs off that menu. + * Hovering one is hovering the peek, however far from the rail it is painted. + */ + const peekLayers = new Set(); + /** When the pointer last rested on the rail or on an adopted layer. */ + let lastPeekPointerMs = Number.NEGATIVE_INFINITY; + /** + * When the pointer last walked off an adopted layer. The submenu a row menu + * opens is often portaled into a sibling wrapper a few pixels away, so the + * event that names it can arrive from the gap between the two boxes instead + * of from the menu itself. That departure is the hand-off. + */ + let lastLayerExitMs = Number.NEGATIVE_INFINITY; const hasRail = sidebarSelectors.length > 0; @@ -714,6 +739,9 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { cancelClickRelease(); rescanNeeded = false; preexistingPopovers.clear(); + peekLayers.clear(); + lastPeekPointerMs = Number.NEGATIVE_INFINITY; + lastLayerExitMs = Number.NEGATIVE_INFINITY; const node = active; if (node === null) return; active = null; @@ -1750,7 +1778,7 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { // A menu the peek opened lives outside the rail in the body, so the // pointer leaving the rail is not the user leaving the peek. Only a // menu the pointer actually entered counts. - if (popoverUnderPointer() !== null) { + if (menuUnderPointer() !== null) { holdForPopover(rail); return; } @@ -1765,13 +1793,14 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { * somewhere else on the page: those used to pin the peek for its whole * budget and made the panel look stuck. */ - function popoverUnderPointer(): HTMLElement | null { + function menuUnderPointer(): HTMLElement | null { 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; + if (!(hit instanceof Element)) return null; + return peekLayerAt(hit) ?? popoverFor(hit); } /** @@ -1839,6 +1868,111 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { return found; } + /** + * The adopted layer the pointer is inside, i.e. a row menu or its submenu. A + * layer the site tore down is dropped here instead of pinning the peek to a + * node nobody can see. + */ + function peekLayerAt(node: Element | null): HTMLElement | null { + if (!(node instanceof Element)) return null; + for (const layer of peekLayers) { + if (!layer.isConnected) { + peekLayers.delete(layer); + continue; + } + if (layer === node || layer.contains(node)) return layer; + } + return null; + } + + /** Whether the pointer node belongs to the peek or to one of its layers. */ + function ownedByPeek(node: Element | null): boolean { + if (node === null) return false; + return railFor(node) !== null || peekLayerAt(node) !== null; + } + + /** + * Adopt the out-of-flow wrapper the pointer just walked into from the peek. + * Page content is laid out in flow, and a wrapper that holds the rail is the + * app shell rather than a menu: both are rejected, so only a floating box + * the pointer reached straight from the panel becomes part of it. The + * outermost such ancestor wins, which is what lets a submenu hang off the + * menu that opened it and still count. + */ + function adoptPeekLayer( + target: Element, + fromLayer = false, + ): HTMLElement | null { + const known = peekLayerAt(target); + if (known !== null) return known; + const doc = boundDocument; + const view = doc?.defaultView ?? null; + if (active === null || doc === null || view === null) { + return null; + } + // Sites rebuild the rail while its menus stay put; the node the peek owns + // is still the best answer for "which wrapper belongs to the page shell" + // even when the current selector no longer resolves it. + const rail = resolvedRail ?? active; + if (!fromLayer) { + const now = performance.now(); + // A flyout reached straight off the rail belongs to the hover that + // opened it; one reached off an adopted menu belongs to that menu, no + // matter how long the pointer rested on it before asking for the + // submenu. + const handedOffFromPeek = + now - lastPeekPointerMs <= SIDEBAR_PEEK_HANDOFF_MS; + const handedOffFromLayer = + now - lastLayerExitMs <= SIDEBAR_PEEK_HANDOFF_MS; + if (!handedOffFromPeek && !handedOffFromLayer) return null; + } + const candidates: HTMLElement[] = []; + for ( + let node: Element | null = target; + node !== null && node !== doc.body && node !== doc.documentElement; + node = node.parentElement + ) { + if (!(node instanceof HTMLElement)) break; + // The rail's own wrapper is the page shell; everything above it is page + // layout, not a menu. + if (node.contains(rail)) break; + if (node.matches(POPOVER_SELECTOR)) { + candidates.push(node); + continue; + } + const position = view.getComputedStyle(node).position; + if ( + position === "absolute" || + position === "fixed" || + position === "sticky" + ) { + candidates.push(node); + } + } + for (let index = candidates.length - 1; index >= 0; index -= 1) { + const layer = candidates[index] as HTMLElement; + // A menu the page already had on screen is the page's own, and a wrapper + // it closed is not the one the pointer is using. + if (isPreexistingPopover(layer)) continue; + if (!isVisiblePopover(layer, view)) continue; + // A viewport-sized fixed wrapper is the page chrome, not a flyout. Left + // in, walking from the rail into the chat column would keep the panel + // open for as long as the pointer moved there. + const rect = layer.getBoundingClientRect(); + if ( + view.innerWidth > 0 && + view.innerHeight > 0 && + rect.width >= view.innerWidth * 0.7 && + rect.height >= view.innerHeight * 0.6 + ) { + continue; + } + peekLayers.add(layer); + return layer; + } + return null; + } + function isPreexistingPopover(node: HTMLElement): boolean { if (preexistingPopovers.size === 0) return false; for (const known of preexistingPopovers) { @@ -1864,7 +1998,7 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { holdTimer = setTimeout(() => { holdTimer = null; if (active !== rail) return; - const popover = popoverUnderPointer(); + const popover = menuUnderPointer(); if (popover !== null && holdRemainingMs > 0) { holdForPopover(rail); return; @@ -1885,6 +2019,9 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { const hit = doc.elementFromPoint(pointerX, pointerY); if (hit instanceof Element) { if (current.contains(hit) || rail.contains(hit)) return true; + // A row menu or a submenu the peek adopted is painted outside the rail + // but is still the peek: hovering it is not leaving the panel. + if (peekLayerAt(hit) !== null) return true; // Gemini and Grok open through their own toggle, which sits outside the // rail. The pointer still rests on the control that opened the panel, so // the peek must not close underneath it. @@ -1926,11 +2063,19 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { if (!(target instanceof Element)) return; const rail = railFor(target); if (rail === null) { + // A flyout the pointer just walked into from the panel is part of the + // peek from here on, so hide nothing and keep the deadline unarmed. + if (adoptPeekLayer(target) !== null) { + lastPeekPointerMs = performance.now(); + cancelHide(); + return; + } // A panel painted by a sibling shell or a blank row between two of them // is still the peek the pointer just came back to. if (pointerReturnedToPeek()) cancelHide(); return; } + lastPeekPointerMs = performance.now(); if (active === rail) { liftInert(rail); if (rescanNeeded) { @@ -1957,6 +2102,7 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { if (target instanceof Element) { const overRail = railFor(target); if (overRail !== null) { + lastPeekPointerMs = performance.now(); // A move that already lands on the rail is the strongest form of the // same intent. Waiting for pointerover loses the first approach when // the rail sits under a transparent overlay, when its box is zero @@ -1966,6 +2112,13 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { return; } } + // A flyout a site re-renders under the resting pointer arrives here as a + // move rather than a pointerover; it is still the peek. + if (target instanceof Element && adoptPeekLayer(target) !== null) { + lastPeekPointerMs = performance.now(); + cancelHide(); + return; + } // Coming back inside the panel before the grace expires is a return, not // a leave: the countdown starts over from the next exit. if (pointerReturnedToPeek()) { @@ -2032,7 +2185,7 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { cancelHide(); return; } - if (popoverUnderPointer() !== null) { + if (menuUnderPointer() !== null) { holdForPopover(open); return; } @@ -2055,9 +2208,29 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { const target = event.target; if (!(target instanceof Element)) return; const rail = railFor(target); - if (rail === null) return; const related = (event as MouseEvent).relatedTarget; - if (related instanceof Element && railFor(related) === rail) return; + if (rail === null) { + // No rail pointerout ever fires when the pointer walks off an adopted + // row menu, so that departure arms the grace here. + const layer = peekLayerAt(target); + if (layer === null || active === null) return; + lastLayerExitMs = performance.now(); + if (related instanceof Element && ownedByPeek(related)) return; + // Walking from the row menu into the submenu it opens is still the + // peek: adopt the box the pointer is heading into instead of arming a + // hide the pointer is about to outrun. + if ( + related instanceof Element && + adoptPeekLayer(related, true) !== null + ) { + lastPeekPointerMs = performance.now(); + cancelHide(); + return; + } + scheduleHide(active); + return; + } + if (related instanceof Element && ownedByPeek(related)) return; scheduleHide(rail); } @@ -2101,7 +2274,8 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { if (rail === null) return; const target = event.target; if (!(target instanceof Element)) return; - if (!rail.contains(target)) return; + // A row menu the peek adopted is pressed as part of the panel. + if (!rail.contains(target) && peekLayerAt(target) === null) return; if (keepsPeek(target)) return; const anchor = target.closest("a[href]"); const view = rail.ownerDocument.defaultView; @@ -2168,7 +2342,10 @@ export function createSidebarPeek(options: SidebarPeekOptions): SidebarPeek { if (!(target instanceof Element)) return; // A press inside a menu the peek opened belongs to the peek, even though // the site portals that menu outside the rail. - if (active !== null && popoverFor(target) !== null) { + if ( + active !== null && + (peekLayerAt(target) !== null || popoverFor(target) !== null) + ) { cancelHide(); // The click may close the menu or keep it open for another choice; the // watcher decides on the next tick instead of leaving the peek pinned. diff --git a/tests/ai-chat-turbo-sidebar-peek.test.ts b/tests/ai-chat-turbo-sidebar-peek.test.ts index d204790..32805c9 100644 --- a/tests/ai-chat-turbo-sidebar-peek.test.ts +++ b/tests/ai-chat-turbo-sidebar-peek.test.ts @@ -4,6 +4,7 @@ import { SIDEBAR_PEEK_ATTRIBUTE, SIDEBAR_PEEK_CLICK_RELEASE_MS, SIDEBAR_PEEK_HIDE_DELAY_MS, + SIDEBAR_PEEK_HANDOFF_MS, SIDEBAR_PEEK_HOLD_ATTRIBUTE, SIDEBAR_PEEK_KEYBOARD_FOCUS_MS, SIDEBAR_PEEK_NAVIGATION_COLLAPSE_MS, @@ -533,6 +534,275 @@ describe("sidebar hover peek", () => { expect(instance.isPeeking()).toBe(false); }); + /** + * A history row action menu is mounted next to the panel, outside the + * rail's DOM subtree, and most sites annotate it with no role at all. The + * pointer walking from the row onto that menu is still the peek being used, + * so the panel must not collapse underneath it. + */ + it("keeps the peek while the pointer rests on a history row menu", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const row = document.getElementById("history"); + if (!(row instanceof HTMLElement)) throw new Error("missing history row"); + stubNodeRect(row, 248, 32, 0); + const menu = document.createElement("div"); + menu.style.position = "absolute"; + stubNodeRect(menu, 180, 120, 300); + const entry = document.createElement("button"); + entry.textContent = "Rename"; + menu.appendChild(entry); + document.body.appendChild(menu); + const restore = stubHit(entry); + + try { + dispatchPointer("pointerover", row, null, "mouse", 40, 100); + dispatchPointer("pointerout", row, entry, "mouse", 300, 100); + dispatchPointer("pointerover", entry, row, "mouse", 300, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(true); + + const chat = document.getElementById("chat"); + if (!chat) throw new Error("missing chat"); + const restoreChat = stubHit(chat); + try { + dispatchPointer("pointerout", entry, chat, "mouse", 600, 300); + dispatchPointerMove(600, 300, chat); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(false); + } finally { + restoreChat(); + } + } finally { + restore(); + menu.remove(); + } + }); + + /** A second-level submenu hangs off the first one and is mounted the same way. */ + it("keeps the peek on a submenu under the row menu", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const row = document.getElementById("history"); + if (!(row instanceof HTMLElement)) throw new Error("missing history row"); + stubNodeRect(row, 248, 32, 0); + const menu = document.createElement("div"); + menu.style.position = "absolute"; + stubNodeRect(menu, 180, 120, 300); + const entry = document.createElement("button"); + menu.appendChild(entry); + document.body.appendChild(menu); + const submenu = document.createElement("div"); + submenu.style.position = "absolute"; + stubNodeRect(submenu, 160, 96, 480); + const subEntry = document.createElement("button"); + subEntry.textContent = "Move to folder"; + submenu.appendChild(subEntry); + document.body.appendChild(submenu); + const restore = stubHit(entry); + + try { + dispatchPointer("pointerover", row, null, "mouse", 40, 100); + dispatchPointer("pointerout", row, entry, "mouse", 300, 100); + dispatchPointer("pointerover", entry, row, "mouse", 300, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(true); + + const restoreSub = stubHit(subEntry); + try { + dispatchPointer("pointerout", entry, subEntry, "mouse", 480, 100); + dispatchPointer("pointerover", subEntry, entry, "mouse", 480, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(true); + } finally { + restoreSub(); + } + } finally { + restore(); + menu.remove(); + submenu.remove(); + } + }); + + /** + * A flyout hangs off the menu the pointer is already using, so the hand-off + * must not depend on how long the pointer rested there: a user who reads the + * first menu for a while and then moves into its submenu is still peeking. + */ + it("keeps the peek on a submenu reached after resting on the row menu", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const row = document.getElementById("history"); + if (!(row instanceof HTMLElement)) throw new Error("missing history row"); + stubNodeRect(row, 248, 32, 0); + const menu = document.createElement("div"); + menu.style.position = "absolute"; + stubNodeRect(menu, 180, 120, 300); + const entry = document.createElement("button"); + entry.textContent = "Move to"; + menu.appendChild(entry); + document.body.appendChild(menu); + const submenu = document.createElement("div"); + submenu.style.position = "absolute"; + stubNodeRect(submenu, 160, 96, 480); + const subEntry = document.createElement("button"); + subEntry.textContent = "Project"; + submenu.appendChild(subEntry); + document.body.appendChild(submenu); + const restoreEntry = stubHit(entry); + + try { + dispatchPointer("pointerover", row, null, "mouse", 40, 100); + dispatchPointer("pointerout", row, entry, "mouse", 300, 100); + dispatchPointer("pointerover", entry, row, "mouse", 300, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HANDOFF_MS + 200); + expect(instance.isPeeking()).toBe(true); + + const restoreSub = stubHit(subEntry); + try { + dispatchPointer("pointerout", entry, subEntry, "mouse", 480, 100); + dispatchPointer("pointerover", subEntry, entry, "mouse", 480, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(true); + } finally { + restoreSub(); + } + } finally { + restoreEntry(); + menu.remove(); + submenu.remove(); + } + }); + + /** + * Site menus are usually a few pixels apart. Crossing that gap fires the + * naming event from the page, not from the menu, so the departure from the + * adopted layer is what has to carry the hand-off. + */ + it("keeps the peek on a submenu across the gap after the menu", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const row = document.getElementById("history"); + if (!(row instanceof HTMLElement)) throw new Error("missing history row"); + stubNodeRect(row, 248, 32, 0); + const chat = document.getElementById("chat"); + if (!(chat instanceof HTMLElement)) throw new Error("missing chat"); + const menu = document.createElement("div"); + menu.style.position = "absolute"; + stubNodeRect(menu, 180, 120, 300); + const entry = document.createElement("button"); + entry.textContent = "Move to"; + menu.appendChild(entry); + document.body.appendChild(menu); + const submenu = document.createElement("div"); + submenu.style.position = "absolute"; + stubNodeRect(submenu, 160, 96, 480); + const subEntry = document.createElement("button"); + subEntry.textContent = "Project"; + submenu.appendChild(subEntry); + document.body.appendChild(submenu); + const restoreEntry = stubHit(entry); + + try { + dispatchPointer("pointerover", row, null, "mouse", 40, 100); + dispatchPointer("pointerout", row, entry, "mouse", 300, 100); + dispatchPointer("pointerover", entry, row, "mouse", 300, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HANDOFF_MS + 200); + + const restoreGap = stubHit(chat); + try { + dispatchPointer("pointerout", entry, chat, "mouse", 470, 100); + dispatchPointer("pointerover", chat, entry, "mouse", 470, 100); + } finally { + restoreGap(); + } + + const restoreSub = stubHit(subEntry); + try { + dispatchPointer("pointerover", subEntry, chat, "mouse", 480, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(true); + } finally { + restoreSub(); + } + } finally { + restoreEntry(); + menu.remove(); + submenu.remove(); + } + }); + + /** + * Page chrome is often a fixed wrapper that does not contain the rail. It is + * not a flyout: adopting it would keep the panel open for as long as the + * pointer moved around the app. + */ + it("does not adopt a viewport-sized fixed wrapper as a peek layer", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const button = document.getElementById("new-chat"); + if (!(button instanceof HTMLElement)) throw new Error("missing button"); + const shell = document.createElement("div"); + shell.style.position = "fixed"; + stubNodeRect(shell, 1024, 768); + const inner = document.createElement("button"); + inner.textContent = "Chat column"; + shell.appendChild(inner); + document.body.appendChild(shell); + const restore = stubHit(inner); + + try { + dispatchPointer("pointerout", button, inner, "mouse", 600, 300); + dispatchPointer("pointerover", inner, button, "mouse", 600, 300); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(false); + } finally { + restore(); + shell.remove(); + } + }); + + /** A flyout that shows up long after the hover belongs to the page. */ + it("does not adopt a flyout the pointer reached long after the hover", () => { + const instance = start(); + hoverButton(); + vi.advanceTimersByTime(SIDEBAR_PEEK_SHOW_DELAY_MS); + + const row = document.getElementById("history"); + if (!(row instanceof HTMLElement)) throw new Error("missing history row"); + stubNodeRect(row, 248, 32, 0); + dispatchPointer("pointerover", row, null, "mouse", 40, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HANDOFF_MS + 200); + + const menu = document.createElement("div"); + menu.style.position = "absolute"; + stubNodeRect(menu, 180, 120, 300); + const entry = document.createElement("button"); + menu.appendChild(entry); + document.body.appendChild(menu); + const restore = stubHit(entry); + + try { + dispatchPointer("pointerout", row, entry, "mouse", 300, 100); + dispatchPointer("pointerover", entry, row, "mouse", 300, 100); + vi.advanceTimersByTime(SIDEBAR_PEEK_HIDE_DELAY_MS); + expect(instance.isPeeking()).toBe(false); + } finally { + restore(); + menu.remove(); + } + }); + it("closes immediately on an outside press or the native toggle", () => { const instance = start(); hoverButton(); From 9754764626c45ee27121c7a1b81620609a6ad0b0 Mon Sep 17 00:00:00 2001 From: Yoko Date: Fri, 4 Dec 2026 19:07:53 +0800 Subject: [PATCH 2/4] fix(ai-chat-turbo-engine): show the version the bundle was built with The panel subtitle read the version from GM_info through the userscript globals helper. This script runs with @grant none, so no manager API exists on the page and the 0.0.0 fallback rendered on every platform while the header declared 0.23.17. The build now passes the metadata version through esbuild define, the same source the header is rendered from, and lifecycle reads that constant. A build test pins the artifact to meta.ts and to the absence of both 0.0.0 and a leftover GM_info read; a HUD test pins the subtitle. --- .../src/build-constants.d.ts | 5 +++ scripts/ai-chat-turbo-engine/src/lifecycle.ts | 8 ++-- tests/ai-chat-turbo-hud.test.ts | 7 +++ tests/build.test.ts | 45 +++++++++++++++++++ tools/build-lib.ts | 13 +++++- vitest.config.ts | 3 ++ 6 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 scripts/ai-chat-turbo-engine/src/build-constants.d.ts diff --git a/scripts/ai-chat-turbo-engine/src/build-constants.d.ts b/scripts/ai-chat-turbo-engine/src/build-constants.d.ts new file mode 100644 index 0000000..285dab2 --- /dev/null +++ b/scripts/ai-chat-turbo-engine/src/build-constants.d.ts @@ -0,0 +1,5 @@ +/** + * Replaced by the build with the `@version` its header carries. Tests define + * it in `vitest.config.ts`; the bundle never contains the identifier itself. + */ +declare const __SCRIPT_VERSION__: string; diff --git a/scripts/ai-chat-turbo-engine/src/lifecycle.ts b/scripts/ai-chat-turbo-engine/src/lifecycle.ts index 13cd6f6..627d0b7 100644 --- a/scripts/ai-chat-turbo-engine/src/lifecycle.ts +++ b/scripts/ai-chat-turbo-engine/src/lifecycle.ts @@ -1,4 +1,3 @@ -import { readUserscriptInfo } from "../../../shared/userscript/globals"; import { createTurnUtils } from "./core/turns"; import { createTurnTextIndex } from "./core/turn-index"; import { createMotionQuiet } from "./core/motion-quiet"; @@ -59,8 +58,11 @@ import { } from "./core/auth"; export function initializeEngine(): void { - // Read the version from the userscript header so the panel cannot drift. - const VERSION = readUserscriptInfo(globalThis)?.script.version ?? "0.0.0"; + // The build substitutes the version its own header carries, so the panel + // cannot drift from the artifact it shipped in. Asking the userscript + // manager instead reported 0.0.0 on every page: this script runs with + // `@grant none`, and that leaves no GM_info on the page to read. + const VERSION = __SCRIPT_VERSION__; const detectedPlatform = detectPlatform(); if (detectedPlatform === null) return; diff --git a/tests/ai-chat-turbo-hud.test.ts b/tests/ai-chat-turbo-hud.test.ts index 92758f0..d5925ba 100644 --- a/tests/ai-chat-turbo-hud.test.ts +++ b/tests/ai-chat-turbo-hud.test.ts @@ -265,6 +265,13 @@ afterEach(() => { }); describe("HUD panel structure", () => { + it("shows the version the bundle was built with", () => { + const { shadow } = createHud(); + const subtitle = shadow.querySelector(".brand-subtitle"); + expect(subtitle?.textContent).toContain("v0.17.1"); + expect(subtitle?.textContent).not.toContain("0.0.0"); + }); + it("renders the four status cards and advanced settings closed by default", () => { const { shadow, panel } = createHud(); const labels = Array.from( diff --git a/tests/build.test.ts b/tests/build.test.ts index 695b202..be666e9 100644 --- a/tests/build.test.ts +++ b/tests/build.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { compileScript, discoverScripts, + loadScriptMeta, parseBuildArguments, selectTargets, } from "../tools/build-lib"; @@ -87,3 +88,47 @@ describe("script discovery and compilation", () => { expect(() => selectTargets(targets, ["missing"])).toThrow(/Unknown script target/); }); }); + +describe("version injection", () => { + it("writes the metadata version into the bundle", async () => { + const root = await createFixture(); + const targets = await discoverScripts(root); + const target = targets[0]; + if (target === undefined) throw new Error("fixture target missing"); + await writeFile( + path.join(root, "scripts", "demo", "src", "index.ts"), + "console.log(__SCRIPT_VERSION__);\n", + "utf8", + ); + const meta: UserscriptMeta = { + name: "Demo", + namespace: "https://example.com/", + version: "2.4.6", + description: "Demo", + author: "Yoko", + match: ["https://example.com/*"], + grant: ["none"], + }; + const built = await compileScript(target, meta, renderUserscriptHeader(meta)); + expect(built.source).toContain('console.log("2.4.6")'); + expect(built.source).not.toContain("__SCRIPT_VERSION__"); + }); + + /** + * The panel used to read its version from GM_info, which `@grant none` + * leaves undefined: every page showed 0.0.0. The shipped artifact must carry + * the header's own number instead, with no fallback string left behind. + */ + it("ships the engine's header version and nothing to fall back to", async () => { + const targets = await discoverScripts(process.cwd()); + const [target] = selectTargets(targets, ["ai-chat-turbo-engine"]); + if (target === undefined) throw new Error("engine target missing"); + const meta = await loadScriptMeta(target, Date.now()); + const built = await compileScript(target, meta, renderUserscriptHeader(meta)); + + expect(built.source).toContain("// @version " + meta.version); + expect(built.source).toContain('const VERSION = "' + meta.version + '"'); + expect(built.source).not.toContain("0.0.0"); + expect(built.source).not.toContain("GM_info"); + }); +}); diff --git a/tools/build-lib.ts b/tools/build-lib.ts index a1217ad..c53085c 100644 --- a/tools/build-lib.ts +++ b/tools/build-lib.ts @@ -126,7 +126,15 @@ export async function loadScriptMeta(target: ScriptTarget, cacheVersion: number) return parseUserscriptMeta(loaded.default); } -export async function bundleScript(target: ScriptTarget): Promise { +/** + * Identifier the bundle reads its version from. It is replaced at build time + * with the metadata version, so the artifact carries the same number as its + * header and the runtime never has to ask the userscript manager: ScriptCat + * runs this script with `@grant none`, which leaves no `GM_info` to read. + */ +export const SCRIPT_VERSION_DEFINE = "__SCRIPT_VERSION__"; + +export async function bundleScript(target: ScriptTarget, meta: UserscriptMeta): Promise { return build({ entryPoints: [target.entryFile], outfile: path.join(path.dirname(path.dirname(target.directory)), "dist", `${target.name}.user.js`), @@ -140,6 +148,7 @@ export async function bundleScript(target: ScriptTarget): Promise { legalComments: "none", logLevel: "silent", metafile: true, + define: { [SCRIPT_VERSION_DEFINE]: JSON.stringify(meta.version) }, }); } @@ -160,7 +169,7 @@ function findJavaScriptOutput(result: BuildResult): { code: string; imports: num } export async function compileScript(target: ScriptTarget, meta: UserscriptMeta, header: string): Promise { - const result = await bundleScript(target); + const result = await bundleScript(target, meta); const output = findJavaScriptOutput(result); if (output.imports > 0) { throw new Error(`${target.name} contains external imports; userscript output must be self-contained`); diff --git a/vitest.config.ts b/vitest.config.ts index 56e93e4..d010e04 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,6 +1,9 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ + // The userscript bundle receives this from its metadata at build time. + // Tests import the same source unbundled, so they name it here. + define: { __SCRIPT_VERSION__: JSON.stringify("test-build") }, test: { include: ["tests/**/*.test.ts", "shared/**/*.test.ts"], environment: "node", From c840a81c2386c27d48db6787078b7ab218780929 Mon Sep 17 00:00:00 2001 From: Yoko Date: Fri, 4 Dec 2026 19:07:57 +0800 Subject: [PATCH 3/4] fix(ai-chat-turbo-engine): pass a Shift+Enter soft break through to Yuanbao The paragraph net on beforeinput cannot see modifier keys. A soft line break is inserted as insertParagraph, so the net took it for a bare Enter, sent, and called preventDefault after Quill had already committed the newline to its model. The DOM and the model then disagreed and the next typed character was inserted twice, which reproduced as a doubled punctuation mark. The keydown stage now remembers a Shift+Enter inside the composer and lets the paragraph insertion it causes through for 200ms. A bare Enter that bypasses keydown still sends, including once that window has passed. --- scripts/ai-chat-turbo-engine/src/core/send.ts | 35 ++++++++++++++++--- tests/ai-chat-turbo-send.test.ts | 30 ++++++++++++++++ 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/scripts/ai-chat-turbo-engine/src/core/send.ts b/scripts/ai-chat-turbo-engine/src/core/send.ts index fa5a423..52672e3 100644 --- a/scripts/ai-chat-turbo-engine/src/core/send.ts +++ b/scripts/ai-chat-turbo-engine/src/core/send.ts @@ -62,6 +62,16 @@ export interface SendInterceptUtils { */ const IME_SETTLE_MS = 30; +/** + * A `beforeinput` carries no modifier keys, so the paragraph break it + * describes can only be attributed to the keydown that produced it. Shift + * keeps the site's soft newline, and treating that break as a send cancels an + * edit Quill has already committed to its model: the next typed character + * then lands twice. The window only has to cover the same task as the + * keydown, and staying short keeps a genuine bypassed Enter sending. + */ +const SOFT_ENTER_CONTEXT_MS = 200; + function isNodeLike(value: unknown): value is Node { return ( typeof value === "object" && @@ -70,6 +80,14 @@ function isNodeLike(value: unknown): value is Node { ); } +function isEnterStroke(event: KeyboardEvent): boolean { + return ( + event.key === "Enter" || + event.code === "Enter" || + event.code === "NumpadEnter" + ); +} + export function createSendInterceptUtils( deps: SendInterceptDeps, ): SendInterceptUtils { @@ -93,6 +111,8 @@ export function createSendInterceptUtils( let composing = false; let composeSettleTimer = 0; + /** When the last Shift+Enter was pressed inside a composer. */ + let softEnterMs = Number.NEGATIVE_INFINITY; function bindCompositionTracking(target: Window): void { target.addEventListener( @@ -154,11 +174,7 @@ export function createSendInterceptUtils( */ function isEnterKey(event: KeyboardEvent): boolean { if (event.shiftKey) return false; - const stroke = - event.key === "Enter" || - event.code === "Enter" || - event.code === "NumpadEnter"; - if (!stroke) return false; + if (!isEnterStroke(event)) return false; if (event.isComposing) return false; return !composing; } @@ -411,6 +427,14 @@ export function createSendInterceptUtils( if (event.type === "keydown") { const keyEvent = event as KeyboardEvent; + // Remember the soft break before the send checks drop the key: the + // paragraph break that follows it belongs to the site's newline. + if (isEnterStroke(keyEvent) && keyEvent.shiftKey) { + const softTarget = resolveComposerInput(event); + if (softTarget !== null && isEventInside(softTarget, event)) { + softEnterMs = performance.now(); + } + } if (!isEnterKey(keyEvent)) return; const input = resolveComposerInput(event); @@ -446,6 +470,7 @@ export function createSendInterceptUtils( if (inputEvent.inputType !== "insertParagraph") return; if (currentPlatform.enterToSend !== true) return; if (composing) return; + if (performance.now() - softEnterMs < SOFT_ENTER_CONTEXT_MS) return; const input = resolveComposerInput(event); if (!input || !isEventInside(input, event)) return; diff --git a/tests/ai-chat-turbo-send.test.ts b/tests/ai-chat-turbo-send.test.ts index 37fbd75..4cadac6 100644 --- a/tests/ai-chat-turbo-send.test.ts +++ b/tests/ai-chat-turbo-send.test.ts @@ -270,6 +270,36 @@ describe("send intercept", () => { expect(fixture.isSubmitting()).toBe(false); }); + /** + * The site turns Shift+Enter into a paragraph break through `beforeinput`, + * which carries no modifiers. Treating that break as a send cancels an edit + * the editor already committed, and every following character then lands + * twice in Yuanbao's Quill composer. + */ + it("keeps the paragraph break that follows Shift+Enter a soft newline", () => { + const fixture = createFixture(); + + expect(fixture.press({ key: "Enter", shiftKey: true }).defaultPrevented) + .toBe(false); + + const beforeinput = fixture.type({ inputType: "insertParagraph" }); + + expect(beforeinput.defaultPrevented).toBe(false); + expect(fixture.fuseAndSubmit).not.toHaveBeenCalled(); + expect(fixture.isSubmitting()).toBe(false); + }); + + it("sends a bare paragraph break once the soft-enter window passed", () => { + const fixture = createFixture(); + fixture.press({ key: "Enter", shiftKey: true }); + vi.advanceTimersByTime(400); + + const beforeinput = fixture.type({ inputType: "insertParagraph" }); + + expect(beforeinput.defaultPrevented).toBe(true); + expect(fixture.fuseAndSubmit).toHaveBeenCalledWith(fixture.input); + }); + it("leaves modified Enter and other keys to the site", () => { const fixture = createFixture(); From 867fed5193bf1b1965e43f6c7f2e356555e52934 Mon Sep 17 00:00:00 2001 From: Yoko Date: Fri, 4 Dec 2026 19:08:12 +0800 Subject: [PATCH 4/4] chore(ai-chat-turbo): bump version to 0.23.18 Records the three repairs in the version log: the peek keeps a history row menu and its submenu inside the panel, the settings panel shows the version the header declares, and a Shift+Enter soft break no longer doubles the next punctuation on Yuanbao. --- docs/ai-chat-turbo-engine.md | 14 ++++++++++++++ scripts/ai-chat-turbo-engine/meta.ts | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/ai-chat-turbo-engine.md b/docs/ai-chat-turbo-engine.md index fd93cf9..8367e9a 100644 --- a/docs/ai-chat-turbo-engine.md +++ b/docs/ai-chat-turbo-engine.md @@ -135,6 +135,7 @@ contain-intrinsic-size: auto var(--turbo-cached-h, 120px); - **脚本只碰必要的内联值。** ChatGPT 的展开面板常驻 DOM,但滚动区带内联的隐藏声明,样式表压不过它,因此探出模块按快照临时抬起该声明、收回时原样写回;这是唯一需要改内联样式的情况,同样不复制节点。 - **内容不再被内层容器裁掉。** 有些站点把面板内容挂在按折叠宽度写死的容器上,只加宽导轨会出现「导轨变宽了、标签仍被裁」的半截状态。平台在 `sidebar.shells` 里列出这些容器(ChatGPT 的 `#app-shell-sidebar`、Gemini 的 `bard-sidenav` 等),探出时同时给 `width` / `min-width` / `max-width` 写探出宽度,收回时按内联快照逐条还原;基础规则也带 `min-width`、`max-width` 与 `box-sizing: border-box`,避免站点自己的 `max-width` 把加宽压回去。 - **中间空隙不会打断探出。** 面板内容可能画在导轨之外的兄弟层里,指针经过这些空白区域时 `elementFromPoint` 命中的是空白、透明遮罩或别的节点。探出期间改用几何包含判断:导轨自身加宽后的矩形,加上所有被拉伸的 shell 矩形,指针落在其中任一处都算仍在面板上;真正离开这条带才进入 160ms 的收回宽限。 +- **历史行菜单与挂在它下面的子菜单算作面板。** 二级菜单由站点画在导轨之外:有的挂到 body,有的挂在行旁边的定位层里,多数还不带 `role`,既不在导轨子树内,也命中不了弹层选择器,于是从行上滑进菜单就被当成离开面板,按下 160ms 宽限收回。现在探出会认领指针从面板直接走进的那层脱离文档流的壳:只接受处于 `absolute` / `fixed` / `sticky` 或自带弹层语义、且不包含导轨的外层(页面的应用外壳在文档流里,不在其列),连同它下面挂的子菜单一起算作面板。从导轨进入第一层菜单仍要求在指针最后一次停在面板上之后的 **500ms** 内(按住不动再滑过去时,移动本身会刷新这个时间);一旦进入已认领的菜单,它再弹出的子菜单只按「从哪离开」判定,不再受停顿时长限制,跨过两框之间几像素空隙时用离开菜单的时刻续上这段交接。页面自己原有的弹层不认领,被站点销毁的层也随之失效,因此不会把页面上顺手打开的菜单粘在探出上。从认领层离开同样算「离开面板」,照旧走 160ms 宽限。 - **导航后立刻退场。** 点击探出面板里的历史条目会由站点自己换路由并重建导航,此时再点一次原生折叠按钮,会命中新路由下的另一个控件,并与页面自己的过渡抢时序,表现就是收回极慢。探出在点击捕获阶段就撤销,且记录「打开时按下的是哪个原生控件」,路由或文档变化后不再按下它;`popstate` / `hashchange`、导轨被替换、`location.href` 与打开时不一致,都走同一条无动画退场路径。 - **状态以站点为准。** 站点自己展开侧栏、节点被替换、或者按下原生开关时,探出属性立即撤销;在原生开关上按 Enter / 空格、Esc、在侧栏外按下指针也会立即收回。触屏与手写笔指针不触发。 - **其余平台默认关闭。** 只有 PLATFORMS 中声明了 sidebar 的平台启用,未声明的平台不注册任何监听。豆包与元宝用 transform 把侧栏整体移出容器,千问折叠后导航节点直接消失,纯 CSS 加宽不可行;Grok 与 Poe 走站点自己的开合控件。 @@ -471,6 +472,10 @@ pointerdown → mousedown → pointerup → mouseup → click 凡是涉及改写平台原生结构的操作(代码折叠、交接流程、发送按钮定位、消息回显胶囊)都遵循同一原则:**无法可靠识别目标时不做修改,保持原生行为,并通过状态提示告知用户**。交接流程额外保证:任何一步失败都把当前进度写入剪贴板,允许手动接续。 +### 版本号单一来源 + +面板标题栏的版本号不再向用户脚本管理器索取。脚本以 `@grant none` 运行,页面上没有 `GM_info` 之类的接口,因此旧写法恒定落到 `0.0.0`。打包时 `tools/build-lib.ts` 用 esbuild 的 `define` 把 `__SCRIPT_VERSION__` 替换成 `meta.ts` 里的 `version`,与头部 `@version` 同源,产物里只留一个数字;测试未打包地运行同一份源码,由 `vitest.config.ts` 的 `define` 提供占位值,`src/build-constants.d.ts` 只声明这个标识符,不携带数字。 + ### 平台扩展 在 `PLATFORMS` 中新增一条平台定义即可接入新平台。`hosts` 与 `hostPaths` 同时驱动用户脚本头部的 `@match` 和运行时识别,不需要再改 `detectPlatform()`;消息根、代码卡片与动效差异用静态能力字段声明,识别后的分支只读这些字段,不比较平台名字。 @@ -519,6 +524,15 @@ pointerdown → mousedown → pointerup → mouseup → click ## 版本记录 +### 0.23.18 + +**修好悬停探出在历史记录二级菜单上误收回、设置面板版本号恒为 0.0.0,以及元宝 `Shift + Enter` 换行后输入标点会重复一次的问题。** + +- **二级菜单不再被判成离开面板。** 一级菜单被认领后,指针从它进入下一级子菜单时,交接依据从「最后一次停在面板上的时间」改为「刚离开的是哪一层」:只要上一刻还在已认领的菜单里,它弹出的子菜单(包括挂在 body 下的独立 portal,以及两框之间几像素的空隙)都算面板,停多久都不会因此收回。 +- **版本号与头部同源。** 面板不再向用户脚本管理器读版本:脚本以 `@grant none` 运行,页面上没有 `GM_info`,旧写法恒落到 `0.0.0`。打包时用 esbuild 的 `define` 把 `__SCRIPT_VERSION__` 换成 `meta.ts` 的 `version`,与 `@version` 同源;测试未打包运行,由 `vitest.config.ts` 提供占位值。 +- **`Shift + Enter` 的段落插入不再当成发送。** 元宝的 `beforeinput` 不带修饰键,旧的第二道网把所有 `insertParagraph` 都当成裸 `Enter`,于是软换行被 `preventDefault()` 取消,而 Quill 已经按换行更新了内部模型,选区与文档错位,随后输入的第一个标点被插入两次。现在在 `keydown` 阶段记住输入框内的 `Shift + Enter`,它产生的段落插入在 **200ms** 内直接放行;绕过 `keydown` 的裸 `Enter` 仍按原逻辑发送。 +- **测试覆盖。** 新增「菜单停驻超过交接窗口后进入子菜单」「跨空隙进入子菜单」两条探出用例,与两条 `Shift + Enter` 后 `insertParagraph` 的放行 / 窗口过期后仍发送用例;原有探出、发送、版本号与构建用例全部保持通过。 + ### 0.23.17 **修好元宝上直接粘贴图片没反应的问题:带文件的剪贴板被当成纯文本接管,附件因此凭空消失。** diff --git a/scripts/ai-chat-turbo-engine/meta.ts b/scripts/ai-chat-turbo-engine/meta.ts index a304ef1..d3cfab7 100644 --- a/scripts/ai-chat-turbo-engine/meta.ts +++ b/scripts/ai-chat-turbo-engine/meta.ts @@ -4,7 +4,7 @@ import { PLATFORM_MATCH_PATTERNS } from "./src/config"; const meta = { name: "AI Chat Turbo Engine", namespace: "https://cyojkoy.github.io/Payment/", - version: "0.23.17", + version: "0.23.18", description: "跨平台 AI 对话加速:常驻统计 + 完整消息提取 + YAML 交接 + 多平台适配 + 长代码折叠 + 自适应脱水 + 推理强度记忆 + 元宝原子工具记忆 + 新对话快捷键覆盖", author: "Yoko", updateURL: "https://cdn.jsdelivr.net/gh/CYoJkoY/Yoko-ScriptCat-Scripts@release/ai-chat-turbo-engine.user.js",