From c751df3ea1625d437a780d58c15a4905e58af152 Mon Sep 17 00:00:00 2001 From: Yoko Date: Tue, 1 Dec 2026 20:48:38 +0800 Subject: [PATCH] fix(ai-chat-turbo-engine): keep the Yuanbao composer native and the preview scrollable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Yuanbao composer is a Quill `ql-editor`, and the engine's writes left it in a state where Backspace and Shift+Enter acted on the wrong block. A clear or a fallback write went through `insertHTML` with one `white-space: pre-wrap` div, but Quill keeps one block per line: the DOM and its blot index no longer matched, so the next Backspace swallowed a whole blank line and Shift+Enter broke above the line the caret was on. The write also left the select-all range in place for a host that ignored the commands, which put the same two keys at the top of the document. The write path now clears through `delete`, hands a paragraph editor `

` markup, and collapses the caret into the last block. Paste in the Yuanbao composer is reduced to the `text/plain` flavour, because a page copy arrives as `insertFromPasteAsQuotation` and Quill renders it as a 引用 block; a paste above the virtual-file threshold still becomes a file. The text preview's `pre` is excluded from the code-fold scan, so a long file scrolls inside the dialog instead of being clamped to the preview height. --- scripts/ai-chat-turbo-engine/src/config.ts | 22 +++ .../ai-chat-turbo-engine/src/core/composer.ts | 150 +++++++++++++++--- scripts/ai-chat-turbo-engine/src/lifecycle.ts | 1 + .../src/ui/code-blocks.ts | 6 + .../src/ui/virtual-files.ts | 145 +++++++++++++++-- tests/ai-chat-turbo-code-blocks.test.ts | 147 +++++++++++++++++ tests/ai-chat-turbo-composer.test.ts | 87 +++++++++- tests/ai-chat-turbo-virtual-files.test.ts | 131 ++++++++++++++- 8 files changed, 644 insertions(+), 45 deletions(-) create mode 100644 tests/ai-chat-turbo-code-blocks.test.ts diff --git a/scripts/ai-chat-turbo-engine/src/config.ts b/scripts/ai-chat-turbo-engine/src/config.ts index 81254eb..e44803f 100644 --- a/scripts/ai-chat-turbo-engine/src/config.ts +++ b/scripts/ai-chat-turbo-engine/src/config.ts @@ -1,5 +1,13 @@ export const HUD_ID = "ai-turbo-extreme-hud"; export const STYLE_ID = "ai-turbo-engine-styles"; +/** + * Roots of the engine's own UI. Their subtrees hold the engine's rendering, + * never a site message, so document-wide scans skip them. The text preview is + * one of them: it paints a payload inside a `pre`, and a code scan that treats + * that `pre` as a site code block folds it to a preview height, which leaves a + * long file unscrollable. + */ +export const ENGINE_UI_SELECTOR = `#${HUD_ID}, #ai-turbo-vf-tray, #ai-turbo-vf-preview-modal, .ai-turbo-modal-backdrop, .ai-turbo-text-preview`; export const CODE_COLLAPSE_HEIGHT = 300; export const CODE_PREVIEW_HEIGHT = 200; export const DEFAULT_MESSAGE_LIMIT = 60; @@ -308,6 +316,13 @@ export interface PlatformDefinition { * line break. Left unset on sites whose own Enter already sends. */ readonly enterToSend?: boolean; + /** + * The host's editor keeps the clipboard's HTML flavour, so text copied from + * the page pastes as a quote block (or with the source's bold/links). When + * set, a paste in the composer is reduced to its plain-text flavour before + * the host sees it. Left unset on hosts whose paste is already plain. + */ + readonly pastePlainText?: boolean; /** * Single-message character cap enforced by the composer. `null` when the * host does not declare or need a hard cap. The engine uses this only to @@ -1009,6 +1024,13 @@ export const PLATFORMS = { * send intent and keep `Shift+Enter` for line breaks. */ enterToSend: true, + /* + * Copying text out of a Yuanbao answer and pasting it back arrives as + * `insertFromPasteAsQuotation` and Quill renders it as a 引用 block, and a + * copy that carries markup pastes bold/link formats the user did not ask + * for. The composer therefore always receives the plain-text flavour. + */ + pastePlainText: true, // Measured on the live composer: a 50,000-character `insertText` stayed, // while 50,001 characters was rejected as over the input limit. composerTextLimit: 50000, diff --git a/scripts/ai-chat-turbo-engine/src/core/composer.ts b/scripts/ai-chat-turbo-engine/src/core/composer.ts index b89c221..bdf1cc7 100644 --- a/scripts/ai-chat-turbo-engine/src/core/composer.ts +++ b/scripts/ai-chat-turbo-engine/src/core/composer.ts @@ -37,6 +37,13 @@ export interface TextBounds { */ export const DECLARED_CONTROL_MAX_DEPTH = 10; +/** + * Editors that keep one block element per line, with a `


