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 `
` 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(line)}
` : "` 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 第一段 第三段 ${LONG_TEXT}
");
+ });
+
+ 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("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": `