fix(ai): recognize macOS root prompts (host:dir user#) as idle-ready (#4197)

* fix(ai): recognize macOS root prompts (host:dir user#) as idle-ready

* fix(ai): reject cmd prompt lines with pending input from root-prompt match
This commit is contained in:
GOUKI9999 authored and GitHub committed 2026-11-23 16:46:27 +08:00
1 parent 10b91f607e
commit 065dccca1d
3 files changed
+260

No files matched your search

@@ -456,3 +456,92 @@ test('OSC 133 C/D markers keep exec gated even when output echoes a known prompt
assert.match(result.error, /no command was sent/);
assert.deepEqual(pty.writes, []);
});
// ── macOS `sudo -i` root prompt (issue #4195): end-to-end startPtyJob seam ──
test('macOS sudo -i root prompt is recognized as idle and allows exec', async () => {
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
const prompt = 'ChrisdeMacBook-Air:~ root# ';
trackSessionIdlePrompt(session, `Password:\r\nSorry, try again.\r\n${prompt}`);
assert.equal(session.lastIdlePrompt, prompt);
assert.equal(readyPrompt(session), prompt);
const result = await startPtyJob(pty, 'echo OK', {
shellKind: 'posix',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 200,
timeoutMs: 1000,
}).resultPromise;
assert.equal(result.ok, true);
assert.equal(pty.writes.length, 1);
});
test('sudo Password: / Sorry, try again. still gate exec as SHELL_NOT_READY', async () => {
for (const line of ['Password:', 'Sorry, try again.']) {
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, `zhangdanting@ChrisdeMacBook-Air ~ %\r\n${line}`);
assert.equal(readyPrompt(session), '', line);
const result = await startPtyJob(pty, 'echo forbidden', {
shellKind: 'posix',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 25,
timeoutMs: 1000,
}).resultPromise;
assert.equal(result.code, 'SHELL_NOT_READY', line);
assert.deepEqual(pty.writes, [], line);
}
});
// #4195 follow-up: the macOS root pattern must not read a `C:` drive prefix as
// a hostname. These cmd.exe lines still have PENDING INPUT (an unfinished
// command), so the readiness gate must stay closed and NO bytes may be typed.
test('cmd.exe prompt-with-input lines are NOT idle-ready: zero PTY bytes written (#4048)', async () => {
for (const line of ['C:\\Users\\alice>echo hello#', 'C:\\> dir#']) {
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, line);
assert.equal(readyPrompt(session), '', line);
const result = await startPtyJob(pty, 'echo forbidden', {
shellKind: 'cmd',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 25,
timeoutMs: 1000,
}).resultPromise;
assert.equal(result.code, 'SHELL_NOT_READY', line);
assert.match(result.error, /no command was sent/, line);
assert.deepEqual(pty.writes, [], line);
}
});
// Valid macOS root prompts still open the gate (no false-negative from the
// tightened pattern), and `Password:` stays blocked.
test('valid macOS root prompt still ready; Password: still blocked end-to-end', async () => {
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, 'Password:\r\nSorry, try again.\r\nhost:~ root$ ');
assert.equal(readyPrompt(session), 'host:~ root$ ');
const result = await startPtyJob(pty, 'echo OK', {
shellKind: 'posix',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 200,
timeoutMs: 1000,
}).resultPromise;
assert.equal(result.ok, true);
assert.equal(pty.writes.length, 1);
const blockedPty = new TestPty();
const blockedSession = { _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(blockedSession, 'Password:');
assert.equal(readyPrompt(blockedSession), '');
const blocked = await startPtyJob(blockedPty, 'echo forbidden', {
shellKind: 'posix',
getReadyPrompt: () => readyPrompt(blockedSession),
promptWaitTimeoutMs: 25,
timeoutMs: 1000,
}).resultPromise;
assert.equal(blocked.code, 'SHELL_NOT_READY');
assert.deepEqual(blockedPty.writes, []);
});
+31
View File
@@ -105,6 +105,36 @@ const OH_MY_ZSH_YS_HOST_LINE_PATTERN = /^#\s+[^\s@]+\s+@\s+[^\s]+(?:\s+[^\n\r]+)
// within the path so partially entered commands do not count as idle prompts.
const ALPINE_PROMPT_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*:(?:~(?:\/[^#$\n\r]*)?|\/[^#$\n\r]*)[#$]$/;
// macOS / bash root prompt after `sudo -i`: PS1 `\h:\W \u\$` renders as
// `host:dir user#` (e.g. `ChrisdeMacBook-Air:~ root#`, `host:/var/root root#`).
// It has NO `@`, so POSIX / ZSH / PAREN (all `user@host`-shaped) miss it, and
// ALPINE only covers `host:~#` with NO ` user` segment. Pure-shape only:
// `host:` + path + whitespace + username + trailing `[#$]`, no `@`; the path
// segment excludes whitespace (incl. CR/LF), `:`, `#`, `$` so partially typed
// commands cannot match. See issue #4195.
// The path segment ALSO excludes `\` and `>` (Windows path / cmd prompt
// markers). Without this, a cmd.exe line with pending input such as
// `C:\Users\alice>echo hello#` or `C:\> dir#` is misread as host `C` + `:` +
// path `\Users\alice>echo` / `\>`, then ` hello` / ` dir` as the username and
// the trailing `#` as the prompt marker — opening the readiness gate on a
// prompt that still has unfinished input. That is exactly the #4048 objection
// (treating prompt-with-input as idle-ready risks typing into unfinished
// input), so drive-letter / `>` forms are rejected outright. The username
// whitelist `[A-Za-z0-9_.-]+` already cannot contain `\`, `>` or `:`.
// `PS C:\>` stays owned by POWERSHELL_PROMPT_PATTERN (checked before this
// whitelist) and `C:\>` by CMD_PROMPT_PATTERN; no collision.
// Deliberately NO shellKind gate: `sudo -i` does not refresh shellKind tracking
// (`detectShellKind` runs at connect time in terminalBridge.cjs; `_loginShellKind`
// comes from sessionShellKind.cjs), so the live root sh/bash is still tracked as
// `zsh`. A `shellKind ∈ {posix, bash}` gate would reject exactly this session;
// every whitelist entry here is pure-shape for the same reason, and a shellKind
// gate cannot be the sole fix for this bug for the same staleness reason.
// Residual false-ready risk: any program printing `host:dir user#` as its last
// line could be mistaken for an idle prompt. That is the same risk class shared
// by every whitelist pattern (POSIX / ZSH / ALPINE / ...); this adds no new
// mitigation and does not change existing recognition semantics.
const MACOS_ROOT_PROMPT_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*:(?:~|\/|[^\s:#$>\\]+)\s+[A-Za-z0-9_.-]+[#$]$/;
// Powerlevel10k / similar Unicode prompt-ending ❯ (U+276F). Common idle forms:
// `~ ❯`, `~/path ❯`, `/tmp ❯`, short-dir `proj ❯`, optional `user@host `
// prefix (`alice@host ~ ❯`). Require a non-empty prefix and whitespace before
@@ -144,6 +174,7 @@ function isDefaultPosixPromptLine(line) {
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
MACOS_ROOT_PROMPT_PATTERN.test(withoutEnvPrefix) ||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
POWERLEVEL10K_PROMPT_PATTERN.test(withoutEnvPrefix) ||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(withoutEnvPrefix)
+140
View File
@@ -1589,3 +1589,143 @@ test("OSC 133 lifecycle state survives rolling-tail eviction without reviving ol
assert.equal(getFreshIdlePrompt(session), "");
assert.equal(getVisibleIdlePrompt(session), "");
});
// ── macOS `sudo -i` root prompt (`host:dir user#`) — issue #4195 ──
test("isDefaultPosixPromptLine matches macOS sudo -i root prompts (host:dir user#)", () => {
for (const prompt of [
"ChrisdeMacBook-Air:~ root#",
"host:/var/root root#",
"MacBook-Pro:/var/root root#",
"ChrisdeMacBook-Air:~ admin$",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
}
});
test("extractTrailingIdlePrompt recognizes a macOS root prompt (incl. ANSI) and preserves trailing whitespace", () => {
assert.equal(
extractTrailingIdlePrompt("Password:\r\nSorry, try again.\r\nChrisdeMacBook-Air:~ root#"),
"ChrisdeMacBook-Air:~ root#",
);
assert.equal(
extractTrailingIdlePrompt("Last login...\r\nChrisdeMacBook-Air:~ root# "),
"ChrisdeMacBook-Air:~ root# ",
);
// ANSI colour wrappers are removed by stripAnsi before shape matching.
assert.equal(
extractTrailingIdlePrompt(
"Password:\r\n\x1b[01;32mChrisdeMacBook-Air\x1b[00m:\x1b[01;34m~\x1b[00m root#",
),
"ChrisdeMacBook-Air:~ root#",
);
// A prompt followed by input, or followed by a newline, is not idle.
assert.equal(extractTrailingIdlePrompt("ChrisdeMacBook-Air:~ root# echo hi"), "");
assert.equal(extractTrailingIdlePrompt("ChrisdeMacBook-Air:~ root#\r\n"), "");
});
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a macOS root prompt, then expire on new output", () => {
const session = {};
trackSessionIdlePrompt(session, "Password:\r\nSorry, try again.\r\nChrisdeMacBook-Air:~ root# ");
assert.equal(session.lastIdlePrompt, "ChrisdeMacBook-Air:~ root# ");
assert.equal(getFreshIdlePrompt(session), "ChrisdeMacBook-Air:~ root# ");
assert.equal(getVisibleIdlePrompt(session), "ChrisdeMacBook-Air:~ root# ");
// A command being echoed breaks the endsWith chain -> no longer fresh.
trackSessionIdlePrompt(session, "uname -a");
assert.equal(getFreshIdlePrompt(session), "");
assert.equal(getVisibleIdlePrompt(session), "");
trackSessionIdlePrompt(session, "\r\nDarwin ... arm64\r\nChrisdeMacBook-Air:~ root# ");
assert.equal(getFreshIdlePrompt(session), "ChrisdeMacBook-Air:~ root# ");
assert.equal(getVisibleIdlePrompt(session), "ChrisdeMacBook-Air:~ root# ");
});
test("macOS root prompt recognition preserves prior classifications and rejects look-alikes", () => {
// No regression: the user's zsh prompt is still idle-ready.
assert.equal(isDefaultPosixPromptLine("zhangdanting@ChrisdeMacBook-Air ~ %"), true);
assert.equal(
extractTrailingIdlePrompt("welcome\r\nzhangdanting@ChrisdeMacBook-Air ~ %"),
"zhangdanting@ChrisdeMacBook-Air ~ %",
);
// `Password:` / `Sorry, try again.` must stay NOT ready: the shell is blocked
// on secret input, so the bridge must never type into it.
for (const line of ["Password:", "Sorry, try again."]) {
assert.equal(isDefaultPosixPromptLine(line), false, line);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
}
// Shapes owned by existing patterns are unchanged.
assert.equal(isDefaultPosixPromptLine("host:~#"), true); // ALPINE (no user segment)
assert.equal(isDefaultPosixPromptLine("user@host:~#"), true); // POSIX
assert.equal(isDefaultPowerShellPromptLine("PS C:\\>"), true); // PowerShell
assert.equal(isDefaultPosixPromptLine("PS C:\\>"), false); // untouched
// Program-output look-alikes: trailing `%` / extra text / pending input.
for (const line of [
"ChrisdeMacBook-Air:~ root# 47%",
"ChrisdeMacBook-Air:~ root# building 47%",
"ChrisdeMacBook-Air:~ root# echo hi",
"deploy: release 100% root#",
]) {
assert.equal(isDefaultPosixPromptLine(line), false, line);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
}
});
test("the macOS root pattern is pure-shape and disjoint from existing whitelist shapes (no double-count)", () => {
// Same shape as MACOS_ROOT_PROMPT_PATTERN; kept local to assert that the new
// pattern does not also claim shapes already owned by ALPINE / POSIX / ZSH /
// CMD / PowerShell / P10K / OMZ (the whitelist is a boolean OR, so overlap
// would be a latent double-count even though readiness is unchanged).
const root = /^[A-Za-z0-9_][A-Za-z0-9_.-]*:(?:~|\/|[^\s:#$>\\]+)\s+[A-Za-z0-9_.-]+[#$]$/;
for (const line of [
"host:~#", // ALPINE, no ` user` segment
"host:/tmp#", // ALPINE
"user@host:~#", // POSIX
"zhangdanting@ChrisdeMacBook-Air ~ %", // ZSH
"PS C:\\>", // PowerShell
"C:\\>", // CMD
"~ ❯", // P10K
"➜ ~", // OMZ
"C:\\Users\\alice>echo hello#", // #4048: cmd prompt-with-input
"C:\\> dir#", // #4048: cmd prompt-with-input
]) {
assert.equal(root.test(line), false, line);
}
for (const line of ["ChrisdeMacBook-Air:~ root#", "host:/var/root root#", "host:~ root$"]) {
assert.equal(root.test(line), true, line);
}
});
test("macOS root pattern rejects cmd drive-letter prompts with pending input (#4048)", () => {
// A `C:` drive prefix is NOT a hostname. These lines carry `\` / `>` and a
// trailing command, i.e. a prompt with unfinished input. They must NEVER be
// judged idle-ready: typing into them would corrupt the pending input.
for (const line of [
"C:\\Users\\alice>echo hello#",
"C:\\> dir#",
"D:\\data>type notes.txt#",
"host:foo>bar root#", // `>` in the path segment
"host:foo\\bar root#", // `\` in the path segment
]) {
assert.equal(isDefaultPosixPromptLine(line), false, line);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
}
// Valid macOS root prompts remain ready (no false-negative regression).
for (const prompt of [
"ChrisdeMacBook-Air:~ root#",
"host:/var/root root#",
"host:~ root$",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
}
// Plain Windows prompts keep their own owners: POWERSHELL for `PS C:\>`,
// CMD for `C:\>`. Neither is claimed by the POSIX whitelist (no collision).
assert.equal(isDefaultPowerShellPromptLine("PS C:\\>"), true);
assert.equal(isDefaultPosixPromptLine("PS C:\\>"), false);
assert.equal(isDefaultCmdPromptLine("C:\\>"), true);
assert.equal(isDefaultPosixPromptLine("C:\\>"), false);
// Credential prompts stay not-ready.
assert.equal(isDefaultPosixPromptLine("Password:"), false);
assert.equal(extractTrailingIdlePrompt("welcome\r\nPassword:"), "");
});