` standing + * for a blank one. Yuanbao's composer is a Quill `ql-editor` (wrapped in + * `rich-textarea`), and Gemini uses the same widget. + */ +const PARAGRAPH_EDITOR_SELECTOR = ".ql-editor, rich-textarea"; + /** Ancestor steps from `input` up to the closest ancestor also holding * `control`; `Infinity` when the two only meet at the body or document. */ export function sharedAncestorDepth( @@ -594,26 +601,27 @@ export function createComposerUtils(deps: ComposerDeps): ComposerUtils { } inputElement.focus(); + selectComposerContent(inputElement); - // 用 Range 选中整个编辑器内容(比 execCommand("selectAll") 更可靠) - try { - const range = document.createRange(); - range.selectNodeContents(inputElement); - const sel = window.getSelection(); - sel?.removeAllRanges(); - sel?.addRange(range); - } catch (error: unknown) { - reportRecoverableError("select composer text", error); + const hasExecCommand = typeof document.execCommand === "function"; + const expectedSignature = text.replace(/\s|\u200b/g, ""); + let inserted = false; + + /* + * Clearing goes through `delete`, not an empty `insertText`: the delete + * command is the one Quill handles itself, so it rebuilds its own single + * empty paragraph and keeps its blot index in step with the DOM. That + * index is what the next Backspace and Shift+Enter act on. + */ + if (!text && hasExecCommand) { try { - document.execCommand("selectAll"); - } catch (fallbackError: unknown) { - reportRecoverableError("select composer text fallback", fallbackError); + inserted = document.execCommand("delete"); + } catch (error: unknown) { + reportRecoverableError("clear composer text", error); } } - const hasExecCommand = typeof document.execCommand === "function"; - let inserted = false; - if (hasExecCommand) { + if (!inserted && hasExecCommand) { try { inserted = document.execCommand("insertText", false, text); } catch (error: unknown) { @@ -622,12 +630,14 @@ export function createComposerUtils(deps: ComposerDeps): ComposerUtils { } const insertedText = readComposerContent(inputElement); - const expectedSignature = text.replace(/\s|\u200b/g, ""); if (!inserted || insertedText.replace(/\s|\u200b/g, "") !== expectedSignature) { if (hasExecCommand) { - const singleContainer = `
${escapeHtml(text)}
`; try { - inserted = document.execCommand("insertHTML", false, singleContainer); + inserted = document.execCommand( + "insertHTML", + false, + composerMarkup(inputElement, text), + ); } catch (error: unknown) { reportRecoverableError("insert composer HTML", error); } @@ -639,13 +649,18 @@ export function createComposerUtils(deps: ComposerDeps): ComposerUtils { !inserted || htmlText.replace(/\s|\u200b/g, "") !== expectedSignature ) { - inputElement.replaceChildren(); - const block = document.createElement("div"); - block.style.whiteSpace = "pre-wrap"; - block.textContent = text; - inputElement.append(block); + writeComposerDom(inputElement, text); } + /* + * Leave the caret collapsed at the end of what was written. The selection + * above spans the whole editor, and a host that ignored the commands keeps + * that span as its own range: the next Shift+Enter then breaks at the top + * of the document (a newline above the line the user is on) and the next + * Backspace deletes the leading block instead of one character. + */ + placeCaretAtEnd(inputElement); + // 派发 input 事件;如果 execCommand 成功,ProseMirror 通常已经派发过, // 这里补派一次保证 React 侧同步(幂等)。 inputElement.dispatchEvent( @@ -660,6 +675,95 @@ export function createComposerUtils(deps: ComposerDeps): ComposerUtils { inputElement.dispatchEvent(new Event("change", { bubbles: true })); } + /** Select the whole editor so a write replaces its previous content. */ + function selectComposerContent(inputElement: HTMLElement): void { + // 用 Range 选中整个编辑器内容(比 execCommand("selectAll") 更可靠) + try { + const range = document.createRange(); + range.selectNodeContents(inputElement); + const sel = window.getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); + } catch (error: unknown) { + reportRecoverableError("select composer text", error); + try { + document.execCommand("selectAll"); + } catch (fallbackError: unknown) { + reportRecoverableError("select composer text fallback", fallbackError); + } + } + } + + /** + * Markup for the `insertHTML` fallback, in the shape the host renders. + * + * A paragraph editor maps `

