Files
Netcatty/components/terminal/runtime/terminalUserPaste.ts
T
39e4e08d9c fix(terminal): skip paste residual EL on the alternate screen (#3776)
* fix(terminal): skip paste residual EL on the alternate screen

Vim often finishes a paste chunk with the cursor mid-line. Injecting
ESC[K there erases the rest of the row and is not redrawn. Clear the
pending flag so the cleanup cannot run after leaving the alt screen.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): skip paste EL after a same-batch alt-screen exit

Remember the pre-write alternate buffer so a paste echo and ESC[?1049l
in one chunk cannot inject ESC[K] into the restored normal screen.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-20 13:27:39 +08:00

574 lines
19 KiB
TypeScript

import type { Terminal as XTerm } from "@xterm/xterm";
import { sanitizeTerminalInput } from "./terminalInputSanitize";
type PasteTarget = Pick<XTerm, "paste" | "scrollToBottom"> &
Partial<Pick<XTerm, "cols" | "rows" | "write">> & {
modes?: { bracketedPasteMode?: boolean };
options?: { ignoreBracketedPasteMode?: boolean };
};
type PasteOptions = {
scrollOnPaste?: boolean;
requestAnimationFrame?: (callback: () => void) => unknown;
onPasteData?: (data: string, options?: { sensitive?: boolean }) => boolean | void;
/**
* Pre-computed sensitivity for this paste. When true, the terminal input
* handler must treat the pasted bytes as sensitive even if its live
* password-prompt ref was cleared while a confirmation dialog was open
* (the dialog await can outlive the prompt flag). The override only
* applies to the pasted data itself and is consumed as it arrives.
*/
sensitive?: boolean;
};
type BroadcastUserInputOptions = {
isBroadcastEnabled?: boolean;
hasBroadcastInputHandler?: boolean;
};
type PasteDisplayState = {
expiresAt: number;
clearPending: number;
pasteEchoFragments: string[];
inPasteEchoActiveRegion: boolean;
// Buffer type observed while preparing this chunk, before xterm applies it.
preparedOnAlternateScreen: boolean;
};
type PasteInputScrollState = {
expiresAt: number;
remainingDataVariants: string[];
};
type TerminalProtocolReplyState = {
expiresAt: number;
pendingCursorPositionReports: number;
cursorPositionReportFragment: string;
};
const pasteDisplayStates = new WeakMap<object, PasteDisplayState>();
const pasteInputScrollStates = new WeakMap<object, PasteInputScrollState>();
const pasteBroadcastStates = new WeakMap<object, PasteInputScrollState>();
const pasteSensitiveStates = new WeakMap<object, PasteInputScrollState>();
type LinePasteOptions = { lineDelayMs: number; sensitive: boolean; broadcast?: boolean };
type LinePasteHandler = (data: string, options: LinePasteOptions) => void;
const linePasteHandlers = new WeakMap<object, LinePasteHandler>();
/** Preserve pending input and local echo before scheduling delayed writes. */
export function registerTerminalLinePasteHandler(term: object, handler: LinePasteHandler): () => void {
linePasteHandlers.set(term, handler);
return () => {
if (linePasteHandlers.get(term) === handler) linePasteHandlers.delete(term);
};
}
export function dispatchTerminalLinePaste(term: object, data: string, options: LinePasteOptions): boolean {
const handler = linePasteHandlers.get(term);
if (!handler) return false;
handler(data, options);
return true;
}
const terminalProtocolReplyStates = new WeakMap<object, TerminalProtocolReplyState>();
const LONG_PASTE_MIN_LENGTH = 200;
const PASTE_DISPLAY_FIX_WINDOW_MS = 4000;
const PASTE_INPUT_SCROLL_WINDOW_MS = 4000;
const TERMINAL_PROTOCOL_REPLY_WINDOW_MS = 4000;
const READLINE_ACTIVE_REGION_START = "\x1b[7m";
const READLINE_ACTIVE_REGION_END = "\x1b[27m";
const BRACKETED_PASTE_START = "\x1b[200~";
const BRACKETED_PASTE_END = "\x1b[201~";
const MIN_PASTE_ECHO_FRAGMENT_LENGTH = 6;
const ESC = "\x1b";
const BEL = "\x07";
const getNow = () => Date.now();
const isStateActive = <T extends { expiresAt: number }>(state: T | undefined): state is T =>
!!state && state.expiresAt > getNow();
const stripReadlineActiveRegion = (data: string): string =>
data
.split(READLINE_ACTIVE_REGION_START)
.join("")
.split(READLINE_ACTIVE_REGION_END)
.join("");
const isCsiFinalByte = (char: string): boolean => {
const code = char.charCodeAt(0);
return code >= 0x40 && code <= 0x7e;
};
const stripAnsiEscapeSequences = (data: string): string => {
let plainText = "";
for (let index = 0; index < data.length; index += 1) {
const char = data[index];
if (char !== ESC) {
plainText += char;
continue;
}
const nextChar = data[index + 1];
if (nextChar === "[") {
index += 2;
while (index < data.length && !isCsiFinalByte(data[index])) {
index += 1;
}
continue;
}
if (nextChar === "]") {
index += 2;
while (index < data.length) {
if (data[index] === BEL) break;
if (data[index] === ESC && data[index + 1] === "\\") {
index += 1;
break;
}
index += 1;
}
continue;
}
if (nextChar) {
index += 1;
}
}
return plainText;
};
const stripNonLineBreakControls = (data: string): string => {
let plainText = "";
for (const char of data) {
const code = char.charCodeAt(0);
if (char === "\n" || (code >= 0x20 && code !== 0x7f)) {
plainText += char;
}
}
return plainText;
};
const getPlainTerminalText = (data: string): string =>
stripNonLineBreakControls(
stripAnsiEscapeSequences(data).replace(/\r\n/g, "\n").replace(/\r/g, "\n"),
);
type CursorPositionReportMatch =
| { type: "complete"; length: number }
| { type: "prefix" }
| { type: "none" };
const isAsciiDigit = (char: string): boolean => char >= "0" && char <= "9";
const matchCursorPositionReportFromStart = (data: string): CursorPositionReportMatch => {
if (!data.startsWith(ESC)) return { type: "none" };
if (data.length === 1) return { type: "prefix" };
if (data[1] !== "[") return { type: "none" };
if (data.length === 2) return { type: "prefix" };
let index = 2;
if (data[index] === "?") {
index += 1;
if (index === data.length) return { type: "prefix" };
}
let rowDigits = 0;
while (index < data.length && isAsciiDigit(data[index])) {
rowDigits += 1;
index += 1;
}
if (index === data.length) return { type: "prefix" };
if (rowDigits === 0 || data[index] !== ";") return { type: "none" };
index += 1;
let columnDigits = 0;
while (index < data.length && isAsciiDigit(data[index])) {
columnDigits += 1;
index += 1;
}
if (index === data.length) return { type: "prefix" };
if (columnDigits === 0 || data[index] !== "R") return { type: "none" };
return { type: "complete", length: index + 1 };
};
const getPasteEchoFragments = (text: string): string[] =>
Array.from(
new Set(
getPlainTerminalText(text)
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length >= MIN_PASTE_ECHO_FRAGMENT_LENGTH),
),
);
const preparePasteTextForXterm = (text: string): string => text.replace(/\r?\n/g, "\r");
const getPasteInputDataVariants = (text: string): string[] => {
const preparedText = preparePasteTextForXterm(text);
return Array.from(
new Set([
preparedText,
`${BRACKETED_PASTE_START}${preparedText}${BRACKETED_PASTE_END}`,
]),
).filter((candidate) => candidate.length > 0);
};
const getPasteInputData = (term: PasteTarget, text: string): string => {
const preparedText = preparePasteTextForXterm(text);
if (term.modes?.bracketedPasteMode && !term.options?.ignoreBracketedPasteMode) {
return `${BRACKETED_PASTE_START}${preparedText}${BRACKETED_PASTE_END}`;
}
return preparedText;
};
const isExpectedPasteEcho = (data: string, state: PasteDisplayState): boolean => {
if (state.pasteEchoFragments.length === 0) return false;
const candidateLines = getPlainTerminalText(stripReadlineActiveRegion(data))
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length >= MIN_PASTE_ECHO_FRAGMENT_LENGTH);
return candidateLines.some((line) =>
state.pasteEchoFragments.some((fragment) => fragment.includes(line) || line.includes(fragment)),
);
};
const stripMatchedReadlineActiveRegion = (
data: string,
state: PasteDisplayState,
): { data: string; matched: boolean } => {
let index = 0;
let matched = false;
let nextData = "";
while (index < data.length) {
if (state.inPasteEchoActiveRegion) {
const endIndex = data.indexOf(READLINE_ACTIVE_REGION_END, index);
if (endIndex === -1) {
nextData += data.slice(index);
matched = true;
break;
}
nextData += data.slice(index, endIndex);
index = endIndex + READLINE_ACTIVE_REGION_END.length;
state.inPasteEchoActiveRegion = false;
matched = true;
continue;
}
const startIndex = data.indexOf(READLINE_ACTIVE_REGION_START, index);
if (startIndex === -1) {
nextData += data.slice(index);
break;
}
nextData += data.slice(index, startIndex);
const contentStart = startIndex + READLINE_ACTIVE_REGION_START.length;
const endIndex = data.indexOf(READLINE_ACTIVE_REGION_END, contentStart);
if (endIndex === -1) {
const highlightedContent = data.slice(contentStart);
if (isExpectedPasteEcho(highlightedContent, state)) {
nextData += highlightedContent;
state.inPasteEchoActiveRegion = true;
matched = true;
} else {
nextData += data.slice(startIndex);
}
break;
}
const highlightedContent = data.slice(contentStart, endIndex);
if (isExpectedPasteEcho(highlightedContent, state)) {
nextData += highlightedContent;
matched = true;
} else {
nextData += data.slice(startIndex, endIndex + READLINE_ACTIVE_REGION_END.length);
}
index = endIndex + READLINE_ACTIVE_REGION_END.length;
}
return { data: nextData, matched };
};
const estimateRows = (text: string, cols: number): number => {
const width = Math.max(1, cols);
return text
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.split("\n")
.reduce((rows, line) => rows + Math.max(1, Math.ceil(line.length / width)), 0);
};
const shouldApplyPasteDisplayFix = (term: PasteTarget, text: string): boolean => {
if (text.length < LONG_PASTE_MIN_LENGTH) return false;
const lineCount = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").length;
const rows = typeof term.rows === "number" && term.rows > 0 ? term.rows : 24;
const cols = typeof term.cols === "number" && term.cols > 0 ? term.cols : 80;
return lineCount >= rows - 1 || estimateRows(text, cols) >= rows - 1;
};
export function pasteTextIntoTerminal(
term: PasteTarget,
text: string,
options: PasteOptions = {},
): void {
if (!text) return;
if (shouldApplyPasteDisplayFix(term, text)) {
pasteDisplayStates.set(term, {
expiresAt: getNow() + PASTE_DISPLAY_FIX_WINDOW_MS,
clearPending: 0,
pasteEchoFragments: getPasteEchoFragments(text),
inPasteEchoActiveRegion: false,
preparedOnAlternateScreen: false,
});
}
if (options.scrollOnPaste === false) {
pasteInputScrollStates.set(term, {
expiresAt: getNow() + PASTE_INPUT_SCROLL_WINDOW_MS,
remainingDataVariants: getPasteInputDataVariants(text),
});
} else {
pasteInputScrollStates.delete(term);
}
if (options.onPasteData) {
const pasteData = getPasteInputData(term, text);
// Forward the pre-dialog sensitivity snapshot (#3491): the broadcast
// callback re-reads the live password-prompt ref, which the confirm
// dialog await may have cleared, so the saved classification must ride
// along to keep the peer fan-out tagged sourceSensitive.
const didBroadcast = options.onPasteData(pasteData, {
sensitive: options.sensitive === true,
}) === true;
if (didBroadcast) {
pasteBroadcastStates.set(term, {
expiresAt: getNow() + PASTE_INPUT_SCROLL_WINDOW_MS,
remainingDataVariants: [pasteData],
});
} else {
pasteBroadcastStates.delete(term);
}
} else {
pasteBroadcastStates.delete(term);
}
// Carry the pre-dialog sensitivity snapshot through term.paste so the
// input handler writes / records this paste as sensitive even when the
// live password-prompt ref has been cleared while the confirm dialog was
// open. The state is consumed chunk-by-chunk like the scroll/broadcast
// states so it never leaks to later, unrelated input.
if (options.sensitive === true) {
// The input handler sanitizes chunk data (stripping zero-width /
// invisible characters such as U+200B or a BOM) before consulting this
// override, so the stored variants must be sanitized equivalently or a
// paste containing such characters would never match and could be
// broadcast / recorded as nonsensitive.
pasteSensitiveStates.set(term, {
expiresAt: getNow() + PASTE_INPUT_SCROLL_WINDOW_MS,
remainingDataVariants: getPasteInputDataVariants(sanitizeTerminalInput(text)),
});
} else {
pasteSensitiveStates.delete(term);
}
term.paste(text);
if (!options.scrollOnPaste) return;
term.scrollToBottom();
const scheduleFrame =
options.requestAnimationFrame ??
(typeof globalThis.requestAnimationFrame === "function"
? globalThis.requestAnimationFrame.bind(globalThis)
: undefined);
if (scheduleFrame) {
scheduleFrame(() => {
term.scrollToBottom();
});
}
}
export function shouldSuppressTerminalInputScrollForUserPaste(term: object, data: string): boolean {
return consumePasteInputState(pasteInputScrollStates, term, data);
}
export function shouldSuppressTerminalBroadcastForUserPaste(term: object, data: string): boolean {
return consumePasteInputState(pasteBroadcastStates, term, data);
}
/**
* True when the given input chunk belongs to a programmatic paste that was
* flagged sensitive before a confirm-dialog await (see PasteOptions.sensitive).
* Consumes the override state so it applies only to the flagged paste data.
*/
export function shouldOverrideTerminalUserPasteSensitivity(
term: object,
data: string,
): boolean {
return consumePasteInputState(pasteSensitiveStates, term, data);
}
export function markExpectedTerminalCursorPositionReport(term: object): void {
const currentState = terminalProtocolReplyStates.get(term);
const activeState = isStateActive(currentState)
? currentState
: {
expiresAt: 0,
pendingCursorPositionReports: 0,
cursorPositionReportFragment: "",
};
terminalProtocolReplyStates.set(term, {
expiresAt: getNow() + TERMINAL_PROTOCOL_REPLY_WINDOW_MS,
pendingCursorPositionReports: activeState.pendingCursorPositionReports + 1,
cursorPositionReportFragment: activeState.cursorPositionReportFragment,
});
}
function shouldSuppressTerminalProtocolReplyBroadcast(term: object, data: string): boolean {
const state = terminalProtocolReplyStates.get(term);
if (!isStateActive(state)) {
terminalProtocolReplyStates.delete(term);
return false;
}
if (state.pendingCursorPositionReports <= 0 || data.length === 0) {
return false;
}
let remainingData = `${state.cursorPositionReportFragment}${data}`;
let consumedCursorPositionReports = 0;
while (remainingData.length > 0) {
const match = matchCursorPositionReportFromStart(remainingData);
if (match.type === "none") {
state.cursorPositionReportFragment = "";
return false;
}
if (match.type === "prefix") {
if (consumedCursorPositionReports >= state.pendingCursorPositionReports) {
return false;
}
state.pendingCursorPositionReports -= consumedCursorPositionReports;
state.cursorPositionReportFragment = remainingData;
return true;
}
consumedCursorPositionReports += 1;
if (consumedCursorPositionReports > state.pendingCursorPositionReports) {
return false;
}
remainingData = remainingData.slice(match.length);
}
state.pendingCursorPositionReports -= consumedCursorPositionReports;
state.cursorPositionReportFragment = "";
if (state.pendingCursorPositionReports <= 0) {
terminalProtocolReplyStates.delete(term);
}
return true;
}
export function shouldBroadcastTerminalUserInput(
term: object,
data: string,
options: BroadcastUserInputOptions,
): boolean {
const isSuppressedUserPaste = shouldSuppressTerminalBroadcastForUserPaste(term, data);
const isSuppressedTerminalProtocolReply = shouldSuppressTerminalProtocolReplyBroadcast(term, data);
return (
!isSuppressedUserPaste &&
!isSuppressedTerminalProtocolReply &&
!!options.isBroadcastEnabled &&
!!options.hasBroadcastInputHandler
);
}
function consumePasteInputState(
states: WeakMap<object, PasteInputScrollState>,
term: object,
data: string,
): boolean {
const state = states.get(term);
if (!isStateActive(state)) {
states.delete(term);
return false;
}
const matchingIndex = state.remainingDataVariants.findIndex((candidate) => {
if (candidate === data) return true;
return candidate.startsWith(data);
});
if (matchingIndex === -1) return false;
const candidate = state.remainingDataVariants[matchingIndex];
if (candidate.length > data.length) {
state.remainingDataVariants[matchingIndex] = candidate.slice(data.length);
} else {
states.delete(term);
}
return true;
}
const isAlternateScreenBuffer = (term: object): boolean =>
(term as { buffer?: { active?: { type?: string } } }).buffer?.active?.type === "alternate";
export function prepareTerminalDataForUserPasteDisplay(term: object, data: string): string {
const state = pasteDisplayStates.get(term);
if (!isStateActive(state)) return data;
// Captured before term.write. The residual check runs in the write callback,
// after a same-batch ESC[?1049l has already restored the normal buffer.
state.preparedOnAlternateScreen = isAlternateScreenBuffer(term);
const strippedActiveRegion = stripMatchedReadlineActiveRegion(data, state);
if (strippedActiveRegion.matched) {
state.clearPending = Math.max(state.clearPending, 3);
return strippedActiveRegion.data;
}
const isPasteEcho = isExpectedPasteEcho(data, state);
if (isPasteEcho && (data.length > LONG_PASTE_MIN_LENGTH || data.includes("\r"))) {
state.clearPending = Math.max(state.clearPending, 1);
}
return data;
}
export function clearPasteResidualAfterTerminalWrite(term: object): string | null {
const state = pasteDisplayStates.get(term);
if (!isStateActive(state)) return null;
// Vim and other alternate-screen apps often end a paste chunk with the cursor
// mid-line. EL would erase the rest of that row, and the app may not redraw it (#3166).
// Drop the pending clear so it cannot fire after returning to the normal screen.
// preparedOnAlternateScreen covers a same-batch exit: buffer.active is already
// normal when this write callback runs.
if (state.preparedOnAlternateScreen || isAlternateScreenBuffer(term)) {
state.preparedOnAlternateScreen = false;
state.clearPending = 0;
return null;
}
if (state.clearPending <= 0) return null;
if (typeof (term as Partial<Pick<XTerm, "write">>).write !== "function") return null;
// Readline can leave stale cells to the right of the cursor after very long
// bracketed paste redraws; clear them locally without sending bytes upstream.
state.clearPending -= 1;
const cleanupData = "\x1b[K";
(term as Pick<XTerm, "write">).write(cleanupData);
return cleanupData;
}