mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 19:07:17 +00:00
* 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.
428 lines
19 KiB
JavaScript
428 lines
19 KiB
JavaScript
"use strict";
|
|
|
|
require("./cliDiscoveryTestIsolation.cjs").isolateCliDiscoveryFile();
|
|
|
|
const assert = require("node:assert/strict");
|
|
const { EventEmitter } = require("node:events");
|
|
const test = require("node:test");
|
|
|
|
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
|
|
|
function loadFreshBridge() {
|
|
const bridgePath = require.resolve("./mcpServerBridge.cjs");
|
|
delete require.cache[bridgePath];
|
|
return require("./mcpServerBridge.cjs");
|
|
}
|
|
|
|
function deferred() {
|
|
let resolve;
|
|
const promise = new Promise((res) => { resolve = res; });
|
|
return { promise, resolve };
|
|
}
|
|
|
|
/**
|
|
* Bridge wired to a fake terminal worker that hosts the given sessions.
|
|
* `reply(sessionId)` may return a result or a promise.
|
|
*/
|
|
function createBridge({ sessionIds = ["ssh-1", "ssh-2", "ssh-3"], reply, refuse, chat = "chat-1", mode = "auto" } = {}) {
|
|
const workerRequests = [];
|
|
const prechecks = [];
|
|
const workerMessages = [];
|
|
const bridge = loadFreshBridge();
|
|
bridge.init({
|
|
sessions: new Map(),
|
|
electronModule: null,
|
|
terminalWorkerManager: {
|
|
send(channel, payload) {
|
|
workerMessages.push({ channel, payload });
|
|
},
|
|
request(channel, payload) {
|
|
if (channel !== "netcatty:ai:exec") return Promise.reject(new Error(`unexpected worker request: ${channel}`));
|
|
if (payload.precheck === true) {
|
|
prechecks.push(payload);
|
|
const error = refuse?.(payload.sessionId, payload);
|
|
return Promise.resolve(error ? { ok: false, error } : { ok: true });
|
|
}
|
|
workerRequests.push({ channel, payload });
|
|
return Promise.resolve(reply ? reply(payload.sessionId, payload) : { ok: true, stdout: `out-${payload.sessionId}\n`, stderr: "", exitCode: 0 });
|
|
},
|
|
},
|
|
});
|
|
bridge.setPermissionMode(mode);
|
|
bridge.setCommandBlocklist([]);
|
|
bridge.setCommandTimeout(30);
|
|
bridge.updateSessionMetadata(
|
|
sessionIds.map((sessionId, index) => ({
|
|
sessionId,
|
|
hostname: `host${index + 1}.example`,
|
|
label: `web${index + 1}`,
|
|
protocol: "ssh",
|
|
connected: true,
|
|
})),
|
|
chat,
|
|
);
|
|
return { bridge, workerRequests, prechecks, workerMessages, chat };
|
|
}
|
|
|
|
function captureApprovals(bridge) {
|
|
const requests = [];
|
|
bridge.setMainWindowGetter(() => ({
|
|
isDestroyed: () => false,
|
|
webContents: {
|
|
id: 1,
|
|
isDestroyed: () => false,
|
|
send(channel, payload) {
|
|
if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload);
|
|
},
|
|
},
|
|
}));
|
|
return requests;
|
|
}
|
|
|
|
const bulkParams = (chatSessionId, overrides = {}) => ({
|
|
command: "uptime",
|
|
sessionIds: '["ssh-1","ssh-2","ssh-3"]',
|
|
chatSessionId,
|
|
...overrides,
|
|
});
|
|
|
|
test("netcatty/execBulk runs one command on every session and groups identical results", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge({
|
|
reply: (sessionId) => ({
|
|
ok: sessionId !== "ssh-3",
|
|
stdout: sessionId === "ssh-3" ? "inactive\n" : "active\n",
|
|
stderr: "",
|
|
exitCode: sessionId === "ssh-3" ? 3 : 0,
|
|
}),
|
|
});
|
|
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
|
|
assert.equal(result.ok, true);
|
|
assert.equal(result.hostCount, 3);
|
|
assert.deepEqual(result.counts, { completed: 3 });
|
|
assert.deepEqual(result.groups, [
|
|
{
|
|
hosts: [{ sessionId: "ssh-1", label: "web1" }, { sessionId: "ssh-2", label: "web2" }],
|
|
status: "completed", exitCode: 0, stdout: "active\n",
|
|
},
|
|
{ hosts: [{ sessionId: "ssh-3", label: "web3" }], status: "completed", exitCode: 3, stdout: "inactive\n" },
|
|
]);
|
|
assert.equal(workerRequests.length, 3);
|
|
for (const request of workerRequests) {
|
|
assert.equal(request.payload.command, "uptime");
|
|
assert.equal(request.payload.commandTimeoutMs, 30000, "every host gets the same timeout");
|
|
assert.equal(request.payload.enforceWallTimeout, true);
|
|
}
|
|
|
|
// The per-chat lock is released afterwards.
|
|
const single = await bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-1", command: "pwd", chatSessionId: chat });
|
|
assert.equal(single.ok, true);
|
|
});
|
|
|
|
test("every host is started before any host finishes", async () => {
|
|
const gates = new Map();
|
|
const { bridge, workerRequests, chat } = createBridge({
|
|
reply: (sessionId) => {
|
|
const gate = deferred();
|
|
gates.set(sessionId, gate);
|
|
return gate.promise;
|
|
},
|
|
});
|
|
const running = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
assert.equal(workerRequests.length, 3);
|
|
for (const [sessionId, gate] of gates) gate.resolve({ ok: true, stdout: `${sessionId}\n`, exitCode: 0 });
|
|
const result = await running;
|
|
assert.equal(result.groups.length, 3);
|
|
});
|
|
|
|
test("the per-chat exec lock is held for the whole fan-out", async () => {
|
|
const gate = deferred();
|
|
const { bridge, chat } = createBridge({ sessionIds: ["ssh-1", "ssh-2", "ssh-3", "ssh-4"], reply: () => gate.promise });
|
|
const running = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
const blocked = await bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-4", command: "pwd", chatSessionId: chat });
|
|
assert.equal(blocked.ok, false);
|
|
assert.equal(blocked.code, "COMMAND_ALREADY_RUNNING");
|
|
gate.resolve({ ok: true, stdout: "x\n", exitCode: 0 });
|
|
assert.equal((await running).ok, true);
|
|
});
|
|
|
|
test("an unknown, out-of-scope or busy session cancels the whole call before anything is sent", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge();
|
|
bridge.reserveSessionExecution("ssh-2", "exec");
|
|
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat, {
|
|
sessionIds: '["ssh-1","ssh-2","ghost"]',
|
|
}));
|
|
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /^nothing was sent\. 2 of 3 targets cannot run this command:/);
|
|
assert.match(result.error, /- ssh-2 \(web2\): Session already has .* in progress/);
|
|
assert.match(result.error, /- ghost: Session "ghost" is not in the current scope\./);
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("the command blocklist applies to the whole fan-out", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge();
|
|
bridge.setCommandBlocklist(["forbidden-word"]);
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat, { command: "echo forbidden-word" }));
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /^nothing was sent\. 3 of 3 targets cannot run this command:/);
|
|
assert.match(result.error, /Command blocked by safety policy/);
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("observer mode refuses and sends nothing", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge({ mode: "observer" });
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /observer/);
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("a chat session is required", async () => {
|
|
const { bridge, workerRequests } = createBridge();
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", { command: "uptime", sessionIds: '["ssh-1","ssh-2"]' });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("invalid input is rejected", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge();
|
|
for (const sessionIds of ["nope", "[]", '["ssh-1"]', '["ssh-1","ssh-1"]']) {
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat, { sessionIds }));
|
|
assert.equal(result.ok, false, sessionIds);
|
|
}
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("confirm mode asks once for all hosts and runs only after approval", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge({ mode: "confirm" });
|
|
const approvals = captureApprovals(bridge);
|
|
|
|
const pending = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
assert.equal(approvals.length, 1);
|
|
assert.equal(approvals[0].toolName, "netcatty/execBulk");
|
|
assert.deepEqual(approvals[0].args, {
|
|
command: "uptime",
|
|
sessions: ["ssh-1 (web1)", "ssh-2 (web2)", "ssh-3 (web3)"],
|
|
});
|
|
assert.equal(approvals[0].allowSession, false);
|
|
assert.equal(workerRequests.length, 0, "nothing runs before approval");
|
|
|
|
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
|
|
const result = await pending;
|
|
assert.equal(result.ok, true);
|
|
assert.equal(workerRequests.length, 3);
|
|
});
|
|
|
|
test("a denied approval sends nothing and frees the sessions", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge({ mode: "confirm" });
|
|
const approvals = captureApprovals(bridge);
|
|
const pending = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, false);
|
|
const result = await pending;
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /denied/i);
|
|
assert.equal(workerRequests.length, 0);
|
|
|
|
// Claims were released: a normal exec on one of the sessions still works.
|
|
bridge.setPermissionMode("auto");
|
|
const single = await bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-1", command: "pwd", chatSessionId: chat });
|
|
assert.equal(single.ok, true);
|
|
});
|
|
|
|
test("remembered grants cannot approve a fan-out", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge({ mode: "confirm" });
|
|
const approvals = captureApprovals(bridge);
|
|
bridge.setPermissionGrants([
|
|
{ id: "g1", capabilityId: "terminal.executeBulk", sessionPattern: "*", createdAt: Date.now() },
|
|
{ id: "g2", capabilityId: "terminal.execute", sessionPattern: "ssh-1", createdAt: Date.now() },
|
|
]);
|
|
const pending = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
assert.equal(approvals.length, 1, "approval is still required");
|
|
assert.equal(workerRequests.length, 0);
|
|
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
|
|
await pending;
|
|
});
|
|
|
|
test("session-wide approval never covers a fan-out, and never sweeps a pending one", async () => {
|
|
const { bridge, workerRequests } = createBridge({
|
|
chat: bridgeExternalChat(),
|
|
sessionIds: ["ssh-1", "ssh-2", "ssh-3", "ssh-4"],
|
|
mode: "confirm",
|
|
});
|
|
const chat = bridge.EXTERNAL_MCP_CHAT_SESSION_ID;
|
|
const socket = new EventEmitter();
|
|
socket.destroyed = false;
|
|
bridge.setExternalMcpHooks({ isEnabled: () => true, recordActivity() {} });
|
|
bridge.attachExternalMcpClient(socket);
|
|
const approvals = captureApprovals(bridge);
|
|
|
|
// 1. A bulk request from this external client: no session-wide option is offered.
|
|
const bulk = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat), { externalSocket: socket });
|
|
await tick();
|
|
assert.equal(approvals.length, 1);
|
|
assert.equal(approvals[0].allowSession, false);
|
|
|
|
// 2. A single exec from the same client is offered session approval and gets it.
|
|
const single = bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-4", command: "pwd", chatSessionId: chat }, { externalSocket: socket });
|
|
await tick();
|
|
assert.equal(approvals.length, 2);
|
|
assert.equal(approvals[1].allowSession, true);
|
|
bridge.resolveApprovalFromRenderer(approvals[1].approvalId, true, "session");
|
|
assert.equal((await single).ok, true);
|
|
|
|
// 3. The pending fan-out was not swept into that session approval.
|
|
let bulkSettled = false;
|
|
bulk.then(() => { bulkSettled = true; });
|
|
await tick();
|
|
assert.equal(bulkSettled, false, "fan-out still waits for its own approval");
|
|
assert.equal(workerRequests.filter((request) => request.payload.command === "uptime").length, 0);
|
|
|
|
// 4. Even a session-scoped answer to the fan-out itself is treated as one-off.
|
|
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true, "session");
|
|
assert.equal((await bulk).ok, true);
|
|
// 5. A client whose ONLY session-scoped answer was to a fan-out is not session-approved
|
|
// for other writes either.
|
|
const other = new EventEmitter();
|
|
other.destroyed = false;
|
|
bridge.attachExternalMcpClient(other);
|
|
const bulkOther = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat), { externalSocket: other });
|
|
await tick();
|
|
assert.equal(approvals.length, 3);
|
|
bridge.resolveApprovalFromRenderer(approvals[2].approvalId, true, "session");
|
|
assert.equal((await bulkOther).ok, true);
|
|
const later = bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-4", command: "pwd", chatSessionId: chat }, { externalSocket: other });
|
|
await tick();
|
|
assert.equal(approvals.length, 4, "a later single exec on that client still asks");
|
|
bridge.resolveApprovalFromRenderer(approvals[3].approvalId, false);
|
|
assert.equal((await later).ok, false);
|
|
|
|
// 6. The next fan-out on the first client asks again as well.
|
|
const again = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat), { externalSocket: socket });
|
|
await tick();
|
|
assert.equal(approvals.length, 5, "the next fan-out asks again");
|
|
bridge.resolveApprovalFromRenderer(approvals[4].approvalId, false);
|
|
assert.equal((await again).ok, false);
|
|
});
|
|
|
|
function bridgeExternalChat() {
|
|
return require("../cli/externalMcpDiscoveryPath.cjs").EXTERNAL_MCP_CHAT_SESSION_ID;
|
|
}
|
|
|
|
test("a session that is closing or disconnected is reported, not run", async () => {
|
|
const { bridge, workerRequests, chat } = createBridge();
|
|
bridge.updateSessionMetadata([
|
|
{ sessionId: "ssh-1", protocol: "ssh", label: "web1", connected: true },
|
|
{ sessionId: "ssh-2", protocol: "ssh", label: "web2", connected: false },
|
|
{ sessionId: "ssh-3", protocol: "ssh", label: "web3", connected: true },
|
|
], chat);
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /- ssh-2 \(web2\): Session "ssh-2" is not connected\./);
|
|
assert.equal(workerRequests.length, 0);
|
|
});
|
|
|
|
test("worker-hosted sessions are fully validated before any host receives the command", async () => {
|
|
const { bridge, workerRequests, prechecks, chat } = createBridge({
|
|
refuse: (sessionId) => (sessionId === "ssh-2"
|
|
? "AI execution is not supported for this local shell executable. Configure the local terminal to use bash/zsh/sh, fish, PowerShell/pwsh, or cmd.exe."
|
|
: null),
|
|
});
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /^nothing was sent\. 1 of 3 targets cannot run this command:/);
|
|
assert.match(result.error, /- ssh-2 \(web2\): AI execution is not supported/);
|
|
assert.equal(prechecks.length, 3, "every worker session is prechecked");
|
|
assert.equal(workerRequests.length, 0, "no host receives the command");
|
|
});
|
|
|
|
test("the precheck sends no command and the real run follows only after all prechecks pass", async () => {
|
|
const order = [];
|
|
const { bridge, workerRequests, prechecks, chat } = createBridge({
|
|
reply: (sessionId) => { order.push(`exec:${sessionId}`); return { ok: true, stdout: "x\n", exitCode: 0 }; },
|
|
refuse: (sessionId) => { order.push(`precheck:${sessionId}`); return null; },
|
|
});
|
|
const result = await bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
assert.equal(result.ok, true);
|
|
assert.equal(prechecks.length, 6, "validated before and again after approval");
|
|
assert.equal(workerRequests.length, 3);
|
|
assert.ok(order.slice(0, 6).every((entry) => entry.startsWith("precheck:")));
|
|
assert.ok(order.slice(6).every((entry) => entry.startsWith("exec:")));
|
|
});
|
|
|
|
test("the backstop deadline cancels the chat's foreground execs inside the worker too", async () => {
|
|
const realSetTimeout = global.setTimeout;
|
|
const timers = [];
|
|
global.setTimeout = (fn, ms, ...rest) => {
|
|
const handle = realSetTimeout(fn, ms, ...rest);
|
|
timers.push({ fn, ms, handle });
|
|
return handle;
|
|
};
|
|
try {
|
|
const { bridge, workerMessages, chat } = createBridge({
|
|
reply: (sessionId) => (sessionId === "ssh-3" ? new Promise(() => {}) : { ok: true, stdout: "ok\n", exitCode: 0 }),
|
|
});
|
|
const running = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
await tick();
|
|
const backstop = timers.find((timer) => timer.ms === 30000 + 3000);
|
|
assert.ok(backstop, "backstop is armed at command timeout + grace");
|
|
backstop.fn();
|
|
const result = await running;
|
|
assert.deepEqual(workerMessages, [{ channel: "netcatty:ai:exec:cancel", payload: { chatSessionId: chat } }]);
|
|
const timeout = result.groups.find((group) => group.status === "timeout");
|
|
assert.deepEqual(timeout.hosts.map((host) => host.sessionId), ["ssh-3"]);
|
|
// The chat lock was released, so the next command is accepted.
|
|
const single = await bridge.dispatchBuiltinRpc("netcatty/exec", { sessionId: "ssh-1", command: "pwd", chatSessionId: chat });
|
|
assert.equal(single.ok, true);
|
|
} finally {
|
|
global.setTimeout = realSetTimeout;
|
|
}
|
|
});
|
|
|
|
test("confirm mode: no probe reaches the worker before approval, and none at all when denied", async () => {
|
|
const approved = createBridge({ mode: "confirm" });
|
|
const approvals = captureApprovals(approved.bridge);
|
|
const pending = approved.bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(approved.chat));
|
|
await tick();
|
|
assert.equal(approvals.length, 1);
|
|
assert.equal(approved.prechecks.length, 3);
|
|
assert.ok(approved.prechecks.every((payload) => payload.probe === false), "pre-approval prechecks are non-probing");
|
|
approved.bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
|
|
assert.equal((await pending).ok, true);
|
|
assert.equal(approved.prechecks.length, 6);
|
|
assert.ok(approved.prechecks.slice(3).every((payload) => payload.probe === undefined), "after approval the full precheck runs");
|
|
|
|
const denied = createBridge({ mode: "confirm" });
|
|
const deniedApprovals = captureApprovals(denied.bridge);
|
|
const deniedCall = denied.bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(denied.chat));
|
|
await tick();
|
|
denied.bridge.resolveApprovalFromRenderer(deniedApprovals[0].approvalId, false);
|
|
assert.equal((await deniedCall).ok, false);
|
|
assert.equal(denied.prechecks.length, 3);
|
|
assert.ok(denied.prechecks.every((payload) => payload.probe === false), "a denied call never probes");
|
|
assert.equal(denied.workerRequests.length, 0);
|
|
});
|
|
|
|
test("switching to observer after the prompt appeared refuses the approved call and touches no host", async () => {
|
|
const { bridge, workerRequests, prechecks, chat } = createBridge({ mode: "confirm" });
|
|
const approvals = captureApprovals(bridge);
|
|
const pending = bridge.dispatchBuiltinRpc("netcatty/execBulk", bulkParams(chat));
|
|
await tick();
|
|
assert.equal(approvals.length, 1);
|
|
bridge.setPermissionMode("observer");
|
|
bridge.resolveApprovalFromRenderer(approvals[0].approvalId, true);
|
|
const result = await pending;
|
|
assert.equal(result.ok, false);
|
|
assert.match(result.error, /observer/);
|
|
assert.equal(workerRequests.length, 0, "no command reached any host");
|
|
assert.ok(prechecks.every((payload) => payload.probe === false), "and no host was probed");
|
|
});
|