` back to its own blots through its paste + * pipeline, so the markup handed to the command already has the shape it + * paints. A single `white-space: pre-wrap` div instead leaves one plain text + * node holding raw newlines, and the editor's line model no longer matches + * its DOM: a later Backspace then swallows a whole blank line and a later + * Shift+Enter breaks above the line the caret is on. + */ + function composerMarkup(inputElement: HTMLElement, text: string): string { + if (!inputElement.closest(PARAGRAPH_EDITOR_SELECTOR)) { + return `

${escapeHtml(text)}
`; + } + if (!text) return "


"; + return text + .split("\n") + .map((line) => (line ? `

${escapeHtml(line)}

` : "


")) + .join(""); + } + + /** + * Fallback write for a host that refused every command. + * + * A paragraph editor gets one block per line, blank lines as `


`, + * because that is the shape its own line model describes. + */ + function writeComposerDom(inputElement: HTMLElement, text: string): void { + inputElement.replaceChildren(); + + if (!inputElement.closest(PARAGRAPH_EDITOR_SELECTOR)) { + const block = document.createElement("div"); + block.style.whiteSpace = "pre-wrap"; + block.textContent = text; + inputElement.append(block); + return; + } + + for (const line of text.split("\n")) { + const paragraph = document.createElement("p"); + if (line) { + paragraph.textContent = line; + } else { + paragraph.append(document.createElement("br")); + } + inputElement.append(paragraph); + } + } + + /** + * Collapse the selection to the end of the editor's content. The caret is + * placed inside the last block rather than on the editor node itself, because + * a paragraph editor maps the block-level position to its own blot offsets + * and a position on the container maps to nothing. + */ + function placeCaretAtEnd(inputElement: HTMLElement): void { + try { + const range = document.createRange(); + const lastBlock = inputElement.lastElementChild; + if (lastBlock) range.selectNodeContents(lastBlock); + else range.selectNodeContents(inputElement); + range.collapse(false); + const sel = window.getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); + } catch (error: unknown) { + reportRecoverableError("place composer caret", error); + } + } + function readComposerContent(input: HTMLElement): string { return ( (typeof input.innerText === "string" && input.innerText) || diff --git a/scripts/ai-chat-turbo-engine/src/lifecycle.ts b/scripts/ai-chat-turbo-engine/src/lifecycle.ts index c749151..13cd6f6 100644 --- a/scripts/ai-chat-turbo-engine/src/lifecycle.ts +++ b/scripts/ai-chat-turbo-engine/src/lifecycle.ts @@ -261,6 +261,7 @@ export function initializeEngine(): void { withSelfMutation, composer, state, + currentPlatform, isEngineDormant, composerTextLimit: currentPlatform.composerTextLimit ?? null, updateHudDashboard: () => hud?.updateHudDashboard(), diff --git a/scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts b/scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts index b6ea444..8b7c9cc 100644 --- a/scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts +++ b/scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts @@ -4,6 +4,7 @@ import { CHATGPT_CODE_HEADER_MARKER_SELECTOR, CODE_COLLAPSE_HEIGHT, CODE_PREVIEW_HEIGHT, + ENGINE_UI_SELECTOR, STREAMING_IDLE_DELAY, type PlatformDefinition, } from "../config"; @@ -124,6 +125,11 @@ export function createCodeBlockUtils(deps: CodeBlockDeps): CodeBlockUtils { /* Dehydrated turns stay unrendered; measuring them would force layout. */ if (candidate.closest(".ai-turbo-dehydrated")) return null; + /* Engine-owned UI renders the engine's own content. The text preview keeps + a pasted file inside a `pre`, and folding that `pre` to a preview height + would clamp the dialog's body: the reader could no longer scroll it. */ + if (candidate.closest(ENGINE_UI_SELECTOR)) return null; + const belongsToUserTurn = isInsideUserTurn(candidate); if ( diff --git a/scripts/ai-chat-turbo-engine/src/ui/virtual-files.ts b/scripts/ai-chat-turbo-engine/src/ui/virtual-files.ts index eb1898a..419cbed 100644 --- a/scripts/ai-chat-turbo-engine/src/ui/virtual-files.ts +++ b/scripts/ai-chat-turbo-engine/src/ui/virtual-files.ts @@ -1,4 +1,5 @@ import { COMPOSER_VISUAL_MAX_DEPTH, VIRTUAL_FILE_THRESHOLD } from "../config"; +import type { PlatformDefinition } from "../config"; import type { ComposerUtils } from "../core/composer"; import { reportRecoverableError } from "../core/diagnostics"; import { @@ -26,6 +27,7 @@ export interface VirtualFileDeps { withSelfMutation: (task: () => T) => T; composer: ComposerUtils; state: EngineState; + currentPlatform: PlatformDefinition; isEngineDormant: () => boolean; composerTextLimit: number | null; updateHudDashboard: () => void; @@ -101,6 +103,7 @@ export function createVirtualFileUtils( withSelfMutation, composer, state, + currentPlatform, isEngineDormant, updateHudDashboard, suspendObservers, @@ -871,30 +874,131 @@ export function createVirtualFileUtils( function handlePasteIntercept(event: ClipboardEvent): void { if (isEngineDormant()) return; - if (!state.virtualFileEnabled) return; - const target = event.target; - if ( - !(target instanceof Element) || - !target.closest(COMPOSER_EDITABLE_SELECTOR) - ) { - return; - } + const editable = resolveComposerEditable(event.target); + if (!editable) return; const clipData = event.clipboardData || readLegacyClipboardData(); if (!clipData) return; const pastedText = clipData.getData("text/plain"); - if (!pastedText || pastedText.length < VIRTUAL_FILE_THRESHOLD) { + + if ( + state.virtualFileEnabled && + pastedText && + pastedText.length >= VIRTUAL_FILE_THRESHOLD + ) { + event.preventDefault(); + event.stopImmediatePropagation(); + + acceptPastedText(pastedText); return; } + if (currentPlatform.pastePlainText !== true) return; + // An image or file paste carries no text of its own: the host keeps it. + if (!pastedText) return; + event.preventDefault(); event.stopImmediatePropagation(); - acceptPastedText(pastedText); + insertPlainTextAtCaret(editable, pastedText); } + /** + * The editable root a paste lands in. The event target is often an inner + * block (`

