Files
Netcatty/electron/bridges/mcpServerBridge.execHandlers.test.cjs
T
陈大猫 ae52ef461e fix(ai): probe remote login shell so fish AI exec works (#1854) (#2061)
* fix(ai): probe remote login shell before PTY wrappers (#1854)

SSH/Telnet sessions never set shellKind, so AI exec defaulted to the
posix wrapper and broke fish login shells with "Unsupported use of '='".

Probe the remote login shell once via a silent SSH exec channel before
AI/MCP PTY execution, cache session.shellKind, and leave et/mosh
shellKind unset so they can take the same path. Fish wrapper coverage
includes a real-fish binary regression test.

* fix(ai): harden remote shell kind probing

* fix(ai): keep PowerShell prompt override after posix login probe

Do not pin probed posix login shells onto session.shellKind. Unset still
defaults to posix wrapping, while leaving the kind open preserves the
live PS ...> prompt override for bash/zsh login shells that entered
pwsh interactively (Codex P2 on #2061 / issue #841 path).

* fix(ai): make remote shellKind probe cancellable before PTY write

Register a pending activePtyExecs marker for the pre-exec shell probe so
Stop during the probe window latches cancellation and does not still type
the command after the probe resolves (Codex P2 on #2061). Wire through
Catty, MCP, and worker foreground exec paths.

* fix(ai): release session lock if job shell probe rejects

terminal_start reserves the session before ensureSessionShellKind; if that
promise rejects, the previous .then-only path never released the lock.

* fix(ai): cancel pending terminal_start during shellKind probe

Register background job entries before the remote shell probe so chat
cancel can latch and abort job start before startPtyJob types into the
PTY (MCP + worker paths; Codex P2 on #2061).

* fix(ai): do not pin login shell as active; default to posix_sh

Login-shell probe no longer sets session.shellKind for fish/posix — only
powershell/cmd are pinned. Unset shellKind resolves to posix_sh (sh -c
inner POSIX wrapper), which both fish and bash interactive shells can
parse, fixing #1854 without assuming login shell === active shell
(Codex P2 on #2061).

* fix(ai): use login shell as soft hint, not sh -c / dash

Drop posix_sh default that ran commands under /bin/sh (often dash) and
broke bash/zsh source, [[ ]], and functions. Keep fish/posix probe as
session._loginShellKind soft hint for resolveEffectiveShellKind so fish
login still gets the fish wrapper and bash/zsh keep the native posix
wrapper, while live PS prompts can still override.

* test(ai): cover shell probe cancellation gaps
2026-07-09 20:56:38 +08:00

127 lines
3.5 KiB
JavaScript

"use strict";
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const { EventEmitter } = require("node:events");
const test = require("node:test");
const { createBackgroundJobApi } = require("./mcpServerBridge/backgroundJobs.cjs");
const { createExecHandlerApi } = require("./mcpServerBridge/execHandlers.cjs");
const { PROBE_OUTPUT_MARKER } = require("./ai/sessionShellKind.cjs");
class FakePty extends EventEmitter {
constructor() {
super();
this.writes = [];
}
write(data) {
this.writes.push(String(data));
}
}
function nextTick() {
return new Promise((resolve) => setImmediate(resolve));
}
function createDeferredShellProbeConn(stdout = `${PROBE_OUTPUT_MARKER}/usr/bin/fish\n`) {
let execCallback = null;
const conn = {
exec(_command, callback) {
execCallback = callback;
},
};
return {
conn,
release() {
assert.equal(typeof execCallback, "function", "probe should be waiting for ssh exec callback");
const stream = new EventEmitter();
stream.stderr = new EventEmitter();
stream.close = () => stream.emit("close");
execCallback(null, stream);
queueMicrotask(() => {
stream.emit("data", Buffer.from(stdout));
stream.emit("close");
});
},
};
}
function createExecHandlerTestContext({ sessions, backgroundJobs }) {
const ctx = {
sessions,
backgroundJobs,
activeSessionSftpOps: new Map(),
activeSessionExecutions: new Map(),
activePtyExecs: new Map(),
crypto,
sftpBridge: {},
BACKGROUND_JOB_RETENTION_MS: 10 * 60 * 1000,
DEFAULT_BACKGROUND_JOB_POLL_INTERVAL_MS: 30 * 1000,
MAX_BACKGROUND_JOB_OUTPUT_CHARS: 256 * 1024,
DEFAULT_BACKGROUND_JOB_TIMEOUT_MS: 60 * 60 * 1000,
commandTimeoutMs: 5000,
activeSftpOpSeq: 0,
debugLog() {},
getSessionMeta() {
return {};
},
checkCommandSafety() {
return { blocked: false };
},
beginChatExecution() {
return { ok: true, release() {} };
},
getFreshIdlePrompt() {
return "";
},
echoCommandToSession() {},
validateSessionScope() {
return null;
},
};
Object.assign(ctx, createBackgroundJobApi(ctx));
return ctx;
}
test("MCP terminal_start chat cancel during shellKind probe aborts before PTY write", async () => {
const pty = new FakePty();
const deferred = createDeferredShellProbeConn();
const sessions = new Map([
["ssh-fish", {
protocol: "ssh",
stream: pty,
conn: deferred.conn,
}],
]);
const backgroundJobs = new Map();
const ctx = createExecHandlerTestContext({ sessions, backgroundJobs });
const api = createExecHandlerApi(ctx);
const pendingStart = api.handleJobStart({
sessionId: "ssh-fish",
command: "sleep 999",
chatSessionId: "chat-cancel-probe",
});
await nextTick();
assert.equal(backgroundJobs.size, 1, "job should be registered while probe is pending");
ctx.cancelBackgroundJobsForSession("chat-cancel-probe");
deferred.release();
const started = await pendingStart;
assert.equal(started.ok, false);
assert.equal(started.error, "Cancelled");
assert.equal(started.status, "cancelled");
assert.equal(
pty.writes.filter((entry) => entry.includes("__NCMCP_")).length,
0,
"cancelled pending start must not type a wrapper into the PTY",
);
const [job] = backgroundJobs.values();
assert.equal(job.status, "cancelled");
assert.equal(job.pendingShellProbe, false);
assert.equal(ctx.activeSessionExecutions.size, 0);
});