mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 00:20:45 +00:00
* fix(terminal): close sessions when their owning renderer is destroyed * test(terminal): keep a shared SSH transport when a copied window closes Closing a child window must drop only the shells that window owns. Cover several tabs on one connection split across the main window and the copied window, for both the in-process lifetime tracker and the worker close path. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
647 lines
23 KiB
JavaScript
647 lines
23 KiB
JavaScript
const test = require("node:test");
|
|
const assert = require("node:assert/strict");
|
|
const Module = require("node:module");
|
|
const { FLOW_HIGH_WATER_MARK } = require("./terminalFlowAck.cjs");
|
|
|
|
class FakePty {
|
|
constructor() {
|
|
this.pid = 4242;
|
|
this.dataHandlers = [];
|
|
this.exitHandlers = [];
|
|
this.paused = false;
|
|
}
|
|
|
|
onData(handler) {
|
|
this.dataHandlers.push(handler);
|
|
}
|
|
|
|
onExit(handler) {
|
|
this.exitHandlers.push(handler);
|
|
}
|
|
|
|
write() {}
|
|
|
|
resize() {}
|
|
|
|
kill() {}
|
|
|
|
pause() {
|
|
this.paused = true;
|
|
}
|
|
|
|
resume() {
|
|
this.paused = false;
|
|
}
|
|
|
|
emitData(data) {
|
|
for (const handler of this.dataHandlers) handler(data);
|
|
}
|
|
|
|
emitExit(evt = { exitCode: 0, signal: 0 }) {
|
|
for (const handler of this.exitHandlers) handler(evt);
|
|
}
|
|
}
|
|
|
|
function loadBridgeWithFakes(spawns, sentries) {
|
|
const bridgePath = require.resolve("./terminalBridge.cjs");
|
|
delete require.cache[bridgePath];
|
|
|
|
const originalLoad = Module._load;
|
|
Module._load = function patchedLoad(request, parent, isMain) {
|
|
if (request === "node-pty") {
|
|
return {
|
|
spawn(...spawnArgs) {
|
|
const pty = new FakePty();
|
|
pty.spawnArgs = spawnArgs;
|
|
spawns.push(pty);
|
|
return pty;
|
|
},
|
|
};
|
|
}
|
|
|
|
if (request === "serialport") {
|
|
return { SerialPort: class { static async list() { return []; } } };
|
|
}
|
|
|
|
if (request === "./nodePtySpawnHelperPermissions.cjs") {
|
|
return { ensureNodePtySpawnHelperExecutable() {} };
|
|
}
|
|
|
|
if (request === "./zmodemHelper.cjs") {
|
|
return {
|
|
createZmodemSentry(options) {
|
|
const sentry = {
|
|
active: false,
|
|
consumeCalls: [],
|
|
consume(data) {
|
|
this.consumeCalls.push(data);
|
|
const raw = Buffer.isBuffer(data) ? data : Buffer.from(String(data));
|
|
options.onData(raw);
|
|
},
|
|
isActive() {
|
|
return this.active;
|
|
},
|
|
cancel() {},
|
|
};
|
|
sentries.push(sentry);
|
|
return sentry;
|
|
},
|
|
};
|
|
}
|
|
|
|
return originalLoad.call(this, request, parent, isMain);
|
|
};
|
|
|
|
try {
|
|
return require("./terminalBridge.cjs");
|
|
} finally {
|
|
Module._load = originalLoad;
|
|
}
|
|
}
|
|
|
|
test("WSL launch arguments use Linux home unless a working directory is explicit", () => {
|
|
const bridge = loadBridgeWithFakes([], []);
|
|
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
|
|
|
|
try {
|
|
Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });
|
|
assert.deepEqual(
|
|
bridge.getWslLaunchArgs("C:\\Windows\\System32\\wsl.exe", ["-d", "Ubuntu"], false),
|
|
["-d", "Ubuntu", "--cd", "~"],
|
|
);
|
|
assert.deepEqual(
|
|
bridge.getWslLaunchArgs("C:\\Windows\\System32\\wsl.exe", ["-d", "Ubuntu"], true),
|
|
["-d", "Ubuntu"],
|
|
);
|
|
assert.deepEqual(
|
|
bridge.getWslLaunchArgs(
|
|
"C:\\Windows\\System32\\wsl.exe",
|
|
["-d", "Ubuntu", "--exec", "zsh", "-l"],
|
|
false,
|
|
),
|
|
["-d", "Ubuntu", "--cd", "~", "--exec", "zsh", "-l"],
|
|
);
|
|
} finally {
|
|
Object.defineProperty(process, "platform", platformDescriptor);
|
|
}
|
|
});
|
|
|
|
test("WSL default directory stays outside the Linux command and option values", () => {
|
|
const bridge = loadBridgeWithFakes([], []);
|
|
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
|
|
const distroGuid = "{01234567-89ab-cdef-0123-456789abcdef}";
|
|
const cases = [
|
|
[[distroGuid], [distroGuid, "--cd", "~"]],
|
|
[[distroGuid, "~"], [distroGuid, "~"]],
|
|
[[distroGuid, "--", "zsh"], [distroGuid, "--cd", "~", "--", "zsh"]],
|
|
[["~"], ["~"]],
|
|
[["~", "-d", "Ubuntu", "--", "zsh"], ["~", "-d", "Ubuntu", "--", "zsh"]],
|
|
[["-d", "Ubuntu", "--", "zsh", "-l"], ["-d", "Ubuntu", "--cd", "~", "--", "zsh", "-l"]],
|
|
[["-e", "zsh", "-l"], ["--cd", "~", "-e", "zsh", "-l"]],
|
|
[["--shell-type", "login", "zsh"], ["--shell-type", "login", "--cd", "~", "zsh"]],
|
|
[["--distribution-id", "{distro-id}"], ["--distribution-id", "{distro-id}", "--cd", "~"]],
|
|
[["--user", "root", "echo", "--cd"], ["--user", "root", "--cd", "~", "echo", "--cd"]],
|
|
[["--exec", "echo", "--cd=/tmp"], ["--cd", "~", "--exec", "echo", "--cd=/tmp"]],
|
|
[["--cd", "/tmp", "--", "zsh"], ["--cd", "/tmp", "--", "zsh"]],
|
|
[["--cd=/tmp", "-e", "zsh"], ["--cd=/tmp", "-e", "zsh"]],
|
|
];
|
|
try {
|
|
Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });
|
|
for (const [args, expected] of cases) {
|
|
const input = Object.freeze([...args]);
|
|
assert.deepEqual(bridge.getWslLaunchArgs("wsl.exe", input, false), expected, JSON.stringify(args));
|
|
assert.deepEqual(bridge.getWslLaunchArgs("wsl.exe", input, true), args);
|
|
assert.deepEqual(bridge.getWslLaunchArgs("powershell.exe", input, false), args);
|
|
}
|
|
Object.defineProperty(process, "platform", { ...platformDescriptor, value: "linux" });
|
|
assert.deepEqual(bridge.getWslLaunchArgs("/usr/bin/wsl", [], false), []);
|
|
} finally {
|
|
Object.defineProperty(process, "platform", platformDescriptor);
|
|
}
|
|
});
|
|
|
|
test("WSL local sessions pass the home directory option to the spawned process", async () => {
|
|
const spawns = [];
|
|
const bridge = loadBridgeWithFakes(spawns, []);
|
|
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
|
|
try {
|
|
Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });
|
|
bridge.init({
|
|
sessions: new Map(),
|
|
electronModule: { webContents: { fromId: () => ({ send() {} }) } },
|
|
});
|
|
const shellArgs = ["-d", "Ubuntu", "--", "zsh", "-l"];
|
|
const payload = { shell: "C:\\Windows\\System32\\wsl.exe", shellArgs };
|
|
await bridge.startLocalSession({ sender: { id: 7 } }, { ...payload, sessionId: "wsl-home" });
|
|
assert.deepEqual(spawns[0].spawnArgs[1], ["-d", "Ubuntu", "--cd", "~", "--", "zsh", "-l"]);
|
|
assert.deepEqual(shellArgs, ["-d", "Ubuntu", "--", "zsh", "-l"]);
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ ...payload, sessionId: "wsl-explicit-cwd", cwd: process.cwd() },
|
|
);
|
|
assert.deepEqual(spawns[1].spawnArgs[1], shellArgs);
|
|
assert.equal(spawns[1].spawnArgs[2].cwd, process.cwd());
|
|
} finally {
|
|
Object.defineProperty(process, "platform", platformDescriptor);
|
|
}
|
|
});
|
|
|
|
test("Windows local terminals enable the bundled ConPTY implementation required for clear", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
|
|
|
|
try {
|
|
Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId: () => ({ send() {} }),
|
|
},
|
|
},
|
|
});
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "windows-clear", shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" },
|
|
);
|
|
|
|
assert.equal(spawns.length, 1);
|
|
assert.equal(spawns[0].spawnArgs[2].useConptyDll, true);
|
|
} finally {
|
|
Object.defineProperty(process, "platform", platformDescriptor);
|
|
}
|
|
});
|
|
|
|
test("local terminal buffers incoming flood while renderer flow is paused", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-flood", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
bridge.setSessionFlowPaused(
|
|
{ sender: {} },
|
|
{ sessionId: "local-flood", paused: true },
|
|
);
|
|
spawns[0].emitData(Buffer.from("ordinary flood"));
|
|
|
|
assert.equal(sentries[0].consumeCalls.length, 1);
|
|
assert.deepEqual(sent, []);
|
|
bridge.setSessionFlowPaused(
|
|
{ sender: {} },
|
|
{ sessionId: "local-flood", paused: false },
|
|
);
|
|
assert.deepEqual(sent.map((item) => item.payload.data), ["ordinary flood"]);
|
|
|
|
sentries[0].active = true;
|
|
spawns[0].emitData(Buffer.from("transfer bytes"));
|
|
|
|
assert.equal(sentries[0].consumeCalls.length, 2);
|
|
});
|
|
|
|
test("local terminal keeps source paused while paced backlog absorbs fresh flood", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-flood-paced-fresh", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
bridge.setSessionFlowPaused(
|
|
{ sender: {} },
|
|
{ sessionId: "local-flood-paced-fresh", paused: true },
|
|
);
|
|
spawns[0].emitData(Buffer.from("a".repeat(FLOW_HIGH_WATER_MARK + 10)));
|
|
|
|
const session = sessions.get("local-flood-paced-fresh");
|
|
assert.equal(spawns[0].paused, true);
|
|
assert.equal(session.flowState.bufferedBytes, FLOW_HIGH_WATER_MARK + 10);
|
|
assert.deepEqual(sent, []);
|
|
|
|
bridge.setSessionFlowPaused(
|
|
{ sender: {} },
|
|
{ sessionId: "local-flood-paced-fresh", paused: false },
|
|
);
|
|
|
|
assert.equal(sent.length, 1);
|
|
assert.equal(spawns[0].paused, true);
|
|
|
|
spawns[0].emitData(Buffer.from("b".repeat(FLOW_HIGH_WATER_MARK)));
|
|
|
|
assert.equal(sent.length, 1);
|
|
assert.equal(spawns[0].paused, true);
|
|
assert.ok(session.flowState.bufferedBytes >= FLOW_HIGH_WATER_MARK);
|
|
});
|
|
|
|
test("closing a local terminal discards buffered output instead of flushing it", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-flood-close", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
spawns[0].emitData(Buffer.from("pending tail"));
|
|
bridge.closeSession({ sender: {} }, { sessionId: "local-flood-close" });
|
|
|
|
assert.deepEqual(sent, [{
|
|
channel: "netcatty:exit",
|
|
payload: { sessionId: "local-flood-close", exitCode: 0, reason: "closed" },
|
|
}]);
|
|
});
|
|
|
|
test("app cleanup discards buffered output instead of flushing it", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-flood-cleanup", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
spawns[0].emitData(Buffer.from("pending tail"));
|
|
bridge.cleanupAllSessions();
|
|
|
|
assert.deepEqual(sent, []);
|
|
assert.equal(sessions.size, 0);
|
|
});
|
|
|
|
test("local terminal exit waits for paced buffered output drain", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-flood-exit", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
const output = "x".repeat(2_400_000);
|
|
spawns[0].emitData(Buffer.from(output));
|
|
spawns[0].emitExit({ exitCode: 0, signal: 0 });
|
|
|
|
assert.equal(sent.some((item) => item.channel === "netcatty:exit"), false);
|
|
|
|
bridge.ackSessionFlow(
|
|
{ sender: {} },
|
|
{ sessionId: "local-flood-exit", bytes: output.length },
|
|
);
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
|
|
const data = sent
|
|
.filter((item) => item.channel === "netcatty:data")
|
|
.map((item) => item.payload.data)
|
|
.join("");
|
|
assert.equal(data, output);
|
|
assert.equal(sent.some((item) => item.channel === "netcatty:exit"), true);
|
|
assert.equal(sessions.has("local-flood-exit"), false);
|
|
});
|
|
|
|
test("local terminal exit completes while renderer flow is paused", async () => {
|
|
const spawns = [];
|
|
const sentries = [];
|
|
const sent = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, sentries);
|
|
|
|
bridge.init({
|
|
sessions,
|
|
electronModule: {
|
|
webContents: {
|
|
fromId() {
|
|
return { send: (channel, payload) => sent.push({ channel, payload }) };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
await bridge.startLocalSession(
|
|
{ sender: { id: 7 } },
|
|
{ sessionId: "local-paused-exit", shell: "/bin/sh", cols: 80, rows: 24 },
|
|
);
|
|
|
|
bridge.setSessionFlowPaused(
|
|
{ sender: {} },
|
|
{ sessionId: "local-paused-exit", paused: true },
|
|
);
|
|
spawns[0].emitData(Buffer.from("pending output"));
|
|
spawns[0].emitExit({ exitCode: 0, signal: 0 });
|
|
|
|
assert.equal(sent.some((item) => item.channel === "netcatty:data"), false);
|
|
assert.equal(sent.some((item) => item.channel === "netcatty:exit"), true);
|
|
assert.equal(sessions.has("local-paused-exit"), false);
|
|
});
|
|
|
|
test("a window closed while preparing the local environment does not spawn a PTY", async () => {
|
|
const spawns = [];
|
|
const bridge = loadBridgeWithFakes(spawns, []);
|
|
let destroyed = false;
|
|
const pending = bridge.startLocalSession(
|
|
{ sender: { id: 7, isDestroyed: () => destroyed } },
|
|
{ sessionId: "closed-before-spawn", shell: "/bin/sh" },
|
|
);
|
|
destroyed = true;
|
|
await assert.rejects(pending, /window closed before startup/);
|
|
assert.equal(spawns.length, 0);
|
|
});
|
|
|
|
async function withPendingLocalPath(run) {
|
|
const shellUtils = require("./ai/shellUtils.cjs");
|
|
const originalResolve = shellUtils.resolveWindowsLivePath;
|
|
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
|
|
const resolvers = [];
|
|
const spawns = [];
|
|
const sessions = new Map();
|
|
const bridge = loadBridgeWithFakes(spawns, []);
|
|
bridge.init({ sessions, electronModule: { webContents: { fromId: () => null } } });
|
|
try {
|
|
Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
|
|
shellUtils.resolveWindowsLivePath = () => new Promise((resolve) => resolvers.push(resolve));
|
|
await run({ bridge, resolvers, spawns, sessions });
|
|
} finally {
|
|
shellUtils.resolveWindowsLivePath = originalResolve;
|
|
Object.defineProperty(process, "platform", platformDescriptor);
|
|
}
|
|
}
|
|
|
|
test("closing a local tab during PATH refresh prevents the pending PTY spawn", async () => {
|
|
await withPendingLocalPath(async ({ bridge, resolvers, spawns, sessions }) => {
|
|
const event = { sender: { id: 7, isDestroyed: () => false } };
|
|
const payload = { sessionId: "closed-pending-path", bootEpoch: 1, shell: "C:\\Windows\\cmd.exe" };
|
|
const pending = bridge.startLocalSession(event, payload);
|
|
const rejected = assert.rejects(pending, { code: "NETCATTY_BOOT_SUPERSEDED" });
|
|
assert.equal(resolvers.length, 1);
|
|
bridge.closeSession(event, payload);
|
|
resolvers[0]("C:\\Windows\\System32");
|
|
await rejected;
|
|
assert.equal(spawns.length, 0);
|
|
assert.equal(sessions.has(payload.sessionId), false);
|
|
});
|
|
});
|
|
|
|
test("a stale close and old PATH completion cannot cancel a newer local boot", async () => {
|
|
await withPendingLocalPath(async ({ bridge, resolvers, spawns, sessions }) => {
|
|
const event = { sender: { id: 7, isDestroyed: () => false } };
|
|
const payload = { sessionId: "restarted-pending-path", shell: "C:\\Windows\\cmd.exe" };
|
|
const older = bridge.startLocalSession(event, { ...payload, bootEpoch: 1 });
|
|
const rejected = assert.rejects(older, { code: "NETCATTY_BOOT_SUPERSEDED" });
|
|
const newer = bridge.startLocalSession(event, { ...payload, bootEpoch: 2 });
|
|
assert.equal(resolvers.length, 2);
|
|
assert.deepEqual(bridge.closeSession(event, { ...payload, bootEpoch: 1 }), {
|
|
skipped: true, reason: "boot-epoch-mismatch",
|
|
});
|
|
resolvers[0]("C:\\old");
|
|
await rejected;
|
|
const { hasPendingBootAfter } = require("./sessionBootEpoch.cjs");
|
|
assert.equal(hasPendingBootAfter(payload.sessionId, 1), true);
|
|
resolvers[1]("C:\\new");
|
|
await newer;
|
|
assert.equal(spawns.length, 1);
|
|
assert.equal(sessions.get(payload.sessionId)?.bootEpoch, 2);
|
|
bridge.closeSession(event, { ...payload, bootEpoch: 1 });
|
|
assert.equal(sessions.get(payload.sessionId)?.bootEpoch, 2);
|
|
bridge.closeSession(event, { ...payload, bootEpoch: 2 });
|
|
});
|
|
});
|
|
|
|
for (const closeChannel of ["netcatty:close", "netcatty:close:await"]) {
|
|
test(`worker ${closeChannel} cancels a local start before PATH refresh can spawn it`, async () => {
|
|
await withPendingLocalPath(async ({ bridge, resolvers, spawns, sessions }) => {
|
|
const { createTerminalWorkerRuntime } = require("../terminalWorker/runtime.cjs");
|
|
const messages = [];
|
|
let receiveMessage;
|
|
const parentPort = {
|
|
on: (_channel, listener) => { receiveMessage = listener; },
|
|
postMessage: (message) => messages.push(message),
|
|
};
|
|
createTerminalWorkerRuntime({
|
|
parentPort,
|
|
registerBridges: (ipcMain) => bridge.registerHandlers(ipcMain),
|
|
}).start();
|
|
const payload = { sessionId: `worker-pending-${closeChannel}`, shell: "C:\\Windows\\cmd.exe" };
|
|
const start = (bootEpoch) => receiveMessage({
|
|
kind: "request", requestId: `start-${bootEpoch}`, channel: "netcatty:local:start",
|
|
webContentsId: 7, payload: { ...payload, bootEpoch },
|
|
});
|
|
const close = (bootEpoch) => receiveMessage({
|
|
kind: closeChannel.endsWith(":await") ? "request" : "send",
|
|
requestId: `close-${bootEpoch}`, channel: closeChannel,
|
|
webContentsId: 7, payload: { ...payload, bootEpoch },
|
|
});
|
|
const drainMessages = () => new Promise((resolve) => setImmediate(resolve));
|
|
start(1);
|
|
await drainMessages();
|
|
assert.equal(resolvers.length, 1, "the real bridge is waiting for PATH inside the worker queue");
|
|
close(1);
|
|
resolvers[0]("C:\\Windows\\System32");
|
|
await drainMessages();
|
|
await drainMessages();
|
|
assert.equal(spawns.length, 0, "a closed tab must not run shell startup scripts");
|
|
assert.equal(sessions.has(payload.sessionId), false);
|
|
assert.match(messages.find((message) => message.requestId === "start-1")?.error ?? "", /closed or superseded/);
|
|
if (closeChannel.endsWith(":await")) {
|
|
assert.equal(messages.find((message) => message.requestId === "close-1")?.result?.closed, false);
|
|
}
|
|
|
|
start(2);
|
|
await drainMessages();
|
|
assert.equal(resolvers.length, 2);
|
|
close(1); // A delayed old close must not abort the replacement's PATH wait.
|
|
resolvers[1]("C:\\Windows\\System32");
|
|
await drainMessages();
|
|
await drainMessages();
|
|
assert.equal(spawns.length, 1);
|
|
assert.equal(sessions.get(payload.sessionId)?.bootEpoch, 2);
|
|
close(2);
|
|
await drainMessages();
|
|
await drainMessages();
|
|
assert.equal(sessions.has(payload.sessionId), false);
|
|
});
|
|
});
|
|
}
|
|
|
|
test("worker replacements abort pending and skip superseded queued local starts", async () => {
|
|
await withPendingLocalPath(async ({ bridge, resolvers, spawns, sessions }) => {
|
|
const { createTerminalWorkerRuntime } = require("../terminalWorker/runtime.cjs");
|
|
const messages = [];
|
|
let receiveMessage;
|
|
createTerminalWorkerRuntime({
|
|
parentPort: {
|
|
on: (_channel, listener) => { receiveMessage = listener; },
|
|
postMessage: (message) => messages.push(message),
|
|
},
|
|
registerBridges: (ipcMain) => bridge.registerHandlers(ipcMain),
|
|
}).start();
|
|
const payload = { sessionId: "worker-replaced-path", shell: "C:\\Windows\\cmd.exe" };
|
|
const start = (bootEpoch, requestId) => receiveMessage({
|
|
kind: "request", requestId, channel: "netcatty:local:start",
|
|
webContentsId: 7, payload: { ...payload, bootEpoch },
|
|
});
|
|
const drainMessages = () => new Promise((resolve) => setImmediate(resolve));
|
|
start(1, "old-start");
|
|
await drainMessages();
|
|
start(2, "queued-replacement");
|
|
start(3, "replacement");
|
|
resolvers[0]("C:\\Windows\\System32");
|
|
await drainMessages();
|
|
await drainMessages();
|
|
assert.equal(spawns.length, 0, "a superseded PATH wait must not run shell startup scripts");
|
|
assert.equal(resolvers.length, 2, "the replacement now owns the startup queue");
|
|
assert.match(messages.find((message) => message.requestId === "old-start")?.error ?? "", /closed or superseded/);
|
|
assert.match(messages.find((message) => message.requestId === "queued-replacement")?.error ?? "", /superseded/);
|
|
start(2, "stale-start");
|
|
receiveMessage({
|
|
kind: "send", channel: "netcatty:close", webContentsId: 7,
|
|
payload: { ...payload, bootEpoch: 2 },
|
|
});
|
|
resolvers[1]("C:\\Windows\\System32");
|
|
await drainMessages();
|
|
await drainMessages();
|
|
assert.equal(spawns.length, 1);
|
|
assert.equal(resolvers.length, 2, "a stale start must not even prepare a new environment");
|
|
assert.equal(sessions.get(payload.sessionId)?.bootEpoch, 3);
|
|
assert.match(messages.find((message) => message.requestId === "stale-start")?.error ?? "", /superseded/);
|
|
receiveMessage({
|
|
kind: "send", channel: "netcatty:close", webContentsId: 7,
|
|
payload: { ...payload, bootEpoch: 3 },
|
|
});
|
|
await drainMessages();
|
|
await drainMessages();
|
|
});
|
|
});
|
|
|
|
test("in-process local session is killed on renderer destruction without closing another renderer's PTY", async () => {
|
|
const EventEmitter = require("node:events");
|
|
const spawns = [];
|
|
const bridge = loadBridgeWithFakes(spawns, []);
|
|
const sessions = new Map();
|
|
const renderers = [7, 8].map(id => Object.assign(new EventEmitter(), { id, send() {} }));
|
|
bridge.init({ sessions, electronModule: { webContents: { fromId: id => renderers.find(r => r.id === id) } } });
|
|
await bridge.startLocalSession({ sender: renderers[0] }, { sessionId: "lifetime-local", shell: "/bin/sh", bootEpoch: 1 });
|
|
await bridge.startLocalSession({ sender: renderers[1] }, { sessionId: "lifetime-other", shell: "/bin/sh", bootEpoch: 1 });
|
|
let killed = 0;
|
|
spawns[0].kill = () => { killed++; };
|
|
renderers[0].emit("destroyed");
|
|
assert.equal(killed, 1);
|
|
assert.equal(sessions.has("lifetime-local"), false);
|
|
assert.equal(sessions.has("lifetime-other"), true);
|
|
bridge.closeSession({}, { sessionId: "lifetime-other" });
|
|
});
|