` inside `.ql-editor`), and insertion has to work from the + * editor root: a selection inside a sibling block would fail a containment + * check against that inner block and drop the text. + */ + function resolveComposerEditable(node: EventTarget | null): HTMLElement | null { + if (!(node instanceof Element)) return null; + const editable = node.closest(COMPOSER_EDITABLE_SELECTOR); + return editable instanceof HTMLElement ? editable : null; + } + + /** + * Insert the pasted text at the caret, so the host never reads the + * clipboard's HTML flavour. Yuanbao's Quill turns a page copy into an + * `insertFromPasteAsQuotation` command (a 引用 block) and keeps markup such + * as bold or links, neither of which the user copied on purpose. + * + * `insertText` is preferred because the host's own input handler sees it and + * keeps its document model in step; the range insertion is only the fallback + * for a document that has no command support. + */ + function insertPlainTextAtCaret(editable: HTMLElement, text: string): void { + if (!editable.isConnected) return; + + if ( + editable instanceof HTMLTextAreaElement || + editable instanceof HTMLInputElement + ) { + const start = editable.selectionStart ?? editable.value.length; + const end = editable.selectionEnd ?? start; + editable.setRangeText(text, start, end, "end"); + editable.dispatchEvent( + new InputEvent("input", { + bubbles: true, + inputType: "insertFromPaste", + data: text, + }), + ); + return; + } + + /* + * The selection belongs to the host's model, not to this handler: it can sit + * in a sibling block, or nowhere at all right after a re-render. Appending + * at the end of the editor is the fallback — the paste was already + * prevented, so dropping the text would lose what the user copied. + * + * The caret is read before `focus()`: focusing an unfocused editor moves + * the caret to the start of its content, and the text would land there. + */ + const selection = window.getSelection(); + const liveRange = + selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null; + const insertionRange = + liveRange && editable.contains(liveRange.startContainer) + ? liveRange + : null; + + editable.focus(); + + if (typeof document.execCommand === "function") { + try { + if (document.execCommand("insertText", false, text)) return; + } catch (error: unknown) { + reportRecoverableError("paste composer text", error); + } + } + + let range: Range; + if (insertionRange) { + range = insertionRange; + } else { + range = document.createRange(); + range.selectNodeContents(editable); + range.collapse(false); + } + + range.deleteContents(); + const node = document.createTextNode(text); + range.insertNode(node); + range.setStartAfter(node); + range.collapse(true); + selection?.removeAllRanges(); + selection?.addRange(range); + + editable.dispatchEvent( + new InputEvent("input", { + bubbles: true, + inputType: "insertFromPaste", + data: text, + }), + ); + } /** * Second net for a paste that already reached the editor as an `input` * command. The `paste` handler is registered at document-start and normally @@ -905,24 +1009,31 @@ export function createVirtualFileUtils( */ function handleBeforeInputPaste(event: InputEvent): void { if (isEngineDormant()) return; - if (!state.virtualFileEnabled) return; if (!PASTE_INPUT_TYPES.has(event.inputType)) return; - const target = event.target; + const editable = resolveComposerEditable(event.target); + if (!editable) return; + + const pastedText = readInputEventText(event); + if ( - !(target instanceof Element) || - !target.closest(COMPOSER_EDITABLE_SELECTOR) + state.virtualFileEnabled && + pastedText.length >= VIRTUAL_FILE_THRESHOLD ) { + event.preventDefault(); + event.stopImmediatePropagation(); + + acceptPastedText(pastedText); return; } - const pastedText = readInputEventText(event); - if (pastedText.length < VIRTUAL_FILE_THRESHOLD) return; + if (currentPlatform.pastePlainText !== true) return; + if (!pastedText) return; event.preventDefault(); event.stopImmediatePropagation(); - acceptPastedText(pastedText); + insertPlainTextAtCaret(editable, pastedText); } /** diff --git a/tests/ai-chat-turbo-code-blocks.test.ts b/tests/ai-chat-turbo-code-blocks.test.ts new file mode 100644 index 0000000..a0bb3ab --- /dev/null +++ b/tests/ai-chat-turbo-code-blocks.test.ts @@ -0,0 +1,147 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from "vitest"; +import { PLATFORMS } from "../scripts/ai-chat-turbo-engine/src/config"; +import { createEngineState } from "../scripts/ai-chat-turbo-engine/src/state"; +import { + createCodeBlockUtils, + type CodeBlockUtils, + type ElementFactory, +} from "../scripts/ai-chat-turbo-engine/src/ui/code-blocks"; +import { TEXT_PREVIEW_MODAL_ID } from "../scripts/ai-chat-turbo-engine/src/ui/text-preview"; + +function createTestElement( + tag: Tag, + attrs: Readonly> = {}, + children: readonly (string | Node)[] = [], +): HTMLElementTagNameMap[Tag] { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(attrs)) { + if (typeof value === "function") node.addEventListener(key, value); + else if (key === "className") node.className = value; + else if (key === "style") node.style.cssText = value; + else node.setAttribute(key, value); + } + for (const child of children) node.append(child); + return node; +} + +const el: ElementFactory = createTestElement; + +function filterOutNested(elements: readonly Element[]): Element[] { + return elements.filter( + (element) => + !elements.some( + (other) => other !== element && other.contains(element), + ), + ); +} + +function createCodeBlocks(): CodeBlockUtils { + const state = createEngineState(); + // The fold only runs while code collapsing is enabled; it is the default + // user setting, and the scan is a no-op without it. + state.collapseCode = true; + + return createCodeBlockUtils({ + currentPlatform: PLATFORMS.yuanbao, + state, + el, + withSelfMutation: (task) => task(), + filterOutNested, + isGeminiThoughtElement: () => false, + requestUpdate: vi.fn(), + }); +} + +/** The engine-owned dialog the 查看 action opens for a pasted file. */ +function mountTextPreviewModal(body: string): HTMLElement { + const backdrop = createTestElement("div", { + id: TEXT_PREVIEW_MODAL_ID, + className: "ai-turbo-modal-backdrop ai-turbo-text-preview", + }); + const pre = createTestElement("pre", { + className: "ai-turbo-text-preview-body", + tabindex: "0", + }); + pre.textContent = body; + // A file long enough that the fold would clamp it, the way a pasted file is. + stubCodeMeasurements(pre); + backdrop.append(pre); + document.body.append(backdrop); + return pre; +} + +/** Folding measures a block before it decides; jsdom reports zero sizes. */ +function stubCodeMeasurements(pre: HTMLElement): void { + for (const property of ["scrollHeight", "offsetHeight", "clientHeight"] as const) { + Object.defineProperty(pre, property, { configurable: true, value: 420 }); + } +} + +/** One site answer carrying a fenced code block, the ordinary fold target. */function mountSiteTurn(): { turn: HTMLElement; pre: HTMLElement } { + const turn = createTestElement("div", { + className: "agent-chat__list__item--ai", + }); + const pre = createTestElement("pre"); + const code = createTestElement("code"); + code.textContent = Array.from({ length: 40 }, (_, index) => `line ${index}`).join( + "\n", + ); + pre.append(code); + turn.append(pre); + document.body.append(turn); + return { turn, pre }; +} + +afterEach(() => { + document.body.replaceChildren(); + vi.restoreAllMocks(); +}); + +describe("code folding targets", () => { + it("folds a site code block but never the engine's own text preview", () => { + // The dialog renders the pasted file inside a `pre`, and the scan looks + // for `pre` anywhere in the document. Folding it clamps the dialog body to + // the preview height, so a long file can no longer be scrolled. + const previewPre = mountTextPreviewModal( + Array.from({ length: 60 }, (_, index) => `row ${index}`).join("\n"), + ); + const site = mountSiteTurn(); + stubCodeMeasurements(site.pre); + const codeBlocks = createCodeBlocks(); + + codeBlocks.requestCodeScan(); + codeBlocks.flushCodeBlockScan(); + + expect(site.pre.classList.contains("ai-turbo-code-target")).toBe(true); + expect(site.turn.querySelector(".ai-turbo-code-bar")).not.toBeNull(); + + expect(previewPre.classList.contains("ai-turbo-code-target")).toBe(false); + expect(previewPre.style.maxHeight).toBe(""); + expect( + document.getElementById(TEXT_PREVIEW_MODAL_ID)?.querySelector( + ".ai-turbo-code-bar", + ), + ).toBeNull(); + }); + + it("never marks or bars the preview body during a turn scan", () => { + const previewPre = mountTextPreviewModal( + Array.from({ length: 60 }, (_, index) => `row ${index}`).join("\n"), + ); + const site = mountSiteTurn(); + stubCodeMeasurements(site.pre); + const codeBlocks = createCodeBlocks(); + + codeBlocks.requestCodeScanForTurn(site.turn); + codeBlocks.flushCodeBlockScan(); + + expect(previewPre.classList.contains("ai-turbo-code-target")).toBe(false); + expect(previewPre.style.maxHeight).toBe(""); + expect( + document.getElementById(TEXT_PREVIEW_MODAL_ID)?.querySelector( + ".ai-turbo-code-bar", + ), + ).toBeNull(); + }); +}); diff --git a/tests/ai-chat-turbo-composer.test.ts b/tests/ai-chat-turbo-composer.test.ts index a1e1474..2ade574 100644 --- a/tests/ai-chat-turbo-composer.test.ts +++ b/tests/ai-chat-turbo-composer.test.ts @@ -110,7 +110,11 @@ describe("send control lookup", () => { }); describe("atomic text insertion", () => { - it("replaces the whole editable with the requested text", () => { + it("writes one paragraph per line into a paragraph editor", () => { + // Quill (Yuanbao's `ql-editor`) describes its document as one block per + // line. A single `white-space: pre-wrap` div instead leaves the editor's + // line model contradicting its DOM, which misplaces the next Shift+Enter + // break and lets the next Backspace delete a whole blank line. const editor = createEditor(); document.body.append(editor); const composer = createComposerUtils({ @@ -119,7 +123,86 @@ describe("atomic text insertion", () => { composer.insertTextAtomic(editor, "第一段\n第二段"); - expect(editor.textContent).toBe("第一段\n第二段"); + const paragraphs = Array.from(editor.children); + expect(paragraphs.map((node) => node.tagName)).toEqual(["P", "P"]); + expect(paragraphs.map((node) => node.textContent)).toEqual([ + "第一段", + "第二段", + ]); + }); + + it("keeps a blank line as the editor's own empty paragraph", () => { + const editor = createEditor(); + document.body.append(editor); + const composer = createComposerUtils({ + currentPlatform: PLATFORMS.yuanbao, + }); + + composer.insertTextAtomic(editor, "第一段\n\n第三段"); + + const paragraphs = Array.from(editor.children); + expect(paragraphs).toHaveLength(3); + expect(paragraphs[1].innerHTML).toBe("
"); + }); + + it("clears a paragraph editor to a single empty paragraph", () => { + const editor = createEditor(); + document.body.append(editor); + const composer = createComposerUtils({ + currentPlatform: PLATFORMS.yuanbao, + }); + + composer.insertTextAtomic(editor, ""); + + expect(editor.children).toHaveLength(1); + expect(editor.firstElementChild?.tagName).toBe("P"); + expect(editor.textContent).toBe(""); + }); + + it("offers a paragraph editor paragraph markup, never raw newlines", () => { + // Chrome's `insertHTML` runs through the host's own paste pipeline, so the + // markup decides the blots the editor ends up with. Paragraphs map back to + // paragraphs; a pre-wrap div with embedded newline characters would not. + const editor = createEditor(); + document.body.append(editor); + const commands: string[] = []; + Object.defineProperty(document, "execCommand", { + configurable: true, + value: (command: string, _show: boolean, value?: string) => { + commands.push(`${command}:${value ?? ""}`); + return false; + }, + }); + + try { + const composer = createComposerUtils({ + currentPlatform: PLATFORMS.yuanbao, + }); + composer.insertTextAtomic(editor, "第一段\n\n第三段"); + } finally { + Reflect.deleteProperty(document, "execCommand"); + } + + const insertHtml = commands.find((call) => call.startsWith("insertHTML:")); + expect(insertHtml).toBe("insertHTML:

第一段


第三段

"); + }); + + it("collapses the caret to the end instead of leaving it selecting everything", () => { + // A host that ignores the commands keeps the applier's select-all range; + // its next Shift+Enter then breaks at the top of the document and the next + // Backspace deletes the leading block. + const editor = createEditor(); + document.body.append(editor); + const composer = createComposerUtils({ + currentPlatform: PLATFORMS.yuanbao, + }); + + composer.insertTextAtomic(editor, "第一段\n第二段"); + + const selection = window.getSelection(); + expect(selection?.rangeCount).toBe(1); + expect(selection?.isCollapsed).toBe(true); + expect(selection?.anchorNode).toBe(editor.lastElementChild); }); it("recognizes a stop control and an ordinary send control", () => { diff --git a/tests/ai-chat-turbo-virtual-files.test.ts b/tests/ai-chat-turbo-virtual-files.test.ts index 889c0fb..2eec0e9 100644 --- a/tests/ai-chat-turbo-virtual-files.test.ts +++ b/tests/ai-chat-turbo-virtual-files.test.ts @@ -1,6 +1,7 @@ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { VIRTUAL_FILE_THRESHOLD } from "../scripts/ai-chat-turbo-engine/src/config"; +import { VIRTUAL_FILE_THRESHOLD, PLATFORMS } from "../scripts/ai-chat-turbo-engine/src/config"; +import type { PlatformDefinition } from "../scripts/ai-chat-turbo-engine/src/config"; import type { ComposerUtils } from "../scripts/ai-chat-turbo-engine/src/core/composer"; import { createEngineState } from "../scripts/ai-chat-turbo-engine/src/state"; import type { ElementFactory } from "../scripts/ai-chat-turbo-engine/src/ui/code-blocks"; @@ -41,7 +42,9 @@ interface VirtualFileFixture { swapComposer: () => HTMLTextAreaElement; } -function createFixture(): VirtualFileFixture { +function createFixture( + options: { platform?: PlatformDefinition } = {}, +): VirtualFileFixture { const container = document.createElement("div"); container.className = "composer"; let current = document.createElement("textarea"); @@ -72,13 +75,21 @@ function createFixture(): VirtualFileFixture { withSelfMutation: (task) => task(), composer, state, + currentPlatform: options.platform ?? PLATFORMS.chatgpt, isEngineDormant: () => false, composerTextLimit: 50000, updateHudDashboard: vi.fn(), suspendObservers: vi.fn(), }); - // Mirror the document-start capture listener the engine installs. + // Mirror the document-start capture listeners the engine installs. + container.addEventListener( + "paste", + (event) => { + files.handlePasteIntercept(event as ClipboardEvent); + }, + true, + ); container.addEventListener( "beforeinput", (event) => { @@ -445,6 +456,7 @@ describe("virtual file paste takeover", () => { const dormant = createVirtualFileUtils({ el, withSelfMutation: (task) => task(), + currentPlatform: PLATFORMS.chatgpt, composer: { getChatInput: () => textarea, findSendControl: () => null, @@ -539,3 +551,116 @@ describe("virtual file tray retirement", () => { expect(tray()).toBeNull(); }); }); + +describe("plain-text paste", () => { + /** A `paste` the way Chrome delivers it: both clipboard flavours. */ + function pasteEvent( + target: EventTarget, + flavours: Readonly>, + ): ClipboardEvent { + // jsdom ships no ClipboardEvent constructor, so the event is built from a + // plain Event and given the clipboard payload the handler reads. + const event = new Event("paste", { + bubbles: true, + cancelable: true, + }) as ClipboardEvent; + Object.defineProperty(event, "clipboardData", { + value: { getData: (type: string): string => flavours[type] ?? "" }, + }); + target.dispatchEvent(event); + return event; + } + + const PAGE_COPY = { + "text/plain": "引用的文字", + "text/html": "
引用的文字
", + }; + + it("drops the HTML flavour a page copy carries", () => { + // Yuanbao's Quill reads the HTML flavour, so a copy out of an answer came + // back as a 引用 block. The composer must only ever see the plain text. + fixture = createFixture({ platform: PLATFORMS.yuanbao }); + const editor = fixture.textarea; + editor.value = "前缀后缀"; + editor.setSelectionRange(2, 2); + + const event = pasteEvent(editor, PAGE_COPY); + + expect(event.defaultPrevented).toBe(true); + expect(editor.value).toBe("前缀引用的文字后缀"); + }); + + it("takes a paste that already reached the editor as a beforeinput command", () => { + fixture = createFixture({ platform: PLATFORMS.yuanbao }); + const editor = document.createElement("div"); + editor.setAttribute("contenteditable", "true"); + editor.textContent = "已有"; + // Inside the composer subtree, so the fixture's capture listener sees the + // command exactly where the engine's document-start listener would. + fixture.textarea.parentElement?.append(editor); + + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(editor); + range.collapse(false); + selection?.removeAllRanges(); + selection?.addRange(range); + + const event = beforeInputPaste("粘贴的文本", { + target: editor, + inputType: "insertFromPasteAsQuotation", + }); + + expect(event.defaultPrevented).toBe(true); + expect(editor.textContent).toBe("已有粘贴的文本"); + expect(editor.querySelector("blockquote")).toBeNull(); + }); + + it("keeps the pasted text when the caret sits in a sibling block", () => { + fixture = createFixture({ platform: PLATFORMS.yuanbao }); + const editor = document.createElement("div"); + editor.setAttribute("contenteditable", "true"); + const first = document.createElement("p"); + first.textContent = ""; + const second = document.createElement("p"); + second.textContent = "第二段"; + editor.append(first, second); + fixture.textarea.parentElement?.append(editor); + + // A host re-render can leave the selection in a block other than the one + // the paste targets. The text must still land instead of vanishing. + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(first); + range.collapse(false); + selection?.removeAllRanges(); + selection?.addRange(range); + const event = pasteEvent(first, { "text/plain": "粘贴" }); + + expect(event.defaultPrevented).toBe(true); + expect(editor.textContent).toBe("粘贴第二段"); + }); + + it("leaves the paste alone on a platform that did not opt in", () => { + const editor = fixture.textarea; + editor.value = ""; + + const event = pasteEvent(editor, PAGE_COPY); + + expect(event.defaultPrevented).toBe(false); + expect(editor.value).toBe(""); + }); + + it("still turns an over-threshold paste into a virtual file", () => { + fixture = createFixture({ platform: PLATFORMS.yuanbao }); + + const event = pasteEvent(fixture.textarea, { + "text/plain": LONG_TEXT, + "text/html": `

${LONG_TEXT}

`, + }); + + expect(event.defaultPrevented).toBe(true); + expect(fixture.files.activeFileCount()).toBe(1); + expect(fixture.textarea.value).toBe(""); + }); +});