Files
Netcatty/electron/terminalWorker/aiExec.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

801 lines
28 KiB
JavaScript

"use strict";
const assert = require("node:assert/strict");
const { EventEmitter } = require("node:events");
const { Duplex } = require("node:stream");
const test = require("node:test");
const { setRendererFlowPaused, clearSessionFlowState } = require("../bridges/terminalFlowAck.cjs");
const {
createWorkerAiJobStartHandler,
registerWorkerAiExecHandlers,
} = require("./aiExec.cjs");
const { PROBE_OUTPUT_MARKER } = require("../bridges/ai/sessionShellKind.cjs");
const { trackSessionIdlePrompt } = require("../bridges/ai/shellUtils.cjs");
test("worker SSH exec waits for a slow interactive shell prompt before any PTY write", async () => {
const pty = new FakePty();
const session = { protocol: 'ssh', stream: pty, shellKind: 'posix', _promptTrackTail: '', lastIdlePrompt: '' };
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([['slow-ssh', session]]) });
const pending = ipcMain.handlers.get('netcatty:ai:exec')(createFakeEvent(), {
sessionId: 'slow-ssh', chatSessionId: 'slow-ssh-chat', command: 'echo ready', commandTimeoutMs: 2000,
});
await new Promise(resolve => setTimeout(resolve, 25));
assert.deepEqual(pty.writes, []);
trackSessionIdlePrompt(session, 'user@host:~$ ');
const marker = await extractMarker(pty.writes);
pty.emit('data', `${marker}_S\nready\n${marker}_E:0\n`);
assert.equal((await pending).stdout, 'ready');
});
test("worker shell readiness route reports prompt state read-only", () => {
const session = { protocol: 'ssh', stream: new FakePty(), shellKind: 'posix', _promptTrackTail: '', lastIdlePrompt: '' };
trackSessionIdlePrompt(session, 'root@host:~# ');
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([['ssh-1', session]]) });
const handler = ipcMain.handlers.get('netcatty:ai:shellReadiness');
const ready = handler(createFakeEvent(), { sessionId: 'ssh-1' });
assert.deepEqual(ready, {
ok: true,
found: true,
trackedShell: true,
freshIdlePrompt: 'root@host:~# ',
visibleIdlePrompt: 'root@host:~# ',
});
assert.deepEqual(session.stream.writes, [], "readiness probe must never write to the PTY");
assert.deepEqual(handler(createFakeEvent(), { sessionId: 'gone' }), { ok: true, found: false });
});
class FakePty extends EventEmitter {
constructor() {
super();
this.writes = [];
}
write(data) {
this.writes.push(String(data));
const input = this.writes.join("");
if (!this.probeReplied && input.includes("command sh -c") && input.endsWith("_Q'\n")) {
this.probeReplied = true;
const marker = input.match(/(__NCMCP_[A-Za-z0-9_]+__)/)[1];
queueMicrotask(() => this.emit("data", `${marker}_P:\n${marker}_Q`));
}
}
}
function createFakeIpcMain() {
const handlers = new Map();
const listeners = new Map();
return {
handlers,
listeners,
handle(channel, handler) {
handlers.set(channel, handler);
},
on(channel, listener) {
listeners.set(channel, listener);
},
};
}
function createFakeEvent() {
const rendererMessages = [];
return {
rendererMessages,
sender: {
send(channel, payload) {
rendererMessages.push({ channel, payload });
},
},
};
}
async function waitForWrapper(writes) {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const input = writes.join("");
const wrapper = input.slice(input.lastIndexOf("\x0b\x15"));
if (wrapper.includes("_cmd") && wrapper.includes("_E:") && wrapper.endsWith("\n") && !wrapper.endsWith("\\\n")) return wrapper;
await new Promise(resolve => setTimeout(resolve, 10));
}
assert.fail("expected complete wrapped command to be written to the PTY");
}
async function extractMarker(writes) {
const wrapper = await waitForWrapper(writes);
const match = wrapper.match(/(__NCMCP_[A-Za-z0-9_]+__)/);
assert.ok(match, "expected command wrapper to contain an MCP marker");
return match[1];
}
function nextTick() {
return new Promise((resolve) => setImmediate(resolve));
}
for (const channel of ["netcatty:ai:exec", "netcatty:ai:jobStart"]) {
test(`${channel} stays cancellable while main validates execution`, async () => {
const pty = new FakePty();
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, {
sessions: new Map([["session", { protocol: "ssh", stream: pty, shellKind: "posix" }]]),
});
let validationEntered;
let allowExecution;
const entered = new Promise(resolve => { validationEntered = resolve; });
const validation = new Promise(resolve => { allowExecution = resolve; });
const event = {
...createFakeEvent(),
beforeExecute: async () => {
validationEntered();
await validation;
},
};
const pending = ipcMain.handlers.get(channel)(event, {
sessionId: "session", command: "echo synthetic", chatSessionId: "chat-validation",
});
await entered;
ipcMain.listeners.get("netcatty:ai:catty:cancel")(event, { chatSessionId: "chat-validation" });
allowExecution();
const result = await pending;
assert.equal(result.ok, false);
assert.equal(result.error, "Cancelled");
assert.deepEqual(pty.writes, []);
});
}
test("worker job stop receives cancellation output while renderer flow is paused", async () => {
class PausablePty extends Duplex {
constructor() { super(); this.writes = []; }
_read() {}
_write(chunk, _encoding, done) {
const text = chunk.toString();
this.writes.push(text);
if (text === "\x03") {
this.push(`${this.marker}_E:130\r\nroot@test:~# `);
} else {
const input = this.writes.join("");
if (!this.probeReplied && input.includes("command sh -c") && input.endsWith("_Q'\n")) {
this.probeReplied = true;
this.marker = input.match(/(__NCMCP_[A-Za-z0-9_]+__)/)[1];
this.push(`${this.marker}_P:\n${this.marker}_Q`);
}
}
done();
}
}
const pty = new PausablePty();
const session = { protocol: "ssh", stream: pty, shellKind: "posix" };
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([["ssh-paused", session]]) });
const event = createFakeEvent();
const started = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-paused", command: "sleep 60", chatSessionId: "chat-paused",
});
const marker = await extractMarker(pty.writes);
pty.push(`${marker}_S\r\nstarted\r\n`);
await nextTick();
setRendererFlowPaused(session, true);
assert.equal(pty.isPaused(), true);
try {
await ipcMain.handlers.get("netcatty:ai:jobStop")(event, {
jobId: started.jobId, chatSessionId: "chat-paused",
});
await nextTick();
const polled = await ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
jobId: started.jobId, chatSessionId: "chat-paused",
});
assert.equal(polled.status, "cancelled");
assert.equal(polled.completed, true);
assert.equal(polled.error, "Cancelled");
assert.equal(pty.writes.filter(data => data === "\x03").length, 1);
} finally {
clearSessionFlowState(session);
await nextTick();
pty.destroy();
}
});
function createShellProbeConn(stdout = `${PROBE_OUTPUT_MARKER}/usr/bin/fish\n`) {
const conn = {
exec(_command, callback) {
const stream = new EventEmitter();
stream.stderr = new EventEmitter();
stream.close = () => stream.emit("close");
queueMicrotask(() => {
callback(null, stream);
queueMicrotask(() => {
stream.emit("data", Buffer.from(stdout));
stream.emit("close");
});
});
},
};
return conn;
}
function createDeferredShellProbeConn(stdout = `${PROBE_OUTPUT_MARKER}/usr/bin/fish\n`) {
let execCallback;
const conn = {
exec(_command, callback) {
execCallback = callback;
},
};
return {
conn,
release() {
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");
});
},
};
}
test("worker AI background jobs start, poll, stop, and block overlapping exec", async () => {
const pty = new FakePty();
const sessions = new Map([
["ssh-1", {
protocol: "ssh",
stream: pty,
shellKind: "posix",
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
assert.equal(typeof ipcMain.handlers.get("netcatty:ai:jobStart"), "function");
assert.equal(typeof ipcMain.handlers.get("netcatty:ai:jobPoll"), "function");
assert.equal(typeof ipcMain.handlers.get("netcatty:ai:jobStop"), "function");
const event = createFakeEvent();
const started = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-1",
command: "npm test",
chatSessionId: "chat-1",
commandTimeoutMs: 5000,
});
assert.equal(started.ok, true);
assert.equal(started.sessionId, "ssh-1");
assert.equal(started.command, "npm test");
assert.equal(started.status, "running");
assert.equal(started.outputMode, "foreground-mirrored");
const marker = await extractMarker(pty.writes);
assert.deepEqual(event.rendererMessages, [
{
channel: "netcatty:data",
payload: {
sessionId: "ssh-1",
data: "npm test\r\n",
syntheticEcho: true,
},
},
{
channel: "netcatty:data",
payload: {
sessionId: "ssh-1",
data: `${marker}_I\n`,
},
},
]);
pty.emit("data", `${marker}_S\r\nready\r\n`);
await nextTick();
const polled = await ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
jobId: started.jobId,
offset: 0,
chatSessionId: "chat-1",
});
assert.equal(polled.ok, true);
assert.equal(polled.completed, false);
assert.equal(polled.output, "ready\n");
assert.equal(polled.nextOffset, "ready\n".length);
const busy = await ipcMain.handlers.get("netcatty:ai:exec")(event, {
sessionId: "ssh-1",
command: "pwd",
chatSessionId: "chat-1",
});
assert.equal(busy.ok, false);
assert.match(busy.error, /already has a long-running command in progress/);
const stopped = await ipcMain.handlers.get("netcatty:ai:jobStop")(event, {
jobId: started.jobId,
chatSessionId: "chat-1",
});
assert.equal(stopped.ok, true);
assert.equal(stopped.status, "stopping");
assert.ok(pty.writes.includes("\x03"), "expected stop to send Ctrl+C to the PTY");
pty.emit("data", `${marker}_E:130\r\n`);
await nextTick();
const cancelled = await ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
jobId: started.jobId,
offset: 0,
chatSessionId: "chat-1",
});
assert.equal(cancelled.status, "cancelled");
assert.equal(cancelled.completed, true);
assert.equal(cancelled.error, "Cancelled");
});
test("worker chat cancellation stops matching background jobs", async () => {
const pty = new FakePty();
const sessions = new Map([
["ssh-1", {
protocol: "ssh",
stream: pty,
shellKind: "posix",
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const started = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-1",
command: "sleep 30",
chatSessionId: "chat-1",
commandTimeoutMs: 5000,
});
const marker = await extractMarker(pty.writes);
pty.emit("data", `${marker}_S\r\nrunning\r\n`);
await nextTick();
ipcMain.listeners.get("netcatty:ai:catty:cancel")(event, {
chatSessionId: "chat-1",
});
assert.ok(pty.writes.includes("\x03"), "expected chat cancellation to send Ctrl+C to the background job");
const stopping = await ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
jobId: started.jobId,
offset: 0,
chatSessionId: "chat-1",
});
assert.equal(stopping.status, "stopping");
assert.equal(stopping.error, "Cancellation requested");
pty.emit("data", `${marker}_E:130\r\n`);
await nextTick();
const cancelled = await ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
jobId: started.jobId,
offset: 0,
chatSessionId: "chat-1",
});
assert.equal(cancelled.status, "cancelled");
assert.equal(cancelled.completed, true);
});
test("worker background job probes unset remote shellKind before wrapping", async () => {
const pty = new FakePty();
const sessions = new Map([
["ssh-fish", {
protocol: "ssh",
stream: pty,
conn: createShellProbeConn(),
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const started = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-fish",
command: "echo fish",
chatSessionId: "chat-1",
commandTimeoutMs: 5000,
});
assert.equal(started.ok, true);
// Login fish is a soft hint (not pinned); wrapper should be fish-native.
assert.equal(sessions.get("ssh-fish").shellKind, undefined);
assert.equal(sessions.get("ssh-fish")._loginShellKind, "fish");
const wrapper = await waitForWrapper(pty.writes);
assert.match(wrapper, /set -l __NCMCP_.*_cmd/);
assert.doesNotMatch(wrapper, / sh -c '/);
const marker = await extractMarker(pty.writes);
pty.emit("data", `${marker}_S\r\n${marker}_E:0\r\n`);
await nextTick();
});
test("worker background job reserves the session while shellKind probe is pending", async () => {
const pty = new FakePty();
const deferred = createDeferredShellProbeConn();
const sessions = new Map([
["ssh-fish", {
protocol: "ssh",
stream: pty,
conn: deferred.conn,
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const firstStart = ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-fish",
command: "sleep 1",
chatSessionId: "chat-1",
commandTimeoutMs: 5000,
});
await nextTick();
const second = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-fish",
command: "pwd",
chatSessionId: "chat-1",
commandTimeoutMs: 5000,
});
assert.equal(second.ok, false);
assert.match(second.error, /already has a long-running command in progress/);
deferred.release();
const first = await firstStart;
assert.equal(first.ok, true);
const marker = await extractMarker(pty.writes);
pty.emit("data", `${marker}_S\r\n${marker}_E:0\r\n`);
await nextTick();
});
test("worker chat cancel during shellKind probe aborts job start before PTY write", async () => {
// Codex P2 on #2061: first jobStart on an unprobed remote session awaits
// ensureSessionShellKind with no backgroundJobs entry historically, so
// catty:cancel missed it and the command was still typed after the probe.
const pty = new FakePty();
const deferred = createDeferredShellProbeConn();
const sessions = new Map([
["ssh-fish", {
protocol: "ssh",
stream: pty,
conn: deferred.conn,
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const pendingStart = ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
sessionId: "ssh-fish",
command: "sleep 999",
chatSessionId: "chat-cancel-probe",
commandTimeoutMs: 5000,
});
await nextTick();
// Cancel while the shell probe is still in-flight.
ipcMain.listeners.get("netcatty:ai:catty:cancel")(event, {
chatSessionId: "chat-cancel-probe",
});
deferred.release();
const started = await pendingStart;
assert.equal(started.ok, false);
assert.equal(started.error, "Cancelled");
assert.equal(
pty.writes.filter((entry) => entry.includes("__NCMCP_") && !entry.includes("command sh -c")).length,
0,
"cancelled pending start must not type a wrapper into the PTY",
);
});
test("worker exec keeps shell-selected defaults: powershell frees $(), dangerous PS commands blocked", async () => {
const pty = new FakePty();
const sessions = new Map([
["ps-1", {
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 ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const exec = ipcMain.handlers.get("netcatty:ai:exec");
// PowerShell subexpression syntax on a PowerShell session is legal: the
// command must pass the worker blocklist and reach the PTY wrapper.
const allowedPromise = exec(event, {
sessionId: "ps-1",
command: 'Write-Host "now: $(Get-Date)"',
chatSessionId: "chat-ps",
commandTimeoutMs: 300,
});
await nextTick();
assert.ok(
pty.writes.some((entry) => entry.includes("__NCMCP_") && !entry.includes("command sh -c")),
"expected the unblocked command to reach the PTY",
);
await allowedPromise.catch(() => {});
// PowerShell-native destructive commands are blocked by the new group.
const blocked = await exec(event, {
sessionId: "ps-1",
command: "Remove-Item -Recurse -Force C:\\important",
chatSessionId: "chat-ps",
commandTimeoutMs: 5000,
});
assert.equal(blocked.ok, false);
assert.match(blocked.error, /Command blocked by safety policy/);
assert.equal(blocked.error.includes("Remove-Item"), true);
});
test("worker exec honors an explicitly empty configured blocklist", async () => {
const pty = new FakePty();
const sessions = new Map([
["posix-no-blocklist", {
protocol: "ssh",
stream: pty,
shellKind: "posix",
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const execution = ipcMain.handlers.get("netcatty:ai:exec")(createFakeEvent(), {
sessionId: "posix-no-blocklist",
command: "rm -rf /tmp/test-only",
chatSessionId: "chat-no-blocklist",
commandTimeoutMs: 300,
commandBlocklist: [],
});
await nextTick();
assert.ok(
pty.writes.some((entry) => entry.includes("__NCMCP_") && !entry.includes("command sh -c")),
"disabled defaults must allow the command to reach the PTY wrapper",
);
await execution.catch(() => {});
});
test("worker background job probes before blocking a first PowerShell command", async () => {
const pty = new FakePty();
const sessions = new Map([
["ps-danger-first", {
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 backgroundJobs = new Map();
const activeSessionJobs = new Map();
const start = createWorkerAiJobStartHandler({
sessions,
backgroundJobs,
activeSessionJobs,
});
const result = await start(createFakeEvent(), {
sessionId: "ps-danger-first",
command: "Remove-Item -Recurse -Force C:\\important",
chatSessionId: "chat-ps-danger",
});
assert.equal(result.ok, false);
assert.match(result.error, /Command blocked by safety policy/);
assert.equal(pty.writes.length, 0);
assert.equal(backgroundJobs.size, 0);
assert.equal(activeSessionJobs.size, 0);
});
test("worker exec on an unclassified posix session still blocks command substitution", async () => {
const pty = new FakePty();
const sessions = new Map([
["ssh-posix", {
protocol: "ssh",
stream: pty,
shellKind: "posix",
}],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const event = createFakeEvent();
const blocked = await ipcMain.handlers.get("netcatty:ai:exec")(event, {
sessionId: "ssh-posix",
command: "echo $(whoami)",
chatSessionId: "chat-posix",
commandTimeoutMs: 5000,
});
assert.equal(blocked.ok, false);
assert.match(blocked.error, /Command blocked by safety policy/);
assert.equal(
pty.writes.filter((entry) => entry.includes("__NCMCP_") && !entry.includes("command sh -c")).length,
0,
"blocked commands must not reach the PTY",
);
});
test("single-channel worker exec does not open an exec channel or send line-kill keys", async () => {
let execCalls = 0;
const pty = new FakePty();
const sessions = new Map([["ssh-single", {
protocol: "ssh",
singleChannelSsh: true,
remoteSshVersion: "CLOUDBILITY-4.14",
stream: pty,
shellKind: "",
conn: { exec() { execCalls += 1; throw new Error("exec channel"); } },
}]]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const execution = ipcMain.handlers.get("netcatty:ai:exec")(createFakeEvent(), {
sessionId: "ssh-single",
command: "uname -a",
chatSessionId: "chat-single",
commandTimeoutMs: 300,
});
await new Promise((resolve) => setTimeout(resolve, 80));
assert.equal(execCalls, 0);
const input = pty.writes.join("");
assert.equal(input.includes("\u0015"), false);
assert.equal(input.includes("\u000b"), false);
assert.ok(input.length > 0);
await execution.catch(() => {});
});
test("worker 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: "", lastIdlePrompt: "" };
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([["not-ready", session]]) });
const event = createFakeEvent();
const started = await ipcMain.handlers.get("netcatty:ai:jobStart")(event, {
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 = ipcMain.handlers.get("netcatty:ai:jobPoll")(event, {
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.deepEqual(pty.writes, []);
trackSessionIdlePrompt(session, "user@host:~$ ");
t.mock.timers.tick(1000);
assert.deepEqual(pty.writes, [], "late readiness must not deliver the failed job");
});
for (const channel of ['netcatty:ai:exec', 'netcatty:ai:jobStart']) {
test(`${channel} revalidates privacy after prompt readiness`, async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const privacy = require('../shared/aiPrivacyService.cjs').createAiPrivacyService();
privacy.checkSession('readiness-chat');
const pty = new FakePty();
const session = { protocol: 'local', pty, shellKind: 'posix', _promptTrackTail: '', lastIdlePrompt: '' };
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([['waiting', session]]) });
const event = { ...createFakeEvent(), beforeExecute: async () => privacy.restore('readiness-chat', []) };
const pending = ipcMain.handlers.get(channel)(event, {
sessionId: 'waiting', chatSessionId: 'readiness-chat', command: 'echo forbidden',
});
await nextTick();
assert.deepEqual(pty.writes, []);
privacy.configure({ enabled: true });
trackSessionIdlePrompt(session, 'user@host:~$ ');
t.mock.timers.tick(50);
await nextTick();
pty.emit('close');
const startedOrFinished = await pending;
const result = channel.endsWith('jobStart')
? ipcMain.handlers.get('netcatty:ai:jobPoll')(event, { jobId: startedOrFinished.jobId, chatSessionId: 'readiness-chat' })
: startedOrFinished;
assert.deepEqual(pty.writes, []);
assert.equal(result.code, 'EXECUTION_NOT_AUTHORIZED');
assert.match(result.error, /start a new chat/);
});
}
test("worker exec precheck runs the deterministic checks and never touches the terminal", async () => {
const pty = new FakePty();
const sessions = new Map([
["ssh", { protocol: "ssh", stream: pty, shellKind: "posix", _promptTrackTail: "", lastIdlePrompt: "" }],
["local-unknown", { protocol: "local", type: "local", stream: new FakePty(), shellKind: "unknown" }],
["no-channel", { protocol: "ssh", shellKind: "posix" }],
]);
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions });
const exec = ipcMain.handlers.get("netcatty:ai:exec");
const precheck = (sessionId, command, extra = {}) => exec(createFakeEvent(), {
sessionId, command, chatSessionId: "chat", commandTimeoutMs: 2000, precheck: true, ...extra,
});
// Passes even though the shell prompt is not ready: readiness is a send-time state.
assert.deepEqual(await precheck("ssh", "uptime"), { ok: true });
assert.match(
(await precheck("ssh", "echo forbidden-word", { commandBlocklist: ["forbidden-word"] })).error,
/^Command blocked by safety policy\. Pattern: /,
);
assert.match((await precheck("local-unknown", "uptime")).error, /AI execution is not supported/);
assert.match((await precheck("no-channel", "uptime")).error, /No terminal stream or SSH client available/);
assert.deepEqual(await precheck("ghost", "uptime"), { ok: false, error: "Session not found" });
assert.deepEqual(pty.writes, [], "a precheck never types into the terminal");
});
test("worker exec:cancel stops only the chat's foreground execs", async () => {
const pty = new FakePty();
const session = { protocol: "ssh", stream: pty, shellKind: "posix", _promptTrackTail: "", lastIdlePrompt: "" };
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([["ssh", session]]) });
const pending = ipcMain.handlers.get("netcatty:ai:exec")(createFakeEvent(), {
sessionId: "ssh", chatSessionId: "chat-a", command: "echo hi", commandTimeoutMs: 5000,
});
await new Promise((resolve) => setTimeout(resolve, 25));
const cancel = ipcMain.listeners?.get?.("netcatty:ai:exec:cancel") || ipcMain.handlers.get("netcatty:ai:exec:cancel");
assert.equal(typeof cancel, "function", "exec:cancel is registered");
cancel(createFakeEvent(), { chatSessionId: "other-chat" });
let settled = false;
pending.then(() => { settled = true; });
await new Promise((resolve) => setTimeout(resolve, 25));
assert.equal(settled, false, "another chat's cancel is ignored");
cancel(createFakeEvent(), { chatSessionId: "chat-a" });
const result = await pending;
assert.equal(result.ok, false);
assert.match(result.error, /cancel/i);
assert.deepEqual(pty.writes, []);
});
test("worker precheck with probe:false opens no channel to the host; the full precheck still probes", async () => {
const make = () => {
const calls = { probe: 0 };
const session = {
protocol: "ssh", shellKind: "", stream: new FakePty(), _promptTrackTail: "", lastIdlePrompt: "",
_shellKindExecProbe: async () => { calls.probe += 1; return "/bin/bash\n"; },
};
const ipcMain = createFakeIpcMain();
registerWorkerAiExecHandlers(ipcMain, { sessions: new Map([["ssh", session]]) });
return { calls, session, exec: (extra) => ipcMain.handlers.get("netcatty:ai:exec")(createFakeEvent(), {
sessionId: "ssh", command: "uptime", chatSessionId: "chat", commandTimeoutMs: 2000, precheck: true, ...extra,
}) };
};
const light = make();
assert.deepEqual(await light.exec({ probe: false }), { ok: true });
assert.equal(light.calls.probe, 0, "no remote command before approval");
assert.match(
(await light.exec({ probe: false, command: "echo forbidden-word", commandBlocklist: ["forbidden-word"] })).error,
/^Command blocked by safety policy\. Pattern: /,
"user patterns still apply without probing",
);
assert.equal(light.calls.probe, 0);
assert.deepEqual(light.session.stream.writes, []);
const full = make();
assert.deepEqual(await full.exec({}), { ok: true });
const probesAfterFirst = full.calls.probe;
assert.ok(probesAfterFirst >= 1, "after approval the shell kind is probed as for any exec");
assert.deepEqual(await full.exec({}), { ok: true });
assert.equal(full.calls.probe, probesAfterFirst, "the result is cached for the real exec");
});