Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions scripts/ai-chat-turbo-engine/src/config.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
150 changes: 127 additions & 23 deletions scripts/ai-chat-turbo-engine/src/core/composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ export interface TextBounds {
*/
export const DECLARED_CONTROL_MAX_DEPTH = 10;

/**
* Editors that keep one block element per line, with a `<p><br></p>` 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(
Expand Down Expand Up @@ -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) {
Expand All @@ -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 = `<div style="white-space:pre-wrap;">${escapeHtml(text)}</div>`;
try {
inserted = document.execCommand("insertHTML", false, singleContainer);
inserted = document.execCommand(
"insertHTML",
false,
composerMarkup(inputElement, text),
);
} catch (error: unknown) {
reportRecoverableError("insert composer HTML", error);
}
Expand All @@ -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(
Expand All @@ -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 `<p>` 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 `<div style="white-space:pre-wrap;">${escapeHtml(text)}</div>`;
}
if (!text) return "<p><br></p>";
return text
.split("\n")
.map((line) => (line ? `<p>${escapeHtml(line)}</p>` : "<p><br></p>"))
.join("");
}

/**
* Fallback write for a host that refused every command.
*
* A paragraph editor gets one block per line, blank lines as `<p><br></p>`,
* 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) ||
Expand Down
1 change: 1 addition & 0 deletions scripts/ai-chat-turbo-engine/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ export function initializeEngine(): void {
withSelfMutation,
composer,
state,
currentPlatform,
isEngineDormant,
composerTextLimit: currentPlatform.composerTextLimit ?? null,
updateHudDashboard: () => hud?.updateHudDashboard(),
Expand Down
6 changes: 6 additions & 0 deletions scripts/ai-chat-turbo-engine/src/ui/code-blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 (
Expand Down
Loading
Loading