Compare commits

...
Author SHA1 Message Date
Cursor Agentand陈大猫 c6b97954b4 fix(ai): keep the alt-screen guard after prompt-tail truncation
A full-screen app can scroll its enter sequence out of the 4096-byte
prompt tail. Remember the mode at the first kept byte and seed the
idle-prompt renderer with it, so painted PowerShell, cmd, and POSIX
prompts do not unlock ptyExec while that app is still running.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-25 14:32:18 +00:00
Cursor Agentand陈大猫 a9dd2bfd04 fix(mcp): send commands when a PowerShell prompt is only visible
PSReadLine echoes the pending-input clear prefix and erases those keys
with cursor-column and ED. stripAnsi drops the erase, so the raw tail
no longer ends with the cached prompt and terminal_execute waits until
SHELL_NOT_READY without writing. Readiness now also accepts the cursor
line when it is a recognized idle prompt.

Fixes #3927

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-25 14:21:01 +00:00
8 changed files with 349 additions and 8 deletions

No files matched your search

@@ -2,6 +2,18 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
const { startPtyJob } = require('./ptyExec.cjs');
const { getFreshIdlePrompt, getVisibleIdlePrompt, trackSessionIdlePrompt } = require('./shellUtils.cjs');
const { terminalCursorLine } = require('../terminalLogSanitizer.cjs');
function readyPrompt(session) {
return getFreshIdlePrompt(session) || getVisibleIdlePrompt(session);
}
// PSReadLine echoes the PowerShell clear-prefix keys, then erases them with
// cursor-column + ED without rewriting the prompt into the byte stream.
function powershellEraseRedraw(prompt) {
return `${prompt}ggd2147483647d\x1b[20G\x1b[0J`;
}
class TestPty extends EventEmitter {
writes = [];
@@ -158,3 +170,116 @@ test('wall deadline during authorization reports authorization failure rather th
assert.match(result.error, /authorization timed out/);
assert.deepEqual(pty.writes, []);
});
test('idle PowerShell whose raw tail was CSI-erased still receives the command', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
const prompt = 'PS C:\\Users\\alice> ';
trackSessionIdlePrompt(session, `Windows PowerShell\r\n${powershellEraseRedraw(prompt)}`);
assert.equal(getFreshIdlePrompt(session), '');
const job = startPtyJob(pty, 'Write-Output ok', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 200,
timeoutMs: 1000,
typedInput: true,
});
t.mock.timers.tick(200);
const result = await job.resultPromise;
assert.equal(result.ok, true);
assert.equal(result.stdout, 'OK');
assert.equal(pty.writes.length, 1);
assert.match(pty.writes[0], /\$__NCMCP_/);
});
test('the next PowerShell exec runs after the clear-prefix echo is erased on screen', async () => {
const prompt = 'PS C:\\Users\\alice> ';
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, prompt);
const pty = new EventEmitter();
pty.writes = [];
pty.write = (data) => {
const text = String(data);
pty.writes.push(text);
const marker = text.match(/(__NCMCP_[0-9a-z]+_[0-9a-f]+__)/i)?.[1];
if (!marker) return;
queueMicrotask(() => {
const chunk = `${marker}_S\r\nok\r\n${marker}_E:0\r\n${powershellEraseRedraw(prompt)}`;
trackSessionIdlePrompt(session, chunk);
pty.emit('data', chunk);
});
};
const first = startPtyJob(pty, 'Write-Output ok', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
timeoutMs: 1000,
typedInput: true,
});
const firstResult = await first.resultPromise;
assert.equal(firstResult.ok, true);
assert.equal(firstResult.stdout, 'ok');
assert.equal(getFreshIdlePrompt(session), '');
assert.equal(getVisibleIdlePrompt(session), prompt);
const second = startPtyJob(pty, 'Write-Output next', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 200,
timeoutMs: 1000,
typedInput: true,
});
const secondResult = await second.resultPromise;
assert.equal(secondResult.ok, true);
assert.equal(secondResult.stdout, 'ok');
assert.equal(pty.writes.length, 2);
});
test('alt-screen paint is not ready after the entry sequence leaves the prompt tail', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
const prompt = 'PS C:\\Users\\alice> ';
// A full-screen app can emit more than the 4096-byte prompt tail. Once the
// alternate-screen entry scrolls off, a painted idle prompt must not unlock
// ptyExec and type into the still-running program.
trackSessionIdlePrompt(session, prompt);
trackSessionIdlePrompt(session, `\x1b[?1049h${'x'.repeat(4200)}`);
trackSessionIdlePrompt(session, `\r\n${prompt}\r`);
assert.equal(session._promptTrackTail.includes('\x1b[?1049h'), false);
assert.equal(terminalCursorLine(session._promptTrackTail).trimEnd(), prompt.trimEnd());
assert.equal(getFreshIdlePrompt(session), '');
assert.equal(getVisibleIdlePrompt(session), '');
assert.equal(readyPrompt(session), '');
const job = startPtyJob(pty, 'Write-Output ok', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 50,
timeoutMs: 1000,
});
t.mock.timers.tick(50);
const result = await job.resultPromise;
assert.equal(result.code, 'SHELL_NOT_READY');
assert.match(result.error, /no command was sent/);
assert.deepEqual(pty.writes, []);
});
test('real pending PowerShell input is still not sent', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, 'PS C:\\Users\\alice> Write-Output ok');
const job = startPtyJob(pty, 'echo OK', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 50,
timeoutMs: 1000,
});
t.mock.timers.tick(50);
const result = await job.resultPromise;
assert.equal(result.code, 'SHELL_NOT_READY');
assert.match(result.error, /no command was sent/);
assert.deepEqual(pty.writes, []);
});
+43 -1
View File
@@ -143,7 +143,20 @@ function looksLikeIdleAutoLogout(outputTail) {
function trackSessionIdlePrompt(session, chunk) {
if (!session || typeof chunk !== "string" || !chunk) return "";
const nextTail = `${session._promptTrackTail || ""}${chunk}`.slice(-MAX_PROMPT_TRACK_TAIL);
const previousTail = session._promptTrackTail || "";
const combined = `${previousTail}${chunk}`;
const overflow = combined.length - MAX_PROMPT_TRACK_TAIL;
if (overflow > 0) {
// The kept tail no longer starts where the previous tail started. Replay
// the dropped prefix so an alternate-screen enter or leave that scrolls
// off is still the mode at the first kept byte.
const { alternateScreenActiveAfter } = require("../terminalLogSanitizer.cjs");
session._promptTrackAltScreenAtTailStart = alternateScreenActiveAfter(
combined.slice(0, overflow),
session._promptTrackAltScreenAtTailStart === true,
);
}
const nextTail = overflow > 0 ? combined.slice(overflow) : combined;
session._promptTrackTail = nextTail;
const prompt = extractTrailingIdlePrompt(nextTail);
@@ -182,6 +195,34 @@ function getFreshIdlePrompt(session) {
return normalizedTail.endsWith(normalizedCached) ? cached : "";
}
// Readiness companion to getFreshIdlePrompt. PSReadLine echoes keys (including
// the pending-input clear prefix) and then erases them with cursor-column +
// ED/EL without appending a fresh copy of the prompt. stripAnsi removes the
// erase, so the raw tail no longer ends with the cached prompt while the
// screen is still an idle default prompt (#3927). Collapse those cursor and
// erase operations, then accept only the line the cursor is actually on.
function getVisibleIdlePrompt(session) {
const tail = session?._promptTrackTail;
if (typeof tail !== "string" || !tail) return "";
const { terminalCursorLine } = require("../terminalLogSanitizer.cjs");
const cursorLine = terminalCursorLine(tail, {
alternateScreenActive: session._promptTrackAltScreenAtTailStart === true,
});
const rightTrimmed = cursorLine.replace(/\s+$/, "");
if (!rightTrimmed) return "";
if (
!isDefaultPowerShellPromptLine(rightTrimmed)
&& !isDefaultPosixPromptLine(rightTrimmed)
&& !isDefaultCmdPromptLine(rightTrimmed)
) {
return "";
}
// Keep one trailing space when the visible prompt has one. Erase-to-end
// padding must not become part of the expected prompt.
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
}
// ── URL helpers ──
function isLocalhostHostname(hostname) {
@@ -1122,6 +1163,7 @@ module.exports = {
formatSyntheticEcho,
extractTrailingIdlePrompt,
getFreshIdlePrompt,
getVisibleIdlePrompt,
isDefaultPowerShellPromptLine,
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
+46
View File
@@ -8,6 +8,7 @@ const {
extractTrailingIdlePrompt,
formatSyntheticEcho,
getFreshIdlePrompt,
getVisibleIdlePrompt,
isDefaultPowerShellPromptLine,
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
@@ -795,6 +796,51 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oracle/RHEL bracke
assert.equal(getFreshIdlePrompt(bracketedPath), "[user@host My [Project]]$ ");
});
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
// erase but keeps the keys, so the cached prompt no longer matches the tail.
// The screen is still an idle default PowerShell prompt (#3927).
const session = {};
const prompt = "PS C:\\Users\\alice> ";
trackSessionIdlePrompt(session, `Windows PowerShell\r\n${prompt}ggd2147483647d\x1b[20G\x1b[0J`);
assert.equal(getFreshIdlePrompt(session), "");
assert.equal(extractTrailingIdlePrompt(session._promptTrackTail), "");
assert.equal(getVisibleIdlePrompt(session), prompt);
const backspaced = {};
trackSessionIdlePrompt(backspaced, `${prompt}\x08`);
assert.equal(getFreshIdlePrompt(backspaced), "");
assert.equal(getVisibleIdlePrompt(backspaced), prompt);
const crHomed = {};
trackSessionIdlePrompt(crHomed, `${prompt}\r`);
assert.equal(getFreshIdlePrompt(crHomed), "");
assert.equal(getVisibleIdlePrompt(crHomed), prompt);
});
test("visible idle prompt stays empty for pending input, a following line, and an unrecognized prompt", () => {
const pending = {};
trackSessionIdlePrompt(pending, "PS C:\\Users\\alice> Write-Output ok");
assert.equal(getFreshIdlePrompt(pending), "");
assert.equal(getVisibleIdlePrompt(pending), "");
const movedOn = {};
trackSessionIdlePrompt(movedOn, "PS C:\\Users\\alice> \r\n");
assert.equal(getVisibleIdlePrompt(movedOn), "");
const custom = {};
trackSessionIdlePrompt(custom, "PS C:\\Users\\alice>\r\nexit\r\n❯ ");
assert.equal(getVisibleIdlePrompt(custom), "");
const fullscreen = {};
trackSessionIdlePrompt(fullscreen, "PS C:\\Users\\alice> \x1b[?1049h\x1b[Hvim");
assert.equal(getVisibleIdlePrompt(fullscreen), "");
assert.equal(getVisibleIdlePrompt({ _promptTrackTail: "" }), "");
assert.equal(getVisibleIdlePrompt(null), "");
});
test("getFreshIdlePrompt and trackSessionIdlePrompt round-trip through a real PTY-like flow", () => {
// (1) Remote PowerShell prompt arrives — lastIdlePrompt is captured.
const session = {};
@@ -3,7 +3,7 @@
// runs under `with (ctx)` where bare `require` resolves to ctx.require
// (based in electron/bridges/). Requiring here keeps the path unambiguous.
const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs");
const { formatSyntheticEcho } = require("../ai/shellUtils.cjs");
const { formatSyntheticEcho, getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
const { remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
const defaultAiPrivacyService = require("../../shared/aiPrivacyService.cjs");
@@ -217,7 +217,7 @@ function registerCattyExecHandlers(ctx) {
chatSessionId,
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) : undefined,
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
typedInput: true,
echoCommand: (rawCommand) => {
const contents = electronModule?.webContents?.fromId?.(session.webContentsId);
@@ -329,6 +329,43 @@ test("expired local and unknown jobs do not claim a lost worker route", (t) => {
});
test("MCP exec sends on an idle PowerShell prompt hidden by a CSI erase", async () => {
const pty = new FakePty();
pty.write = (data) => {
pty.writes.push(String(data));
const marker = String(data).match(/(__NCMCP_[0-9a-z]+_[0-9a-f]+__)/i)?.[1];
if (!marker) return;
queueMicrotask(() => pty.emit("data", `${marker}_S\r\nok\r\n${marker}_E:0\r\n`));
};
const { trackSessionIdlePrompt } = require("./ai/shellUtils.cjs");
const session = {
protocol: "ssh",
pty,
shellKind: "powershell",
_promptTrackTail: "",
lastIdlePrompt: "",
};
trackSessionIdlePrompt(session, "PS C:\\Users\\alice> ggd2147483647d\x1b[20G\x1b[0J");
const ctx = createExecHandlerTestContext({
sessions: new Map([["ps", session]]),
backgroundJobs: new Map(),
});
ctx.commandTimeoutMs = 200;
ctx.startPtyJob = require("./ai/ptyExec.cjs").startPtyJob;
ctx.execViaPty = require("./ai/ptyExec.cjs").execViaPty;
ctx.getFreshIdlePrompt = require("./ai/shellUtils.cjs").getFreshIdlePrompt;
const api = createExecHandlerApi(ctx);
const result = await api.handleExec({
sessionId: "ps",
chatSessionId: "ps-chat",
command: "Write-Output ok",
});
assert.equal(result.ok, true);
assert.equal(result.stdout, "ok");
assert.equal(pty.writes.length, 1);
assert.match(pty.writes[0], /\$__NCMCP_/);
});
test("MCP background readiness timeout survives job polling without PTY writes", async (t) => {
t.mock.timers.enable({ apis: ["Date", "setTimeout"] });
const pty = new FakePty();
@@ -2,6 +2,7 @@
// Module-level require: code inside createExecHandlerApi runs under `with (ctx)`
// where bare `require` resolves to ctx.require (based in electron/bridges/).
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
const { getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
const { emitJobDiag } = require("../ai/jobStartupDiagnostics.cjs");
const {
ensureSessionShellKind,
@@ -159,7 +160,7 @@ function createExecHandlerApi(ctx) {
onEchoSuppressionPrime: (marker) => echoCommandToSession(session, sessionId, `${marker}_I`, { syntheticEcho: false }),
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) : undefined,
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
typedInput: true,
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
chatSessionId,
@@ -341,7 +342,7 @@ function createExecHandlerApi(ctx) {
chatSessionId,
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) : undefined,
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
typedInput: true,
echoCommand: (rawCommand) => echoCommandToSession(session, sessionId, rawCommand),
maxBufferedChars: MAX_BACKGROUND_JOB_OUTPUT_CHARS,
+90
View File
@@ -76,6 +76,11 @@ class TerminalTextRenderer {
return this.toString();
}
getCursorLine() {
const line = this.lines[this.row] || [];
return line.map((cell) => cell?.ch || " ").join("");
}
toString({ includePendingClearedScreen = false, formatLine = (line) => line } = {}) {
const lines = includePendingClearedScreen ? this.#linesWithPendingClearedScreen() : this.lines;
return lines
@@ -515,6 +520,89 @@ function terminalDataToPlainText(terminalData) {
return renderer.finish();
}
function terminalCursorLine(terminalData, options) {
// Prompt tracking keeps a rolling tail, so the alternate-screen entry may
// already have scrolled off. Seed the mode that was active at the first
// byte still in that tail; a fresh renderer would otherwise treat TUI paint
// as the main screen.
const renderer = new TerminalTextRenderer({
alternateScreenActive: options?.alternateScreenActive === true,
});
renderer.feed(terminalData || "");
renderer.finish();
// A full-screen program owns the display. The main buffer may still hold
// the shell prompt from before the alternate screen was entered.
if (renderer.alternateScreenActive) return "";
return renderer.getCursorLine();
}
// Alternate-screen transitions from TerminalTextRenderer, without a text
// buffer. Callers replay the bytes a rolling tail dropped so truncation
// cannot clear the guard.
function alternateScreenActiveAfter(text, alternateScreenActive) {
let active = alternateScreenActive === true;
if (!text) return active;
let state = "normal";
let escapeBuffer = "";
for (const ch of text) {
if (state === "esc") {
if (ch === "[") {
state = "csi";
escapeBuffer = "";
continue;
}
if (ch === "]") {
state = "osc";
continue;
}
if (ch === "c") active = false;
state = "normal";
continue;
}
if (state === "csi") {
escapeBuffer += ch;
if (CSI_FINAL_RE.test(ch)) {
active = alternateScreenActiveFromCsi(escapeBuffer, active);
state = "normal";
escapeBuffer = "";
}
continue;
}
if (state === "osc") {
if (ch === "\x07") state = "normal";
else if (ch === "\x1b") state = "oscEsc";
continue;
}
if (state === "oscEsc") {
state = ch === "\\" ? "normal" : "osc";
continue;
}
if (ch === "\x1b") {
state = "esc";
continue;
}
if (ch === "\x9b") {
state = "csi";
escapeBuffer = "";
}
}
return active;
}
function alternateScreenActiveFromCsi(sequence, active) {
const final = sequence.at(-1);
if (final !== "h" && final !== "l") return active;
const params = sequence.slice(0, -1);
if (!params.includes("?")) return active;
for (const part of params.replace(/[?><=]/g, "").split(";")) {
if (part === "") continue;
const mode = Number.parseInt(part, 10);
if (mode === 47 || mode === 1047 || mode === 1049) return final === "h";
}
return active;
}
function terminalDataToHtmlContent(terminalData) {
const renderer = new TerminalTextRenderer();
renderer.feed(terminalData || "");
@@ -531,6 +619,8 @@ module.exports = {
createTerminalTextRenderer,
terminalDataToHtmlContent,
terminalDataToPlainText,
terminalCursorLine,
alternateScreenActiveAfter,
};
function createDefaultStyle() {
+3 -3
View File
@@ -8,7 +8,7 @@ const {
execViaChannel,
execViaRawPty,
} = require("../bridges/ai/ptyExec.cjs");
const { getFreshIdlePrompt, formatSyntheticEcho } = require("../bridges/ai/shellUtils.cjs");
const { getFreshIdlePrompt, getVisibleIdlePrompt, formatSyntheticEcho } = require("../bridges/ai/shellUtils.cjs");
const {
ensureSessionShellKind,
remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec,
@@ -338,7 +338,7 @@ function createWorkerAiExecHandler({
chatSessionId,
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) : undefined,
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
typedInput: true,
echoCommand: (rawCommand) => {
event?.sender?.send?.("netcatty:data", {
@@ -567,7 +567,7 @@ function createWorkerAiJobStartHandler({
chatSessionId,
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) : undefined,
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
typedInput: true,
echoCommand: (rawCommand) => {
event?.sender?.send?.("netcatty:data", {