Files
Netcatty/electron/bridges/mcpServerBridge.execHandlers.test.cjs
T
Radwan Selo a4805b3e3d feat(capabilities): add terminal_execute_bulk to run one command on many sessions (#4342)
* feat(capabilities): add terminal_execute_bulk to run one command on many sessions

Add a terminal_execute_bulk MCP tool that runs the same short command on
2-20 open terminal sessions and groups identical results.

- All-or-nothing preflight: scope, closing, busy, connected, transport
  and the per-shell command safety policy are checked for every target
  before anything is sent. Any bad target cancels the whole call and all
  bad targets are reported at once.
- One approval listing every host. Remembered grants and external-client
  session approval never satisfy it (policy.requiresFreshApproval), and a
  pending fan-out is not swept up by another request's session approval.
- Targets are claimed before the prompt and re-checked after it; all
  targets then start in the same synchronous turn under a single per-chat
  exec lock, each with its own wall-clock timeout.
- Results are grouped only when status, exit code, stdout, stderr and
  error are identical on the full output, then truncated (tailLines and
  size caps). JSON output matches the other tools.
- Loaded on demand through the terminal_bulk toolset.

* fix(capabilities): harden terminal_execute_bulk after review

- Only trust the metadata "connected" flag for worker-hosted sessions; a
  live main-process session with a stale snapshot is no longer refused.
- Keep targets protected from idle auto-close from the claim through the
  approval wait to completion, and release on every path.
- Classify blocklist refusals before status keywords so a pattern such as
  "cancel-job" is reported as not_sent, not cancelled.
- List the terminal_bulk toolset in the MCP server instructions and the
  netcatty-mcp skill so clients can discover it.
- Test that the bulk RPC gets the same timeout budget as terminal_execute.

* fix(capabilities): validate worker sessions up front and cancel them at the deadline

An independent review found that the default (terminal worker) sessions
could receive a partial send, and that the backstop deadline never
reached the worker.

- Add a no-send precheck mode to the worker exec handler. The bulk
  preflight now runs every deterministic check for worker sessions
  (transport, shell kind, shell-specific safety patterns, unsupported
  local shell, busy job) so a refusal cancels the whole call before any
  host receives the command.
- Add netcatty:ai:exec:cancel and call it at the deadline, so a stuck
  worker command is cancelled before the per-chat lock is released
  instead of overlapping the next command. Background jobs are left
  alone.
- Make the deadline grace 3s and give the bulk RPC extra timeout budget
  for its preflight, so the backstop fires before the client gives up.
- Do not group hosts whose exec layer already dropped different amounts
  of output, and share one size budget between stdout and stderr.
- Restrict the capability to the sidebar agent; the global agent runs
  delegated, which bulk refuses.
- Document that live terminal readiness is a send-time state.

* test(capabilities): cover terminal_execute_bulk over the real MCP wire and close mutation gaps

- Drive the tool through the real stdio MCP server: hidden until the
  terminal_bulk toolset is loaded, schema shape, JSON result, Error text
  with isError, schema rejection of a native array, and privacy masking
  of the grouped result with token restoration in the command.
- Mutation testing (18 deliberate breakages of the safety-critical
  lines) left three survivors; add tests that kill two of them: hosts
  differing only in exit code, status, stderr or error never share a
  group, and a session-scoped answer to a fan-out approval does not
  approve later writes from that client.
- Assert that delegated agents cannot reach the fan-out at the gate.

* fix(capabilities): address review findings on terminal_execute_bulk

- Keep the tool MCP-only for now. The in-app agent has no completed-write
  replay for it after a context-compaction retry, and its SDK approval
  gate would stack a second prompt on the bridge's fresh approval. Both
  can follow in a separate change.
- Re-run the transport preflight for every claimed target after the
  approval and before the synchronous start, so a worker session that
  changed while the user was deciding cancels the whole call instead of
  being refused after other hosts have started.
- Never group hosts whose exec layer already dropped part of the output:
  equal retained tails do not prove equal full results.

* fix(capabilities): only report not_sent on explicit evidence and flag capped output

- Classify a host as not_sent only when the exec layer says so (a known
  pre-send code or refusal text). An error with no output and no exit
  code, such as a terminal worker exiting after it typed the command,
  is now reported as error, so a mutating command is never presented as
  safe to retry blindly. SHELL_NOT_READY and EXECUTION_NOT_AUTHORIZED
  are now recognised, so a call where every host refuses fails as
  not sent instead of returning ok.
- Have execViaRawPty and execViaChannel set outputTruncated when they
  stop collecting at their size cap, so hosts that differ only in the
  discarded output are never grouped.

* test(capabilities): run terminal_execute_bulk against the real worker exec handler

Wire the bridge to the production terminal-worker exec handler with fake
shells that speak the wrapper protocol, and cover the grouped result,
Stop while every host is running, and real per-host timeouts.

* fix(capabilities): do not probe hosts before the bulk approval

In confirm mode the preflight ran the shell-kind probe, which opens an
SSH exec channel and runs a remote command, before the approval prompt.
Denying the call (or another target failing) still executed something on
the host, and on an account with a forced command that could trigger it.

- The preflight before the prompt is now read-only: no channel is opened,
  and the safety check uses the shell kind only if it is already known,
  otherwise the shell-independent patterns.
- The full check, including the probe and the shell-aware patterns, runs
  right after approval and before any command is sent, so the call is
  still all-or-nothing. Without a prompt the full check runs first.
- The worker precheck honours the same distinction.

* fix(capabilities): recheck local guards before probing hosts after approval

After the approval the bulk call ran the probing transport pass first and
rechecked cancellation, scope and the privacy policy afterwards. A call
that was no longer authorized (Stop pressed, session out of scope,
privacy settings changed while the prompt was open) was rejected only
after the hosts had already been probed.

Run the local, read-only guards first, then the probing pass, then the
guards again because the pass awaits, and only then take the chat lock
and start. A refusal by the privacy hook now happens before the lock is
taken.

* fix(capabilities): re-read the permission mode and classify exec refusals precisely

- Re-evaluate the live permission mode with the other local guards, both
  before the probing pass and again before the start. Switching to
  observer while a prompt is open (or while hosts are being checked) now
  refuses the call, and a call that needed no approval is refused if the
  mode turns into confirm before it starts.
- Keep the code of an error the exec layer throws, so SHELL_PROMPT_PENDING
  (thrown before anything is written) is reported as not_sent and an
  all-refused call fails as not sent.
- Recognise the executors' real closed-stream messages ("Stream closed
  unexpectedly", "Serial port closed unexpectedly") as connection_lost.
2026-11-25 15:45:53 +08:00

560 lines
21 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");
const { createAiPrivacyService } = require("../shared/aiPrivacyService.cjs");
const {
checkBlocklistForShell,
resolveSessionBlocklistShellKind,
} = require("./ai/commandSafety.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(),
closingTerminalSessions: 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,
SESSION_CLOSE_CLEANUP_TIMEOUT_MS: 20,
DEFAULT_BACKGROUND_JOB_TIMEOUT_MS: 60 * 60 * 1000,
commandTimeoutMs: 5000,
activeSftpOpSeq: 0,
debugLog() {},
getSessionMeta() {
return {};
},
checkCommandSafetyForShell() {
return { blocked: false };
},
resolveSessionBlocklistShellKind() {
return "";
},
beginChatExecution() {
return { ok: true, release() {} };
},
getFreshIdlePrompt() {
return "";
},
echoCommandToSession() {},
validateSessionScope() {
return null;
},
};
Object.assign(ctx, createBackgroundJobApi(ctx));
return ctx;
}
test("SFTP cancellation targets one terminal session and waits for cleanup", async () => {
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs: new Map() });
const events = [];
ctx.registerSftpOp("chat-1", "session-1", async () => {
await nextTick();
events.push("session-1-clean");
});
ctx.registerSftpOp("chat-2", "session-1", () => {
events.push("session-1-other-scope-clean");
});
ctx.registerSftpOp("chat-1", "session-2", () => {
events.push("session-2-clean");
});
await ctx.cancelSftpOpsForTerminalSession("session-1");
assert.deepEqual(events, ["session-1-other-scope-clean", "session-1-clean"]);
assert.equal(ctx.activeSessionSftpOps.size, 1);
});
test("terminal close does not hang on stalled SFTP cleanup", async () => {
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs: new Map() });
ctx.activeSessionSftpOps.set("sftp-stalled", {
chatSessionId: "chat-1",
sessionId: "session-1",
cancel: () => new Promise(() => {}),
});
const startedAt = Date.now();
await ctx.cancelSftpOpsForTerminalSession("session-1");
assert.ok(Date.now() - startedAt < 200, "session close cleanup should be bounded");
assert.equal(ctx.activeSessionSftpOps.size, 0);
});
test("SFTP operations that start while a terminal is closing are cancelled immediately", () => {
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs: new Map() });
let cancelled = false;
ctx.beginTerminalSessionClose("session-1");
ctx.registerSftpOp("chat-1", "session-1", () => {
cancelled = true;
});
assert.equal(cancelled, true);
assert.equal(ctx.activeSessionSftpOps.size, 0);
ctx.endTerminalSessionClose("session-1");
});
test("overlapping closes keep SFTP blocked until the last close finishes", () => {
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs: new Map() });
ctx.beginTerminalSessionClose("session-1");
ctx.beginTerminalSessionClose("session-1");
ctx.endTerminalSessionClose("session-1");
let cancelled = false;
ctx.registerSftpOp("chat-1", "session-1", () => {
cancelled = true;
});
assert.equal(cancelled, true);
ctx.endTerminalSessionClose("session-1");
ctx.registerSftpOp("chat-1", "session-1", () => {});
assert.equal(ctx.activeSessionSftpOps.size, 1);
});
test("terminal close cancels and removes background jobs for that terminal", async () => {
let cancelCount = 0;
let settleJob;
const resultPromise = new Promise((resolve) => {
settleJob = resolve;
});
const backgroundJobs = new Map([
["job-1", {
sessionId: "session-1",
status: "running",
handle: {
cancel: () => { cancelCount += 1; },
resultPromise,
},
}],
["job-2", { sessionId: "session-2", status: "running", handle: {} }],
]);
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs });
ctx.activeSessionExecutions.set("session-1", { kind: "job", token: "token-1" });
ctx.cancelBackgroundJobsForTerminalSession("session-1");
assert.equal(cancelCount, 1);
assert.equal(backgroundJobs.get("job-1").status, "stopping");
const settling = ctx.settleBackgroundJobsForTerminalSession("session-1");
assert.equal(backgroundJobs.has("job-1"), true);
settleJob({ error: "Cancelled" });
await settling;
assert.equal(backgroundJobs.has("job-1"), false);
assert.equal(backgroundJobs.has("job-2"), true);
assert.equal(ctx.activeSessionExecutions.has("session-1"), false);
});
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);
});
test("MCP exec probes an unclassified PowerShell session before the authoritative check", async () => {
const pty = new FakePty();
const session = {
protocol: "ssh",
stream: pty,
shellKind: "",
remoteSshVersion: "OpenSSH_for_Windows_9.5",
lastIdlePrompt: "custom% ",
_promptTrackTail: "custom prompt\r\ncustom% ",
_shellKindExecProbe: async () => (
"DefaultShell REG_SZ C:\\Program Files\\PowerShell\\7\\pwsh.exe\r\n"
),
};
const ctx = createExecHandlerTestContext({
sessions: new Map([["ssh-powershell", session]]),
backgroundJobs: new Map(),
});
ctx.checkCommandSafetyForShell = checkBlocklistForShell;
ctx.resolveSessionBlocklistShellKind = resolveSessionBlocklistShellKind;
ctx.execViaPty = async () => ({ ok: true, stdout: "ok", stderr: "", exitCode: 0 });
const api = createExecHandlerApi(ctx);
const result = await api.handleExec({
sessionId: "ssh-powershell",
command: 'Write-Host "now: $(Get-Date)"',
chatSessionId: "chat-powershell",
});
assert.equal(result.ok, true);
assert.equal(session._loginShellKind, "powershell");
});
for (const route of ["pty", "channel", "job"]) {
test(`MCP ${route} rechecks privacy after shell probing before command handoff`, async () => {
const privacy = createAiPrivacyService();
privacy.checkSession("chat");
const deferred = createDeferredShellProbeConn();
const session = { protocol: "ssh", conn: deferred.conn };
if (route !== "channel") session.stream = new FakePty();
const ctx = createExecHandlerTestContext({
sessions: new Map([["ssh", session]]),
backgroundJobs: new Map(),
});
const effects = [];
ctx.execViaPty = (...args) => { effects.push(args); return { ok: true }; };
ctx.execViaChannel = (...args) => { effects.push(args); return { ok: true }; };
ctx.startPtyJob = (...args) => { effects.push(args); return { resultPromise: Promise.resolve({}) }; };
const api = createExecHandlerApi(ctx);
const handler = route === "job" ? api.handleJobStart : api.handleExec;
const pending = handler({
sessionId: "ssh", command: "echo synthetic", chatSessionId: "chat",
}, { beforeExecute: () => privacy.restore("chat", []) });
await nextTick();
privacy.configure({ enabled: true });
deferred.release();
const result = await Promise.resolve(pending).catch((error) => ({ ok: false, error: error.message }));
assert.equal(result.ok, false);
assert.match(result.error, /start a new chat/);
assert.deepEqual(effects, []);
assert.equal(ctx.activeSessionExecutions.size, 0);
});
}
test("expired local and unknown jobs do not claim a lost worker route", (t) => {
const original = process.env.NETCATTY_JOB_DIAG;
process.env.NETCATTY_JOB_DIAG = "1";
t.after(() => {
if (original === undefined) delete process.env.NETCATTY_JOB_DIAG;
else process.env.NETCATTY_JOB_DIAG = original;
});
const events = [];
t.mock.method(console, "info", (line) => {
events.push(JSON.parse(line.slice("[Netcatty JobDiag] ".length)));
});
const jobs = new Map([["local-expired", {
status: "completed", updatedAt: Date.now() - 20 * 60 * 1000,
chatSessionId: "owner",
}], ["local-scoped", { status: "running", chatSessionId: "owner" }]]);
const ctx = createExecHandlerTestContext({ sessions: new Map(), backgroundJobs: jobs });
const api = createExecHandlerApi(ctx);
ctx.pruneCompletedBackgroundJobs();
assert.equal(jobs.has("local-expired"), false);
for (const jobId of ["local-expired", "unknown"]) {
assert.equal(api.handleJobPoll({ jobId }).ok, false);
assert.equal(api.handleJobStop({ jobId }).ok, false);
}
api.handleJobPoll({ jobId: "local-scoped", chatSessionId: "other" });
assert.deepEqual(events.map(({ reason }) => reason), [
"job-missing", "job-missing", "job-missing", "job-missing", "scope-mismatch",
]);
});
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();
const session = { protocol: "local", pty, shellKind: "posix", _promptTrackTail: "" };
const ctx = createExecHandlerTestContext({
sessions: new Map([["not-ready", session]]), backgroundJobs: new Map(),
});
ctx.startPtyJob = require("./ai/ptyExec.cjs").startPtyJob;
const api = createExecHandlerApi(ctx);
const started = await api.handleJobStart({
sessionId: "not-ready", chatSessionId: "readiness-chat", command: "echo must-not-run",
});
assert.equal(started.ok, true);
t.mock.timers.tick(30001);
await nextTick();
const polled = api.handleJobPoll({ jobId: started.jobId, chatSessionId: "readiness-chat" });
assert.equal(polled.status, "failed");
assert.equal(polled.completed, true);
// #4195: a live shell whose prompt was never recognized is an actionable
// unknown, not a terminal SHELL_NOT_READY. The command is still never sent.
assert.equal(polled.code, "SHELL_READINESS_UNKNOWN");
assert.equal(ctx.activeSessionExecutions.size, 0);
assert.deepEqual(pty.writes, []);
ctx.getFreshIdlePrompt = () => "user@host:~$ ";
t.mock.timers.tick(1000);
assert.deepEqual(pty.writes, [], "late readiness must not deliver the failed job");
});
for (const route of ['exec', 'job']) {
test(`MCP ${route} revalidates privacy when the awaited prompt becomes ready`, async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const privacy = createAiPrivacyService();
privacy.checkSession('readiness-chat');
const pty = new FakePty();
const session = { protocol: 'local', pty, shellKind: 'posix', _promptTrackTail: '' };
const ctx = createExecHandlerTestContext({
sessions: new Map([['waiting', session]]), backgroundJobs: new Map(),
});
let prompt = '';
ctx.getFreshIdlePrompt = () => prompt;
Object.assign(ctx, require('./ai/ptyExec.cjs'));
const api = createExecHandlerApi(ctx);
const pending = (route === 'job' ? api.handleJobStart : api.handleExec)({
sessionId: 'waiting', chatSessionId: 'readiness-chat', command: 'echo forbidden',
}, { beforeExecute: () => privacy.restore('readiness-chat', []) });
await nextTick();
assert.deepEqual(pty.writes, []);
privacy.configure({ enabled: true });
prompt = 'user@host:~$ ';
t.mock.timers.tick(50);
await nextTick();
// Also clean up on the old implementation, where a probe was already sent.
pty.emit('close');
const startedOrFinished = await pending;
const result = route === 'job'
? api.handleJobPoll({ jobId: startedOrFinished.jobId, chatSessionId: 'readiness-chat' })
: startedOrFinished;
assert.deepEqual(pty.writes, [], 'retired privacy session must not send even probe/control bytes');
assert.match(result.error, /start a new chat/);
assert.equal(ctx.activeSessionExecutions.size, 0);
});
}
// ── terminal_execute_bulk support: preflightExec + shared chat lock ──
function createBulkExecContext(sessions, overrides = {}) {
const ctx = createExecHandlerTestContext({ sessions, backgroundJobs: new Map() });
ctx.checkCommandSafetyForShell = checkBlocklistForShell;
ctx.resolveSessionBlocklistShellKind = resolveSessionBlocklistShellKind;
ctx.execViaPty = async () => ({ ok: true, stdout: "ran", stderr: "", exitCode: 0 });
ctx.execViaChannel = async () => ({ ok: true, stdout: "ran", stderr: "", exitCode: 0 });
ctx.execViaRawPty = async () => ({ ok: true, stdout: "ran", stderr: "", exitCode: null });
Object.assign(ctx, overrides);
return createExecHandlerApi(ctx);
}
test("preflightExec accepts supported transports without sending a command", async () => {
const pty = new FakePty();
const sessions = new Map([
["pty", { protocol: "ssh", shellKind: "posix", stream: pty }],
["channel", { protocol: "ssh", shellKind: "posix", conn: { exec() {} } }],
// Serial sessions are network-device-like and expose their port as `stream`.
["serial", { protocol: "serial", stream: { write() {} }, serialPort: { write() {} } }],
]);
const api = createBulkExecContext(sessions);
for (const sessionId of sessions.keys()) {
const result = await api.preflightExec({ sessionId, command: "uptime", chatSessionId: "chat" });
assert.deepEqual(result, { ok: true }, sessionId);
}
assert.deepEqual(pty.writes, [], "preflight never types into the terminal");
});
test("preflightExec reports the same refusals handleExec would give", async () => {
const sessions = new Map([
["blocked", { protocol: "ssh", shellKind: "posix", stream: new FakePty() }],
["dead", { protocol: "ssh", shellKind: "posix" }],
["net-no-pty", { protocol: "ssh", conn: { exec() {} } }],
]);
const api = createBulkExecContext(sessions, {
getSessionMeta: (sessionId) => (sessionId === "net-no-pty" ? { deviceType: "network" } : {}),
});
const blocked = await api.preflightExec({ sessionId: "blocked", command: "rm -rf /", chatSessionId: "chat" });
assert.equal(blocked.ok, false);
assert.match(blocked.error, /^Command blocked by safety policy\. Pattern: /);
assert.deepEqual(
await api.preflightExec({ sessionId: "dead", command: "uptime", chatSessionId: "chat" }),
{ ok: false, error: "Session does not support command execution" },
);
assert.match(
(await api.preflightExec({ sessionId: "net-no-pty", command: "uptime", chatSessionId: "chat" })).error,
/no writable PTY stream/,
);
assert.deepEqual(
await api.preflightExec({ sessionId: "ghost", command: "uptime", chatSessionId: "chat" }),
{ ok: false, error: "Session not found" },
);
});
test("preflightExec skips the blocklist for serial and network-device sessions like handleExec", async () => {
const sessions = new Map([
["serial", { protocol: "serial", stream: { write() {} }, serialPort: { write() {} } }],
["net", { protocol: "ssh", stream: new FakePty() }],
]);
const api = createBulkExecContext(sessions, {
getSessionMeta: (sessionId) => (sessionId === "net" ? { deviceType: "network" } : {}),
});
for (const sessionId of ["serial", "net"]) {
assert.deepEqual(
await api.preflightExec({ sessionId, command: "shutdown", chatSessionId: "chat" }),
{ ok: true },
sessionId,
);
}
});
test("handleExec takes the chat lock unless the bulk executor already holds it", async () => {
const { CHAT_LOCK_HELD } = require("./mcpServerBridge/execBulk.cjs");
const locks = [];
const make = () => createBulkExecContext(
new Map([["ssh", { protocol: "ssh", shellKind: "posix", stream: new FakePty() }]]),
{ beginChatExecution: (...args) => { locks.push(args); return { ok: true, release() {} }; } },
);
await make().handleExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" });
assert.equal(locks.length, 1, "single exec takes the lock");
locks.length = 0;
await make().handleExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" }, { [CHAT_LOCK_HELD]: true });
assert.equal(locks.length, 0, "bulk-held lock is not taken twice");
locks.length = 0;
// A plain object key with the same text is not the private marker.
await make().handleExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" }, { chatLockHeld: true });
assert.equal(locks.length, 1);
});
test("preflightExec with probe:false never opens a channel to the host and uses the common patterns", async () => {
const make = (session, overrides = {}) => createBulkExecContext(new Map([["ssh", session]]), {
checkCommandSafetyCommonOnly: (command) => (command.includes("forbidden")
? { blocked: true, matchedPattern: "forbidden" } : { blocked: false }),
...overrides,
});
const unknownShell = () => {
const calls = { probe: 0, exec: 0 };
const session = {
protocol: "ssh", shellKind: "", stream: new FakePty(),
_shellKindExecProbe: async () => { calls.probe += 1; return "/bin/bash\n"; },
conn: { exec() { calls.exec += 1; } },
};
return { session, calls };
};
const quiet = unknownShell();
const api = make(quiet.session);
assert.deepEqual(await api.preflightExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" }, { probe: false }), { ok: true });
assert.deepEqual(quiet.calls, { probe: 0, exec: 0 }, "no probe and no SSH channel before approval");
assert.match(
(await api.preflightExec({ sessionId: "ssh", command: "echo forbidden", chatSessionId: "chat" }, { probe: false })).error,
/Command blocked by safety policy\. Pattern: forbidden/,
"unknown shell falls back to the shell-independent patterns",
);
const loud = unknownShell();
const full = make(loud.session);
await full.preflightExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" });
const probesAfterFirst = loud.calls.probe;
assert.ok(probesAfterFirst >= 1, "the default (after approval) still probes the shell kind");
await full.preflightExec({ sessionId: "ssh", command: "uptime", chatSessionId: "chat" });
assert.equal(loud.calls.probe, probesAfterFirst, "the result is cached, so the later exec does not probe again");
});